Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(onboarding): onboarding v4 (#5155)
teo81c767fff7d8
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex a0ce954738..054538ffad 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -57,6 +57,7 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/generic_email_domains","crates/import","crates/invite_email","crates/item_filters",@@ -223,6 +224,7 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/generic_email_domains","crates/import","crates/invite_email","crates/item_filters",@@ -370,6 +372,7 @@"crates/foreign_entity","crates/frecency","crates/fusionauth",+ "crates/generic_email_domains","crates/github","crates/invite_email","crates/ip_extractor",@@ -685,6 +688,7 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/generic_email_domains","crates/import","crates/invite_email","crates/item_filters",@@ -1420,6 +1424,7 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/generic_email_domains","crates/import","crates/invite_email","crates/ip_extractor",@@ -1543,6 +1548,7 @@"crates/foreign_entity","crates/frecency","crates/fusionauth",+ "crates/generic_email_domains","crates/github","crates/graphql_common","crates/graphql_email",@@ -2543,6 +2549,10 @@"crates/fusionauth","crates/workspace-hack"],+ "generic_email_domains": [+ "crates/generic_email_domains",+ "crates/workspace-hack"+ ],"github": ["crates/agent","crates/ai_toolset",@@ -3472,6 +3482,7 @@"crates/foreign_entity","crates/frecency","crates/fusionauth",+ "crates/generic_email_domains","crates/import","crates/invite_email","crates/item_filters",@@ -3578,6 +3589,7 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/generic_email_domains","crates/import","crates/invite_email","crates/item_filters",@@ -4157,6 +4169,7 @@"crates/connection_gateway_client","crates/connection_gateway_models","crates/cowlike",+ "crates/generic_email_domains","crates/import","crates/macro_auth","crates/macro_authorization",@@ -4551,6 +4564,7 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/generic_email_domains","crates/import","crates/invite_email","crates/item_filters",@@ -5502,6 +5516,7 @@"crates/entity_access_management","crates/filter_ast","crates/frecency",+ "crates/generic_email_domains","crates/invite_email","crates/item_filters","crates/kafka_util",diff --git a/Cargo.lock b/Cargo.lockindex a68c4c18d5..eb382b71fd 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5799,6 +5799,13 @@ dependencies = ["rustc-hash 2.1.2",]+[[package]]+name = "generic_email_domains"+version = "0.1.0"+dependencies = [+ "workspace-hack",+]+[[package]]name = "gethostname"version = "1.1.0"@@ -10090,6 +10097,7 @@ dependencies = ["anyhow","axum","chrono",+ "generic_email_domains","import","macro_authorization","macro_user_id",@@ -14226,6 +14234,7 @@ dependencies = ["chrono","contacts","entity_access",+ "generic_email_domains","macro_authorization","macro_db_migrator","macro_event_broker",diff --git a/Cargo.toml b/Cargo.tomlindex e1e8859d4a..5e7693469c 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -19,6 +19,7 @@ members = ["crates/embedding","crates/favorites","crates/foreign_entity",+ "crates/generic_email_domains","crates/graphql_common","crates/graphql_email","crates/graphql_notification",diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsxindex b41bf26473..717956c6ce 100644--- a/apps/web/src/components/app/Layout.tsx+++ b/apps/web/src/components/app/Layout.tsx@@ -45,7 +45,7 @@ import {SidebarVisibilityContext,} from '@components/app/sidebarVisibility';import { useIsAuthenticated } from '@core/auth';-import { ENABLE_NEW_ONBOARDING_V3 } from '@core/constant/featureFlags';+import { ENABLE_ONBOARDING_V4 } from '@core/constant/featureFlags';import { usePaywallState } from '@core/constant/PaywallState';import { isSoloSettings } from '@core/constant/SettingsState';import { attachGlobalDOMScope } from '@core/hotkey/hotkeys';@@ -284,9 +284,9 @@ function CollapsedSidebarIncomingCallWidget(props: {}/**- * Sends first-time desktop users into the split-screen onboarding at- * /setup. Fires from anywhere in the app (marketing SSO lands on /app, not- * /login), but never off auth/full-screen routes — /setup itself included.+ * Sends first-time desktop users into the onboarding flow at /onboarding.+ * Fires from anywhere in the app (marketing SSO lands on /app, not /login),+ * but never off auth/full-screen routes — /onboarding itself included.*/function NewOnboardingRedirect() {const userInfoQuery = useUserInfoQuery();@@ -294,7 +294,7 @@ function NewOnboardingRedirect() {const location = useLocation();createEffect(() => {- if (!ENABLE_NEW_ONBOARDING_V3 || isMobile() || isNativeMobilePlatform()) {+ if (!ENABLE_ONBOARDING_V4 || isMobile() || isNativeMobilePlatform()) {return;}const data = userInfoQuery.data;@@ -303,12 +303,14 @@ function NewOnboardingRedirect() {}if (AUTH_URLS.includes(location.pathname)) return;// Preserve the deep link the user arrived on (a shared doc, an invite):- // /setup carries it as ?next and its finish() returns there instead of+ // the flow carries it as ?next and its finish() returns there instead of// home. Base-relative so navigate() can resolve it against the router.const target =location.pathname.slice(ROUTER_BASE_CONCAT.length - 1) + location.search;navigate(- target === '/' ? '/setup' : `/setup?next=${encodeURIComponent(target)}`,+ target === '/'+ ? '/onboarding'+ : `/onboarding?next=${encodeURIComponent(target)}`,{ replace: true });});diff --git a/apps/web/src/components/icon/macro-brand-loader-2.svg b/apps/web/src/components/icon/macro-brand-loader-2.svgindex ca574512cc..f144ccbbfd 100644--- a/apps/web/src/components/icon/macro-brand-loader-2.svg+++ b/apps/web/src/components/icon/macro-brand-loader-2.svg@@ -1,89 +1,118 @@<svg fill="none" width="100%" height="100%" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="99" stroke-linejoin="round" stroke-width="0.4" viewBox="0 0 37 20" xmlns="http://www.w3.org/2000/svg">- <rect x="0" y="0" width="37" height="32" fill="var(--color-surface)" stroke="none"/>- <path fill="currentColor" fill-opacity="0.2" d="m20.51 15.501 3.3805-1.3255 12.693 11.996-3.378 1.3278z"/>- <path d="m23.89 14.176v4.5204"/>- <g transform="translate(0, -3)">- <animateTransform- keySplines="0.8 0 0.2 1; 0.8 0 0.2 1"- values="0, -3; 0, 14; 0, -3"- attributeName="transform"- repeatCount="indefinite"- keyTimes="0; 0.5; 1"- calcMode="spline"- type="translate"- begin="0.4s"- dur="4s"- />- <g stroke-dasharray="0.5, 1">- <path d="m23.89 14.176-3.3805 1.3255"/>- <path d="m23.89 14.176v-10.674"/>- <path d="m23.89 14.176 12.693 11.996"/>- </g>- <path fill="currentColor" fill-opacity="0.53" d="m23.89 3.5019-3.3805 1.3255v10.674l12.696 11.999 3.378-1.3278-1e-4 -10.674z"/>- <g>- <path d="m33.206 16.826-12.696-11.999"/>- <path d="m33.206 16.826 3.3779-1.3278"/>- <path d="m33.206 16.826v10.673"/>+ <!-- The animated bars slide past the column bases. The shapes hiding the+ overflow used to be painted in the surface color, which broke on any+ non-surface background (gradients, tinted panels). They are masks now:+ each group is masked by exactly the occluders that were painted after+ it, so the render is unchanged on plain surface and properly+ transparent everywhere else. -->+ <defs>+ <mask id="mbl2-r" maskUnits="userSpaceOnUse" x="-5" y="-5" width="50" height="40">+ <rect x="-5" y="-5" width="50" height="40" fill="#fff" stroke="none"/>+ <path fill="#000" stroke="none" d="m20.51 15.501-1.4402 0.0125v13.486h19v-2.8183l-1.486-0.0095-3.378 1.3278z"/>+ <path fill="#000" stroke="none" d="m6.4402 15.501-1.4402 0.0125v13.486h19v-2.8183l-1.486-0.0095-3.378 1.3278z"/>+ <path fill="#000" stroke="none" d="m0.41661 23.097-1.4166 0.012184v5.8906h11v-2.8184l-1.5462-0.012319-3.3834 1.33z"/>+ </mask>+ <mask id="mbl2-m" maskUnits="userSpaceOnUse" x="-5" y="-5" width="50" height="40">+ <rect x="-5" y="-5" width="50" height="40" fill="#fff" stroke="none"/>+ <path fill="#000" stroke="none" d="m6.4402 15.501-1.4402 0.0125v13.486h19v-2.8183l-1.486-0.0095-3.378 1.3278z"/>+ <path fill="#000" stroke="none" d="m0.41661 23.097-1.4166 0.012184v5.8906h11v-2.8184l-1.5462-0.012319-3.3834 1.33z"/>+ </mask>+ <mask id="mbl2-l" maskUnits="userSpaceOnUse" x="-5" y="-5" width="50" height="40">+ <rect x="-5" y="-5" width="50" height="40" fill="#fff" stroke="none"/>+ <path fill="#000" stroke="none" d="m0.41661 23.097-1.4166 0.012184v5.8906h11v-2.8184l-1.5462-0.012319-3.3834 1.33z"/>+ </mask>+ </defs>++ <g mask="url(#mbl2-r)">+ <path fill="currentColor" fill-opacity="0.2" d="m20.51 15.501 3.3805-1.3255 12.693 11.996-3.378 1.3278z"/>+ <path d="m23.89 14.176v4.5204"/>+ <g transform="translate(0, -3)">+ <animateTransform+ keySplines="0.8 0 0.2 1; 0.8 0 0.2 1"+ values="0, -3; 0, 14; 0, -3"+ attributeName="transform"+ repeatCount="indefinite"+ keyTimes="0; 0.5; 1"+ calcMode="spline"+ type="translate"+ begin="0.4s"+ dur="4s"+ />+ <g stroke-dasharray="0.5, 1">+ <path d="m23.89 14.176-3.3805 1.3255"/>+ <path d="m23.89 14.176v-10.674"/>+ <path d="m23.89 14.176 12.693 11.996"/>+ </g>+ <path fill="currentColor" fill-opacity="0.53" d="m23.89 3.5019-3.3805 1.3255v10.674l12.696 11.999 3.378-1.3278-1e-4 -10.674z"/>+ <g>+ <path d="m33.206 16.826-12.696-11.999"/>+ <path d="m33.206 16.826 3.3779-1.3278"/>+ <path d="m33.206 16.826v10.673"/>+ </g></g></g>- <path fill="var(--color-surface)" stroke="none" d="m20.51 15.501-1.4402 0.0125v13.486h19v-2.8183l-1.486-0.0095-3.378 1.3278z"/>- <path d="m20.51 15.501 12.696 11.999 3.378-1.3278"/>- <path fill="currentColor" fill-opacity="0.2" d="m6.4402 15.501 3.3805-1.3255 12.693 11.996-3.378 1.3278z"/>- <path d="m9.8207 14.176v4.5204"/>- <g transform="translate(0, -3)">- <animateTransform- keySplines="0.8 0 0.2 1; 0.8 0 0.2 1"- values="0, -3; 0, 14; 0, -3"- attributeName="transform"- repeatCount="indefinite"- keyTimes="0; 0.5; 1"- calcMode="spline"- type="translate"- begin="0.2s"- dur="4s"- />- <g stroke-dasharray="0.5, 1">- <path d="m9.8207 14.176-3.3805 1.3255"/>- <path d="m9.8207 14.176v-10.674"/>- <path d="m9.8207 14.176 12.693 11.996"/>- </g>- <path fill="currentColor" fill-opacity="0.53" d="m9.8207 3.50169-3.3805 1.3255v10.674l12.696 11.999 3.378-1.3278-5.8e-5 -10.674z"/>- <g>- <path d="m19.136 16.826-12.696-11.999"/>- <path d="m19.136 16.826 3.3779-1.3279"/>- <path d="m19.136 16.826v10.673"/>+ <g mask="url(#mbl2-m)">+ <path d="m20.51 15.501 12.696 11.999 3.378-1.3278"/>++ <path fill="currentColor" fill-opacity="0.2" d="m6.4402 15.501 3.3805-1.3255 12.693 11.996-3.378 1.3278z"/>+ <path d="m9.8207 14.176v4.5204"/>+ <g transform="translate(0, -3)">+ <animateTransform+ keySplines="0.8 0 0.2 1; 0.8 0 0.2 1"+ values="0, -3; 0, 14; 0, -3"+ attributeName="transform"+ repeatCount="indefinite"+ keyTimes="0; 0.5; 1"+ calcMode="spline"+ type="translate"+ begin="0.2s"+ dur="4s"+ />+ <g stroke-dasharray="0.5, 1">+ <path d="m9.8207 14.176-3.3805 1.3255"/>+ <path d="m9.8207 14.176v-10.674"/>+ <path d="m9.8207 14.176 12.693 11.996"/>+ </g>+ <path fill="currentColor" fill-opacity="0.53" d="m9.8207 3.50169-3.3805 1.3255v10.674l12.696 11.999 3.378-1.3278-5.8e-5 -10.674z"/>+ <g>+ <path d="m19.136 16.826-12.696-11.999"/>+ <path d="m19.136 16.826 3.3779-1.3279"/>+ <path d="m19.136 16.826v10.673"/>+ </g></g></g>- <path fill="var(--color-surface)" stroke="none" d="m6.4402 15.501-1.4402 0.0125v13.486h19v-2.8183l-1.486-0.0095-3.378 1.3278z"/>- <path d="m6.4402 15.501 12.696 11.999 3.378-1.3278"/>- <path fill="currentColor" fill-opacity="0.2" d="m0.41661 23.097 3.3805-1.3255 4.6567 4.3976-3.3834 1.33z"/>- <path d="m3.7971 21.772v4.5204"/>- <g transform="translate(0, -3)">- <animateTransform- keySplines="0.8 0 0.2 1; 0.8 0 0.2 1"- values="0, -3; 0, 14; 0, -3"- attributeName="transform"- repeatCount="indefinite"- keyTimes="0; 0.5; 1"- calcMode="spline"- type="translate"- begin="0s"- dur="4s"- />- <g stroke-dasharray="0.5, 1">- <path d="m8.454 26.169-4.6569-4.3976"/>- <path d="m3.7971 21.772-3.3805 1.3255"/>- <path d="m3.7971 21.772v-10.673"/>- </g>- <path fill="currentColor" fill-opacity="0.53" d="m3.7971 11.0984-3.3805 1.3255v10.673l4.6538 4.4021 3.3834-1.33v-10.673z"/>- <g>- <path d="m5.0704 16.826v10.673"/>- <path d="m5.0704 16.826-4.6538-4.4021"/>- <path d="m5.0704 16.826 3.3834-1.33"/>+ <g mask="url(#mbl2-l)">+ <path d="m6.4402 15.501 12.696 11.999 3.378-1.3278"/>++ <path fill="currentColor" fill-opacity="0.2" d="m0.41661 23.097 3.3805-1.3255 4.6567 4.3976-3.3834 1.33z"/>+ <path d="m3.7971 21.772v4.5204"/>+ <g transform="translate(0, -3)">+ <animateTransform+ keySplines="0.8 0 0.2 1; 0.8 0 0.2 1"+ values="0, -3; 0, 14; 0, -3"+ attributeName="transform"+ repeatCount="indefinite"+ keyTimes="0; 0.5; 1"+ calcMode="spline"+ type="translate"+ begin="0s"+ dur="4s"+ />+ <g stroke-dasharray="0.5, 1">+ <path d="m8.454 26.169-4.6569-4.3976"/>+ <path d="m3.7971 21.772-3.3805 1.3255"/>+ <path d="m3.7971 21.772v-10.673"/>+ </g>+ <path fill="currentColor" fill-opacity="0.53" d="m3.7971 11.0984-3.3805 1.3255v10.673l4.6538 4.4021 3.3834-1.33v-10.673z"/>+ <g>+ <path d="m5.0704 16.826v10.673"/>+ <path d="m5.0704 16.826-4.6538-4.4021"/>+ <path d="m5.0704 16.826 3.3834-1.33"/>+ </g></g></g>- <path fill="var(--color-surface)" stroke="none" d="m0.41661 23.097-1.4166 0.012184v5.8906h11v-2.8184l-1.5462-0.012319-3.3834 1.33z"/>+<path d="m0.41661 23.097 4.6538 4.4021 3.3834-1.33"/></svg>diff --git a/apps/web/src/features/auth/EmailAuth.tsx b/apps/web/src/features/auth/EmailAuth.tsxindex ed71f6ebad..c5e15bf444 100644--- a/apps/web/src/features/auth/EmailAuth.tsx+++ b/apps/web/src/features/auth/EmailAuth.tsx@@ -4,11 +4,16 @@ import { updateUserAuth } from '@core/auth';import { redirectToEmailAuth } from '@core/auth/email';import { LoadingBlock } from '@core/component/LoadingBlock';import { toast } from '@core/component/Toast/Toast';+import { ENABLE_ONBOARDING_V4 } from '@core/constant/featureFlags';import { useSettingsState } from '@core/constant/SettingsState';import { useEmailLinks } from '@core/email-link';import { isMobile } from '@core/mobile/isMobile';+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { whenSettled } from '@core/util/whenSettled';-import { invalidateAllAfterLogin } from '@queries/auth/user-info';+import {+ invalidateAllAfterLogin,+ useUserInfoQuery,+} from '@queries/auth/user-info';import { useNavigate, useSearchParams } from '@solidjs/router';import { createSignal, onMount, Show, Suspense } from 'solid-js';@@ -112,9 +117,23 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {navigate(props.successPath, { replace: true });};+ const userInfoQuery = useUserInfoQuery();+// The desktop settings split doesn't exist on mobile, so the callback// returns mobile users to the list view with the toast as confirmation.const navigateToEmailSettings = () => {+ // A first-run user connected this inbox from the onboarding flow:+ // return straight to it. Landing in mail settings would mount the app+ // shell mid-onboarding just for NewOnboardingRedirect to bounce back.+ if (+ ENABLE_ONBOARDING_V4 &&+ !isMobile() &&+ !isNativeMobilePlatform() &&+ userInfoQuery.data?.tutorialComplete === false+ ) {+ navigate('/onboarding', { replace: true });+ return;+ }if (isMobile()) {navigateToSuccess();return;diff --git a/apps/web/src/features/auth/LoginNew.tsx b/apps/web/src/features/auth/LoginNew.tsxindex 28ffb8746a..71781d5683 100644--- a/apps/web/src/features/auth/LoginNew.tsx+++ b/apps/web/src/features/auth/LoginNew.tsx@@ -1,8 +1,12 @@import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';+import { OnboardingFlow } from '@app/features/setup/flow/OnboardingFlow';+import { NoiseBackground } from '@app/features/setup/flow/shared';import { useAnalytics } from '@app/lib/analytics/analytics-context';import { GOOGLE_GMAIL_IDP } from '@core/auth/email';import { LoadingBlock } from '@core/component/LoadingBlock';+import { ENABLE_ONBOARDING_V4 } from '@core/constant/featureFlags';import { useEmailLinks } from '@core/email-link';+import { isMobile } from '@core/mobile/isMobile';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';import { unsetTokenPromise } from '@core/util/fetchWithToken';@@ -10,13 +14,13 @@ import { getNativeMobilePlatform } from '@core/util/platform';import IconApple from '@icon/macro-apple.svg';import IconGoogle from '@icon/macro-google.svg';import LogoIcon from '@icon/macro-logo.svg';-import IconMail from '@icon/macro-mail.svg';import ArrowLeft from '@phosphor/arrow-left.svg';import ArrowRight from '@phosphor/arrow-right.svg';import { useUserInfo } from '@queries/auth';import {invalidateAllAfterLogin,invalidateUserInfo,+ useUserInfoQuery,} from '@queries/auth/user-info';import { authServiceClient } from '@service-auth/client';import {@@ -31,7 +35,6 @@ import { Stepper } from '@ui/components/Stepper';import { detect } from 'detect-browser';import {createEffect,- createMemo,createSignal,type JSX,onCleanup,@@ -45,6 +48,7 @@ import {sentEmailCode,useResetEmailCode,} from './EmailForm';+import { OtpInput } from './OtpInput';import { Stage } from './Shared';import { useSsoLogin } from './useSsoLogin';@@ -60,10 +64,34 @@ function PostLoginRedirect() {return <LoadingBlock />;}+/**+ * Where login and onboarding meet: once authenticated, first-time desktop+ * users continue straight into the onboarding steps IN PLACE — same page,+ * no redirect — while everyone else proceeds into the app. This keeps+ * /login a single surface that decides what the user needs next.+ */+function PostAuthGate() {+ const userInfoQuery = useUserInfoQuery();++ const needsOnboarding = () =>+ ENABLE_ONBOARDING_V4 &&+ !isMobile() &&+ !isNativeMobilePlatform() &&+ userInfoQuery.data?.authenticated === true &&+ userInfoQuery.data.tutorialComplete === false;++ return (+ <Show when={needsOnboarding()} fallback={<PostLoginRedirect />}>+ <OnboardingFlow />+ </Show>+ );+}+function LoginPicker(props: { setStage: (next: Stage) => void }) {const startSsoLogin = useSsoLogin();- const showApple =- !isNativeMobilePlatform() || getNativeMobilePlatform() === 'ios';+ // Apple sign-in is iOS-only: it's required there for App Store review,+ // and intentionally absent on desktop.+ const showApple = getNativeMobilePlatform() === 'ios';return (<div class="flex flex-col gap-3">@@ -78,7 +106,8 @@ function LoginPicker(props: { setStage: (next: Stage) => void }) {<Show when={showApple}><Button- class="ring ring-edge-muted"+ variant="base"+ class="bg-surface"onClick={() => startSsoLogin('Apple')}><IconApple />@@ -87,10 +116,10 @@ function LoginPicker(props: { setStage: (next: Stage) => void }) {</Show><Button- class="ring ring-edge-muted"+ variant="base"+ class="bg-surface"onClick={() => props.setStage(Stage.Email)}>- <IconMail />Continue with email</Button></div>@@ -229,7 +258,7 @@ function EmailFormNew(props: {Continue<ArrowRight class="size-4" /></Button>- <Button class="ring ring-edge-muted" onClick={props.onBack}>+ <Button variant="base" class="bg-surface" onClick={props.onBack}><ArrowLeft class="size-4" />Back to sign in</Button>@@ -260,6 +289,7 @@ function VerifyFormNew(props: {setStage: (next: Stage) => void;onBack: () => void;}) {+ const [code, setCode] = createSignal('');const [resendError, setResendError] = createSignal<string>();const [showResendCode, setShowResendCode] = createSignal(false);const [resendTimer, setResendTimer] = createSignal(RESEND_TIMER);@@ -345,52 +375,50 @@ function VerifyFormNew(props: {class="flex flex-col gap-3"><input type="hidden" name="email" value={email() ?? ''} />+ <input type="hidden" name="one-time-code" value={code()} /><p class="text-xs text-ink-muted leading-snug">Enter the 6-digit code we sent to{' '}<span class="text-ink font-medium break-all">{email()}</span>.</p>- <div class="relative">- <FormInput- id="one-time-code"- type="text"- inputMode="numeric"- pattern="[0-9]{6}"- placeholder="••••••"- maxLength={6}- monospace- centered- class="pr-20"- onInput={(e) => {- const value = e.currentTarget.value;- if (value.length === 6) {- const formData = new FormData(formEl);- formData.set('email', email());- submit(formData);- }- }}- />- <Button+ <OtpInput+ value={code()}+ disabled={submission.pending}+ onInput={setCode}+ onComplete={(value) => {+ const formData = new FormData(formEl);+ formData.set('email', email());+ formData.set('one-time-code', value);+ submit(formData);+ }}+ />+ <p class="text-center text-xs text-ink-muted" aria-live="polite">+ Didn't receive a code?{' '}+ <buttontype="button"- variant="ghost"- size="sm"onClick={handleResendCode}disabled={emailSubmission.pending || submission.pending || !showResendCode()}- aria-live="polite"- class="absolute right-1.5 top-1/2 -translate-y-1/2 text-xs rounded-lg"+ class="font-medium text-ink transition-colors hover:text-ink-muted disabled:text-ink-extra-muted"><Show when={resendTimer() > 0} fallback="Resend">- {resendTimer()}s+ Resend ({resendTimer()})</Show>- </Button>- </div>+ </button>+ </p><FormError msg={submission.error?.message ?? resendError()} />- <Button variant="cta" type="submit" disabled={submission.pending}>+ {/* The visible pattern-validated input is gone (the code lives in a+ hidden field, which browsers exempt from constraint validation), so+ gate submission here instead of round-tripping partial codes. */}+ <Button+ variant="cta"+ type="submit"+ disabled={submission.pending || code().length !== 6}+ >Verify<ArrowRight class="size-4" /></Button>- <Button class="ring ring-edge-muted" onClick={props.onBack}>+ <Button variant="base" class="bg-surface" onClick={props.onBack}><ArrowLeft class="size-4" />Change email</Button>@@ -504,19 +532,8 @@ export function LoginNew() {}};- const headerTitle = createMemo(() => {- switch (stage()) {- case Stage.Email:- return 'Enter your email';- case Stage.Verify:- return 'Check your inbox';- default:- return 'Log in to Macro';- }- });-return (- <Show when={!userInfo()?.authenticated} fallback={<PostLoginRedirect />}>+ <Show when={!userInfo()?.authenticated} fallback={<PostAuthGate />}><div class="flex items-center justify-center size-full overflow-hidden relative"><style>{/*css*/ `@@ -539,17 +556,20 @@ export function LoginNew() {`}</style>- <div class="w-full max-w-sm sm:max-w-md ln-card">- <div class="px-4 sm:px-8 flex flex-col gap-16">+ <NoiseBackground />++ <div class="relative z-10 w-full max-w-sm sm:max-w-lg ln-card">+ <div class="px-4 sm:px-8 flex flex-col gap-12"><div class="flex flex-col gap-8"><Show when={!virtualKeyboardVisible()}>- <div class="flex flex-col items-center text-center gap-2">- <LogoIcon class="shrink-0 text-accent size-10" />- <h1- class={cn('font-semibold tracking-tight text-ink text-2xl')}- >- {headerTitle()}+ <div class="flex flex-col gap-1.5">+ <LogoIcon class="mb-2 size-9 text-accent" />+ <h1 class="font-semibold tracking-tight text-ink text-2xl">+ Welcome to Macro</h1>+ <p class="text-sm text-ink-muted">+ The open source workspace+ </p></div></Show>diff --git a/apps/web/src/features/auth/LoginOptions.tsx b/apps/web/src/features/auth/LoginOptions.tsxindex 6a735a5422..2e948fa2c9 100644--- a/apps/web/src/features/auth/LoginOptions.tsx+++ b/apps/web/src/features/auth/LoginOptions.tsx@@ -1,6 +1,5 @@import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';import { GOOGLE_GMAIL_IDP } from '@core/auth/email';-import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { getNativeMobilePlatform } from '@core/util/platform';import IconApple from '@icon/macro-apple.svg';@@ -62,14 +61,6 @@ export function LoginOptions(props: {onClick={() => startSsoLogin(GOOGLE_GMAIL_IDP)}/>- <Show when={!props.signupMode && !isNativeMobilePlatform()}>- <LoginOption- icon={<IconApple />}- label="Continue with Apple"- onClick={() => startSsoLogin('Apple')}- />- </Show>-<Show when={!props.signupMode}><LoginOptionicon={<IconMail />}diff --git a/apps/web/src/features/auth/OtpInput.tsx b/apps/web/src/features/auth/OtpInput.tsxnew file mode 100644index 0000000000..634c1a6d05--- /dev/null+++ b/apps/web/src/features/auth/OtpInput.tsx@@ -0,0 +1,86 @@+import { cn } from '@ui';+import { createSignal, Index, onCleanup, onMount } from 'solid-js';++/**+ * Segmented one-time-code input: one visible box per digit, backed by a+ * single invisible input stretched over them — so focus, paste, backspace,+ * and `autocomplete="one-time-code"` all behave like a native field while+ * the boxes just render its value. The active box (where the next digit+ * lands) carries the focus ring.+ */+export function OtpInput(props: {+ length?: number;+ value: string;+ disabled?: boolean;+ onInput: (value: string) => void;+ onComplete?: (value: string) => void;+}) {+ const length = () => props.length ?? 6;+ let inputEl: HTMLInputElement | undefined;+ const [focused, setFocused] = createSignal(false);++ onMount(() => {+ // The Stepper's outin Transition mounts this JSX before attaching it to+ // the document, so poll until connected — cancelled on unmount, or a+ // node discarded before attaching would keep the rAF loop alive.+ let cancelled = false;+ onCleanup(() => {+ cancelled = true;+ });+ const focusWhenConnected = () => {+ if (cancelled || !inputEl) return;+ if (inputEl.isConnected) inputEl.focus({ preventScroll: true });+ else requestAnimationFrame(focusWhenConnected);+ };+ focusWhenConnected();+ });++ const activeIndex = () => Math.min(props.value.length, length() - 1);++ // No native maxLength: it counts raw pasted characters, so "123 456"+ // would truncate before the separator is stripped and drop a digit.+ const handleInput = (el: HTMLInputElement) => {+ const value = el.value.replace(/\D/g, '').slice(0, length());+ if (el.value !== value) el.value = value;+ props.onInput(value);+ if (value.length === length()) props.onComplete?.(value);+ };++ return (+ <div class="relative">+ <input+ ref={(el) => {+ inputEl = el;+ }}+ type="text"+ inputMode="numeric"+ autocomplete="one-time-code"+ data-1p-ignore+ data-lpignore="true"+ value={props.value}+ disabled={props.disabled}+ onInput={(e) => handleInput(e.currentTarget)}+ onFocus={() => setFocused(true)}+ onBlur={() => setFocused(false)}+ aria-label="One-time code"+ class="absolute inset-0 z-10 size-full cursor-text opacity-0"+ />+ <div class="flex justify-between gap-2">+ <Index each={Array.from({ length: length() })}>+ {(_, index) => (+ <div+ class={cn(+ 'flex h-13 flex-1 items-center justify-center rounded-lg border bg-surface text-lg font-medium tabular-nums text-ink transition-colors',+ focused() && index === activeIndex()+ ? 'border-accent'+ : 'border-edge'+ )}+ >+ {props.value[index] ?? ''}+ </div>+ )}+ </Index>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/settings/Account.tsx b/apps/web/src/features/settings/Account.tsxindex 3f9a280ea1..7e1ac2a4e5 100644--- a/apps/web/src/features/settings/Account.tsx+++ b/apps/web/src/features/settings/Account.tsx@@ -8,6 +8,7 @@ import {blockNameToMimeTypes,} from '@core/constant/allBlocks';import {+ DEV_MODE_ENV,DISABLE_AUTO_UPDATE_UI_FLAG,ENABLE_AUTO_UPDATE_UI_OVERRIDE,ENABLE_PROFILE_PICTURES,@@ -428,7 +429,10 @@ export function Account() {</SettingsSection></Show>- <Show when={isNativeMobilePlatform()}>+ {/* Account deletion ships on native mobile (App Store requirement) and+ in dev builds, where deleting test users keeps flows like onboarding+ re-runnable. */}+ <Show when={isNativeMobilePlatform() || DEV_MODE_ENV}><SettingsSection title="Danger zone"><SettingsCard><SettingsRowdiff --git a/apps/web/src/features/setup/ConnectorsSection.tsx b/apps/web/src/features/setup/ConnectorsSection.tsxindex d0cb3f9c46..d4fffbd1ca 100644--- a/apps/web/src/features/setup/ConnectorsSection.tsx+++ b/apps/web/src/features/setup/ConnectorsSection.tsx@@ -2,18 +2,13 @@ import {FEATURED_MCP_SERVERS,type FeaturedMcpServer,} from '@core/component/AI/constant/mcpServers';-import { toast } from '@core/component/Toast/Toast';import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';import SpinnerIcon from '@phosphor/spinner-gap.svg';-import {- useAddMcpServerMutation,- useMcpServersQuery,- useStartMcpAuthMutation,-} from '@queries/mcp-servers';-import type { StartAuthResponse } from '@service-cognition/generated/schemas';+import { useMcpServersQuery } from '@queries/mcp-servers';import { cn, Layer } from '@ui';-import { createMemo, createSignal, For, Match, Switch } from 'solid-js';+import { createMemo, For, Match, Switch } from 'solid-js';import { StatusDot } from '../settings/integration-ui';+import { createConnectorConnect } from './useConnectorConnect';/** The connectors onboarding leads with (the ones the builder acts on). */const SETUP_CONNECTOR_NAMES = ['Linear', 'GitHub', 'Notion', 'Slack'];@@ -25,52 +20,19 @@ const SETUP_CONNECTOR_NAMES = ['Linear', 'GitHub', 'Notion', 'Slack'];* affordance until then (the tagline survives as the hover title).* Clicking an unconnected card kicks off add + OAuth in a popup; the server* reconciles the moment OAuth completes, and the polled servers query flips- * the card when the user returns.+ * the card when the user returns. Also used by the onboarding flow's+ * connector steps.*/-function ConnectorRow(props: {+export function ConnectorRow(props: {server: FeaturedMcpServer;connected: boolean;authenticated: boolean;}) {- const addMutation = useAddMcpServerMutation();- const authMutation = useStartMcpAuthMutation();- const [busy, setBusy] = createSignal(false);-- const handleConnect = async () => {- if (props.authenticated || busy()) return;- setBusy(true);- // Open the popup synchronously, while the click's transient activation- // is still live — opening after the awaited mutations gets rejected by- // strict popup blockers. The OAuth URL is assigned once it's known;- // severing `opener` keeps the provider page from reaching back into- // the app (reverse tabnabbing).- const popup = window.open('about:blank', '_blank');- if (popup) popup.opener = null;- try {- if (!props.connected) {- await addMutation.mutateAsync({- server_name: props.server.server_name,- url: props.server.url,- });- }- const result: StartAuthResponse = await authMutation.mutateAsync({- server_name: props.server.server_name,- server_url: props.server.url,- });- if (popup) {- popup.location.href = result.authorization_url;- } else {- // Popup was blocked outright — fall back to a plain open (may- // still be blocked, but nothing else to try).- window.open(result.authorization_url, '_blank', 'noopener,noreferrer');- }- } catch {- popup?.close();- toast.failure(`Failed to connect ${props.server.server_name}`);- } finally {- setBusy(false);- }- };+ const { connect, busy } = createConnectorConnect({+ server: props.server,+ connected: () => props.connected,+ authenticated: () => props.authenticated,+ });return (<Layer depth={2}>@@ -81,7 +43,7 @@ function ConnectorRow(props: {? `${props.server.server_name} is connected`: props.server.tagline}- onClick={() => void handleConnect()}+ onClick={() => void connect()}class={cn('group flex h-11 w-full items-center gap-2.5 rounded-xl border border-ink/[0.05] bg-surface px-3.5 text-sm','cursor-default outline-none focus-visible:ring-1 focus-visible:ring-accent/50',diff --git a/apps/web/src/features/setup/flow/BuildingStep.tsx b/apps/web/src/features/setup/flow/BuildingStep.tsxnew file mode 100644index 0000000000..509e816b23--- /dev/null+++ b/apps/web/src/features/setup/flow/BuildingStep.tsx@@ -0,0 +1,68 @@+import { LoadingSpinner } from '@core/component/LoadingSpinner';+import { createSignal, onCleanup, onMount, Show } from 'solid-js';++/** The breather before the summary: brand animation + cycling phrases for+ * ~15s, then auto-advance. Pure theater — nothing waits on real work. */++const BUILDING_PHRASES = [+ 'Building your unified workspace…',+ 'Processing your inbox…',+ 'Linking people, docs, and threads…',+ 'Distilling months of context…',+ 'Bringing in your tasks and docs…',+ 'Waking up your Macro…',+];++const BUILDING_HOLD_MS = 15_000;+const PHRASE_MS = BUILDING_HOLD_MS / BUILDING_PHRASES.length;++export function BuildingStep(props: { onDone: () => void }) {+ const [phraseIndex, setPhraseIndex] = createSignal(0);++ onMount(() => {+ const interval = setInterval(() => {+ setPhraseIndex((index) =>+ Math.min(index + 1, BUILDING_PHRASES.length - 1)+ );+ }, PHRASE_MS);+ const done = setTimeout(props.onDone, BUILDING_HOLD_MS);+ onCleanup(() => {+ clearInterval(interval);+ clearTimeout(done);+ });+ });++ const progress = () => ((phraseIndex() + 1) / BUILDING_PHRASES.length) * 100;++ return (+ <div class="flex flex-col items-center gap-8 py-16">+ <style>{+ /*css*/ `+ @keyframes obf-phrase-in {+ from { opacity: 0; transform: translateY(6px); }+ to { opacity: 1; transform: translateY(0); }+ }+ .obf-phrase { animation: obf-phrase-in 400ms ease-out both; }+ `+ }</style>++ <LoadingSpinner class="size-28 p-0" />++ {/* Keyed so each phrase re-enters with the fade-up animation. */}+ <Show when={BUILDING_PHRASES[phraseIndex()]} keyed>+ {(phrase) => (+ <p class="obf-phrase min-h-6 text-center text-base text-ink">+ {phrase}+ </p>+ )}+ </Show>++ <div class="h-1 w-48 overflow-hidden rounded-full bg-ink/10">+ <div+ class="h-full rounded-full bg-accent transition-all duration-1000 ease-linear"+ style={{ width: `${progress()}%` }}+ />+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/setup/flow/ConnectorStep.tsx b/apps/web/src/features/setup/flow/ConnectorStep.tsxnew file mode 100644index 0000000000..5f337a6a4e--- /dev/null+++ b/apps/web/src/features/setup/flow/ConnectorStep.tsx@@ -0,0 +1,89 @@+import { useAnalytics } from '@app/lib/analytics/analytics-context';+import type { FeaturedMcpServer } from '@core/component/AI/constant/mcpServers';+import SpinnerIcon from '@phosphor/spinner-gap.svg';+import { useMcpServersQuery } from '@queries/mcp-servers';+import { Layer } from '@ui';+import { createEffect, createMemo, Show } from 'solid-js';+import { ConnectorRow } from '../ConnectorsSection';+import { ContinueButton, FeatureList, SkipButton } from './shared';++/** One connector per page. OAuth runs in a popup; the polled servers query+ * flips the card, and the server starts an auto-importing gather on it. */+export function ConnectorStep(props: {+ server: FeaturedMcpServer;+ /** What connecting actually does, one row per point. */+ features: string[];+ /** Shown once connected — what happens behind the scenes ("we're already+ * looking through your Linear…"). Omit for connect-only tools (GitHub). */+ gatherHint?: string;+ onContinue: () => void;+ onSkip: () => void;+}) {+ // Poll: OAuth completes in a popup, and if this window never blurs no+ // focus-refetch would ever flip the step.+ const serversQuery = useMcpServersQuery({+ refetchInterval: 4_000,+ neverSuspend: true,+ });+ const record = createMemo(() =>+ serversQuery.data?.find((server) => server.url === props.server.url)+ );+ const authenticated = () => record()?.authenticated ?? false;++ const analytics = useAnalytics();+ let wasAuthenticated: boolean | undefined;+ createEffect(() => {+ if (serversQuery.isPlaceholderData) return;+ const authed = authenticated();+ if (wasAuthenticated === false && authed) {+ analytics.track('onboarding_v4_connector_connected', {+ connector: props.server.server_name.toLowerCase(),+ });+ }+ wasAuthenticated = authed;+ });++ return (+ <div class="flex flex-col gap-3">+ {/* On the placeholder, an already-connected server would render as+ unconnected and clickable (duplicate add + pointless popup). */}+ <Show+ when={!serversQuery.isPlaceholderData}+ fallback={+ <Layer depth={2}>+ <div class="flex h-11 w-full items-center gap-2.5 rounded-xl border border-ink/[0.05] bg-surface px-3.5 text-sm">+ <span class="flex size-4 shrink-0 items-center justify-center [&_svg]:size-4">+ <props.server.icon />+ </span>+ <span class="min-w-0 truncate font-medium text-ink">+ {props.server.server_name}+ </span>+ <span class="ml-auto flex shrink-0 items-center gap-1.5 text-xs text-ink-muted">+ <SpinnerIcon class="size-3 shrink-0 animate-spin" />+ Checking…+ </span>+ </div>+ </Layer>+ }+ >+ <ConnectorRow+ server={props.server}+ connected={record() !== undefined}+ authenticated={authenticated()}+ />+ </Show>++ <FeatureList features={props.features} />++ <Show+ when={authenticated()}+ fallback={<SkipButton onClick={props.onSkip} />}+ >+ <Show when={props.gatherHint}>+ <p class="text-xs leading-snug text-ink-muted">{props.gatherHint}</p>+ </Show>+ <ContinueButton onClick={props.onContinue} />+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/setup/flow/EmailStep.tsx b/apps/web/src/features/setup/flow/EmailStep.tsxnew file mode 100644index 0000000000..ae5dcc954a--- /dev/null+++ b/apps/web/src/features/setup/flow/EmailStep.tsx@@ -0,0 +1,186 @@+import { useAnalytics } from '@app/lib/analytics/analytics-context';+import { useUserId } from '@core/context/user';+import { useAddInboxFlow } from '@core/email-link';+import GmailIcon from '@icon/mcp-gmail.svg';+import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';+import SpinnerIcon from '@phosphor/spinner-gap.svg';+import { invalidateEmailLinks, useEmailLinksQuery } from '@queries/email/link';+import { cn, Layer } from '@ui';+import {+ createEffect,+ createMemo,+ createSignal,+ For,+ onCleanup,+ onMount,+ Show,+} from 'solid-js';+import { StatusDot } from '../../settings/integration-ui';+import { ContinueButton, SkipButton } from './shared';++/** How often the step re-checks for freshly-linked inboxes while visible. */+const LINKS_POLL_MS = 5_000;++/** The inbox count at the moment a connect was started — the web OAuth+ * round-trip reloads the page, so detecting "a link landed" after the+ * return needs a pre-redirect baseline that survives the reload. */+const CONNECT_BASELINE_KEY = 'onboarding-flow-email-baseline';++/** Connect Google accounts. On web the add-inbox flow is a full-page OAuth+ * redirect; the flow's persisted step brings the user back here. */+export function EmailStep(props: {+ onContinue: () => void;+ onSkip: () => void;+}) {+ const linksQuery = useEmailLinksQuery();+ const userId = useUserId();+ const startAddInbox = useAddInboxFlow();+ const analytics = useAnalytics();+ const [connecting, setConnecting] = createSignal<string>();++ // The links query has a long stale time; a connect that just completed+ // (this tab or another) must show up the moment the user is back.+ onMount(() => {+ void invalidateEmailLinks();+ const interval = setInterval(+ () => void invalidateEmailLinks(),+ LINKS_POLL_MS+ );+ onCleanup(() => clearInterval(interval));+ });++ // No macro_id ownership filter: linking a mailbox owned by another Macro+ // user creates a SHARED link carrying the owner's macro_id — filtering+ // would hide an inbox the user just connected.+ const links = createMemo(() => {+ const uid = userId();+ return [...(linksQuery.data?.links ?? [])].sort(+ (a, b) =>+ Number(b.is_primary && b.macro_id === uid) -+ Number(a.is_primary && a.macro_id === uid)+ );+ });++ const connectSlots = createMemo(() =>+ links().length === 0+ ? ['Connect primary account', 'Connect secondary account']+ : ['Connect another email']+ );++ // Detects a landed link via the persisted pre-redirect baseline (the+ // OAuth round-trip reloads the page, so in-memory state won't survive).+ createEffect(() => {+ const count = linksQuery.data?.links.length;+ if (count === undefined) return;+ const raw = sessionStorage.getItem(CONNECT_BASELINE_KEY);+ if (raw === null) return;+ const baseline = Number(raw);+ if (Number.isFinite(baseline) && count > baseline) {+ analytics.track('onboarding_v4_email_connected', {+ connected_count: count,+ });+ }+ if (count !== baseline) sessionStorage.removeItem(CONNECT_BASELINE_KEY);+ });++ const connect = async (slot: string) => {+ if (connecting() !== undefined) return;+ setConnecting(slot);+ analytics.track('onboarding_v4_email_connect_clicked', { slot });+ sessionStorage.setItem(+ CONNECT_BASELINE_KEY,+ String(linksQuery.data?.links.length ?? 0)+ );+ try {+ await startAddInbox();+ } finally {+ setConnecting(undefined);+ }+ };++ return (+ <div class="flex flex-col gap-3">+ <div class="flex flex-col gap-2">+ <For each={links()}>+ {(link) => (+ <Layer depth={2}>+ <div class="flex h-11 w-full items-center gap-2.5 rounded-xl border border-ink/[0.05] bg-surface px-3.5 text-sm">+ <Show+ when={typeof link.photo_url === 'string' && link.photo_url}+ fallback={<GmailIcon class="size-4 shrink-0" />}+ >+ {(photoUrl) => (+ <img+ src={photoUrl()}+ alt=""+ class="size-5 shrink-0 rounded-full"+ />+ )}+ </Show>+ <span class="min-w-0 truncate font-medium text-ink">+ {link.email_address}+ </span>+ <span class="ml-auto flex shrink-0 items-center gap-1.5 text-xs text-ink-muted">+ <StatusDot state="connected" />+ Connected+ </span>+ </div>+ </Layer>+ )}+ </For>++ <For each={connectSlots()}>+ {(slot) => (+ <Layer depth={2}>+ <button+ type="button"+ disabled={connecting() !== undefined}+ onClick={() => void connect(slot)}+ class={cn(+ 'group flex h-11 w-full items-center gap-2.5 rounded-xl border border-ink/[0.05] bg-surface px-3.5 text-sm',+ 'cursor-default outline-none focus-visible:ring-1 focus-visible:ring-ink/30',+ connecting() === undefined && 'hover:border-ink/10'+ )}+ >+ <GmailIcon class="size-4 shrink-0" />+ <span class="min-w-0 truncate font-medium text-ink">+ {slot}+ </span>+ <span class="ml-auto shrink-0">+ <Show+ when={connecting() === slot}+ fallback={+ <span class="flex items-center gap-1 text-xs font-medium text-ink-muted group-hover:text-ink">+ Connect+ <ArrowUpRightIcon class="size-3 shrink-0" />+ </span>+ }+ >+ <span class="flex items-center gap-1.5 text-xs text-ink-muted">+ <SpinnerIcon class="size-3 shrink-0 animate-spin" />+ Connecting…+ </span>+ </Show>+ </span>+ </button>+ </Layer>+ )}+ </For>+ </div>++ <Show when={links().length === 1}>+ <p class="text-xs leading-snug text-ink-muted">+ Macro works best with two accounts connected — add your secondary+ account so nothing lives in a silo.+ </p>+ </Show>++ <Show+ when={links().length > 0}+ fallback={<SkipButton onClick={props.onSkip} />}+ >+ <ContinueButton onClick={props.onContinue} />+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/setup/flow/OnboardingFlow.tsx b/apps/web/src/features/setup/flow/OnboardingFlow.tsxnew file mode 100644index 0000000000..2db89e7824--- /dev/null+++ b/apps/web/src/features/setup/flow/OnboardingFlow.tsx@@ -0,0 +1,436 @@+import { useAnalytics } from '@app/lib/analytics/analytics-context';+import { FEATURED_MCP_SERVERS } from '@core/component/AI/constant/mcpServers';+import LogoIcon from '@icon/macro-logo.svg';+import { authKeys } from '@queries/auth/keys';+import { useCompleteTutorialMutation } from '@queries/auth/tutorial';+import { useUserInfoQuery } from '@queries/auth/user-info';+import { queryClient } from '@queries/client';+import { useEmailLinksQuery } from '@queries/email/link';+import { useImportQuery } from '@queries/import';+import { useMcpServersQuery } from '@queries/mcp-servers';+import { useOnboardingQuery } from '@queries/onboarding';+import { useNavigate } from '@solidjs/router';+import { cn } from '@ui';+import { Stepper } from '@ui/components/Stepper';+import {+ createEffect,+ createMemo,+ createSignal,+ For,+ Index,+ type JSX,+ Show,+ Suspense,+} from 'solid-js';+import { BuildingStep } from './BuildingStep';+import { ConnectorStep } from './ConnectorStep';+import { createFlowFinish } from './createFlowFinish';+import { EmailStep } from './EmailStep';+import { PlanStep } from './PlanStep';+import { SummaryStep } from './SummaryStep';+import {+ FLOW_NEXT_STORAGE_KEY,+ FLOW_STEP_STORAGE_KEY,+ NoiseBackground,+} from './shared';+import { TeamStep } from './TeamStep';++/**+ * The full-screen onboarding flow new users land in after signup (desktop+ * `/onboarding`, also rendered in place on /login). Forward-only with+ * per-step skips; the server orchestrates imports (reads of an active+ * onboarding start due gather runs with auto-import). Finishing the last+ * step marks onboarding complete.+ */++interface StepDef {+ key: string;+ /** Header title; omitted for chromeless steps (the building screen). */+ title?: string;+ subtitle?: string;+ /** Widens the column (the plan grid and the summary cards need room). */+ wide?: boolean;+ /** Excluded from the progress dots (transitions, not stops). */+ noDot?: boolean;+ render: (controls: StepControls) => JSX.Element;+}++interface StepControls {+ /** Advance after finishing the step (tracked as completed). */+ next: () => void;+ /** Advance without finishing the step (tracked as skipped). */+ skip: () => void;+ finishing: () => boolean;+ finishFree: (planSkipped: boolean) => void;+ finishPremium: (tier: 'premium') => void;+}++interface ConnectorStepCopy {+ subtitle: string;+ features: string[];+ /** Shown under the row once connected — what happens behind the scenes. */+ gatherHint?: string;+}++const CONNECTOR_COPY: Record<string, ConnectorStepCopy> = {+ Linear: {+ subtitle: 'Bring your issues into your unified workspace.',+ features: [+ 'Macro imports a small set of your recent issues — and your tags — as Macro tasks, ready to work on.',+ 'Macro AI can create and update Linear issues without leaving Macro.',+ ],+ gatherHint:+ "We're already looking through your Linear — you'll see what we found before you finish.",+ },+ Notion: {+ subtitle: 'Bring your docs and wikis into your unified workspace.',+ features: [+ 'Macro imports a small set of your key pages — and your tags — as Macro docs.',+ 'Macro AI can search your pages and wikis; Notion itself is never changed.',+ ],+ gatherHint:+ "We're already looking through your Notion — you'll see what we found before you finish.",+ },+ Slack: {+ subtitle: 'Bring the conversations where decisions happen.',+ features: [+ 'Macro imports a small set of your most active channels for your team.',+ 'Macro AI can search conversations and post updates for you.',+ ],+ gatherHint:+ "We're already looking through your Slack — you'll see what we found before you finish.",+ },+ GitHub: {+ subtitle: 'Give Macro AI eyes on your code.',+ features: [+ 'Ask Macro AI about your repos, pull requests, and issues.',+ 'Nothing syncs on its own — GitHub stays exactly as it is until you ask.',+ ],+ },+};++/** Connector steps, in spec order, dropping tools absent from this build+ * (Slack is dev-only in production FEATURED_MCP_SERVERS). */+const CONNECTOR_STEP_NAMES = ['Linear', 'Notion', 'Slack', 'GitHub'];++function buildSteps(): StepDef[] {+ const connectorSteps: StepDef[] = CONNECTOR_STEP_NAMES.flatMap((name) => {+ const server = FEATURED_MCP_SERVERS.find(+ (candidate) => candidate.server_name === name+ );+ const copy = CONNECTOR_COPY[name];+ if (!server || !copy) return [];+ return [+ {+ key: `connect-${name.toLowerCase()}`,+ title: `Connect ${name}`,+ subtitle: copy.subtitle,+ render: (controls: StepControls) => (+ <ConnectorStep+ server={server}+ features={copy.features}+ gatherHint={copy.gatherHint}+ onContinue={controls.next}+ onSkip={controls.skip}+ />+ ),+ },+ ];+ });++ return [+ {+ key: 'email',+ title: 'Connect your Google accounts',+ subtitle:+ 'Macro builds one unified memory across everything you do. Connecting work and personal brings your email, docs, and calendar together — so nothing lives in a silo.',+ render: (controls) => (+ <EmailStep onContinue={controls.next} onSkip={controls.skip} />+ ),+ },+ ...connectorSteps,+ {+ key: 'team',+ title: 'Set up your team',+ subtitle:+ 'Macro is designed as a multiplayer tool — your unified memory gets sharper with every teammate who joins.',+ render: (controls) => (+ <TeamStep onContinue={controls.next} onSkip={controls.skip} />+ ),+ },+ {+ // Pure theater while gathers land; auto-advances into the summary.+ key: 'building',+ noDot: true,+ render: (controls) => <BuildingStep onDone={controls.next} />,+ },+ {+ key: 'summary',+ title: 'Your workspace is taking shape',+ subtitle:+ "Here's what we're bringing into Macro. Imports keep running in the background — no need to wait.",+ wide: true,+ render: (controls) => <SummaryStep onContinue={controls.next} />,+ },+ {+ key: 'plan',+ title: 'Choose your plan',+ subtitle: 'Start free, or go Premium. You can change this anytime.',+ wide: true,+ render: (controls) => (+ <PlanStep+ finishing={controls.finishing()}+ onFree={controls.finishFree}+ onPremium={controls.finishPremium}+ />+ ),+ },+ ];+}++/** Quiet placeholder while a step's first-load queries resolve. */+function StepFallback() {+ return (+ <div class="flex justify-center py-10">+ <LogoIcon class="size-6 animate-pulse text-ink/30" />+ </div>+ );+}++export function OnboardingFlow() {+ // Own boundary: a query suspending here would otherwise blank the whole+ // app through the root <Suspense>.+ return (+ <Suspense+ fallback={+ <div class="flex h-full w-full items-center justify-center bg-surface">+ <LogoIcon class="size-8 animate-pulse text-accent" />+ </div>+ }+ >+ <FlowContent />+ </Suspense>+ );+}++function FlowContent() {+ const navigate = useNavigate();+ const userInfoQuery = useUserInfoQuery();+ // Reading the onboarding state creates the flow's row and starts gather+ // runs — it must never fire for someone who already onboarded.+ const needsOnboarding = () =>+ userInfoQuery.data?.authenticated === true &&+ userInfoQuery.data.tutorialComplete === false;+ const onboardingQuery = useOnboardingQuery({ enabled: needsOnboarding });+ // Mounted for the whole flow so gather results are warm by the summary.+ useImportQuery({ enabled: needsOnboarding });+ // Analytics inputs; read only from handlers/effects so they never+ // suspend this boundary.+ const linksQuery = useEmailLinksQuery();+ const serversQuery = useMcpServersQuery({ neverSuspend: true });+ const analytics = useAnalytics();++ const steps = buildSteps();++ const [stepIndex, setStepIndex] = createSignal(0);+ const currentStep = createMemo(() => steps[stepIndex()]);+ const userId = () => userInfoQuery.data?.userId;++ // Resume where a full-page OAuth round-trip left off — only for the user+ // who saved the step: sessionStorage is per-tab, and a different account+ // logging in on the same tab must not inherit the previous user's step.+ let restored = false;+ createEffect(() => {+ const uid = userId();+ if (restored || !uid) return;+ restored = true;+ try {+ const raw = sessionStorage.getItem(FLOW_STEP_STORAGE_KEY);+ if (!raw) return;+ const saved: { user?: string; step?: string } = JSON.parse(raw);+ if (saved.user !== uid) {+ sessionStorage.removeItem(FLOW_STEP_STORAGE_KEY);+ sessionStorage.removeItem(FLOW_NEXT_STORAGE_KEY);+ return;+ }+ const index = steps.findIndex((step) => step.key === saved.step);+ if (index !== -1) setStepIndex(index);+ } catch {+ sessionStorage.removeItem(FLOW_STEP_STORAGE_KEY);+ }+ });++ // A Google SSO signup arrives with its Gmail inbox already linked, an+ // email-code signup with none — the first links payload is the signal.+ let startedTracked = false;+ createEffect(() => {+ if (startedTracked || !needsOnboarding()) return;+ const links = linksQuery.data?.links;+ if (!links) return;+ startedTracked = true;+ analytics.track('onboarding_v4_started', {+ signup_method: links.length > 0 ? 'google' : 'email_code',+ entry_step: currentStep().key,+ });+ });++ createEffect(() => {+ if (!needsOnboarding()) return;+ analytics.track('onboarding_v4_step', {+ step: currentStep().key,+ index: stepIndex(),+ state: 'viewed',+ });+ });++ // Forward-only: there is no back.+ const advance = (state: 'completed' | 'skipped') => {+ analytics.track('onboarding_v4_step', {+ step: currentStep().key,+ index: stepIndex(),+ state,+ });+ const index = Math.min(stepIndex() + 1, steps.length - 1);+ setStepIndex(index);+ sessionStorage.setItem(+ FLOW_STEP_STORAGE_KEY,+ JSON.stringify({ user: userId(), step: steps[index].key })+ );+ };++ const finish = createFlowFinish({+ completionRollup: () => ({+ emails_connected: linksQuery.data?.links.length ?? 0,+ connectors_connected: (serversQuery.data ?? [])+ .filter((server) => server.authenticated)+ .map((server) => server.server_name.toLowerCase()),+ }),+ });+ const controls: StepControls = {+ next: () => advance('completed'),+ skip: () => advance('skipped'),+ finishing: finish.finishing,+ finishFree: (planSkipped) => void finish.finishFree(planSkipped),+ finishPremium: (tier) => void finish.finishPremium(tier),+ };++ // Heal a half-landed finish: NewOnboardingRedirect keys off+ // tutorialComplete while this flow keys off the onboarding row, and the+ // two are not completed atomically — row completed + flag stuck false+ // would ping-pong between Layout and this flow forever.+ const completeTutorial = useCompleteTutorialMutation();+ const [healingTutorial, setHealingTutorial] = createSignal(false);+ const healTutorial = () => {+ if (healingTutorial()) return;+ setHealingTutorial(true);+ void completeTutorial+ .mutateAsync()+ .then(() =>+ queryClient.refetchQueries({ queryKey: authKeys.userInfo.queryKey })+ )+ .catch(() => {});+ };++ // Redirect out when there is nothing to onboard. finishing() guards the+ // window between our own complete call and the checkout redirect.+ createEffect(() => {+ const info = userInfoQuery.data;+ if (info?.authenticated === false) {+ navigate('/login', { replace: true });+ return;+ }+ if (finish.finishing() || info?.authenticated !== true) return;+ if (info.tutorialComplete !== false) {+ navigate(finish.afterTarget(), { replace: true });+ return;+ }+ if (onboardingQuery.data?.row.status === 'completed') {+ healTutorial();+ }+ });++ return (+ <div class="relative size-full overflow-y-auto bg-surface font-sans text-ink">+ <style>{+ /*css*/ `+ @keyframes obf-card-in {+ from { opacity: 0; transform: translateY(14px) scale(0.985); }+ to { opacity: 1; transform: translateY(0) scale(1); }+ }+ .obf-card { animation: obf-card-in 520ms cubic-bezier(0.22, 1, 0.36, 1) both; }++ /* Override browser autofill yellow with our surface/ink palette */+ .obf-input:-webkit-autofill,+ .obf-input:-webkit-autofill:hover,+ .obf-input:-webkit-autofill:focus,+ .obf-input:-webkit-autofill:active {+ -webkit-box-shadow: 0 0 0 1000px var(--color-surface) inset;+ -webkit-text-fill-color: var(--color-ink);+ caret-color: var(--color-ink);+ transition: background-color 5000s ease-in-out 0s;+ }+ `+ }</style>++ <NoiseBackground />++ <div class="relative z-10 flex min-h-full items-center justify-center px-6 py-12">+ <div+ class={cn(+ 'w-full obf-card transition-[max-width] duration-300',+ currentStep().wide ? 'sm:max-w-xl' : 'sm:max-w-lg'+ )}+ >+ <div class="flex flex-col gap-8">+ <Show when={currentStep().title}>+ <div class="flex flex-col gap-1.5">+ <h1 class="text-2xl font-semibold tracking-tight text-ink">+ {currentStep().title}+ </h1>+ <Show when={currentStep().subtitle}>+ <p class="max-w-md text-sm leading-relaxed text-ink-muted">+ {currentStep().subtitle}+ </p>+ </Show>+ </div>+ </Show>++ <Stepper step={stepIndex()} transition={Stepper.transitions.scale}>+ <For each={steps}>+ {(step) => (+ <Stepper.Step>+ {/* Per-step boundary: a first-load query suspending+ inside the Stepper's Transition would drop the+ entering node entirely. */}+ <Suspense fallback={<StepFallback />}>+ {step.render(controls)}+ </Suspense>+ </Stepper.Step>+ )}+ </For>+ </Stepper>++ <Show when={!currentStep().noDot}>+ <div class="flex gap-1.5">+ <Index each={steps.filter((step) => !step.noDot)}>+ {(step) => (+ <div+ class={cn(+ 'size-1.5 rounded-full transition-colors',+ stepIndex() === steps.indexOf(step())+ ? 'bg-accent'+ : stepIndex() > steps.indexOf(step())+ ? 'bg-ink/40'+ : 'bg-ink/15'+ )}+ />+ )}+ </Index>+ </div>+ </Show>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/setup/flow/PlanStep.tsx b/apps/web/src/features/setup/flow/PlanStep.tsxnew file mode 100644index 0000000000..71bf842831--- /dev/null+++ b/apps/web/src/features/setup/flow/PlanStep.tsx@@ -0,0 +1,99 @@+import {+ PLAN_FEATURES,+ PLANS,+ type PlanTier,+} from '@app/features/paywall/plans';+import ArrowRight from '@phosphor/arrow-right.svg';+import Check from '@phosphor/check.svg';+import { Button, cn } from '@ui';+import { createSignal, Index, Show } from 'solid-js';+import { SkipButton } from './shared';++/** Free vs paid. The last step: continuing or skipping marks onboarding+ * complete; skippers land exactly where finishers do. */+export function PlanStep(props: {+ finishing: boolean;+ onFree: (planSkipped: boolean) => void;+ onPremium: (tier: Exclude<PlanTier, 'free'>) => void;+}) {+ const [selected, setSelected] = createSignal<PlanTier>('free');++ const finish = () => {+ const tier = selected();+ if (tier === 'free') props.onFree(false);+ else props.onPremium(tier);+ };++ return (+ <div class="flex flex-col gap-6">+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <Index each={PLANS}>+ {(plan) => (+ <button+ type="button"+ onClick={() => setSelected(plan().tier)}+ class={cn(+ 'flex flex-col gap-4 rounded-xl border p-5 text-left transition-colors cursor-default',+ selected() === plan().tier+ ? 'border-ink/40 ring-1 ring-ink/20'+ : 'border-edge hover:border-edge-muted'+ )}+ >+ <div class="flex items-center justify-between">+ <span class="text-sm font-semibold text-ink">+ {plan().name}+ </span>+ <span+ class={cn(+ 'flex items-center justify-center size-4 rounded-full border',+ selected() === plan().tier+ ? 'border-ink bg-ink text-surface'+ : 'border-edge'+ )}+ >+ <Show when={selected() === plan().tier}>+ <Check class="size-3" />+ </Show>+ </span>+ </div>+ <div class="flex items-baseline gap-1">+ <span class="text-2xl font-semibold tracking-tight text-ink">+ ${plan().price}+ </span>+ <span class="text-xs text-ink-muted">+ {plan().price === 0 ? 'forever' : 'per user / month'}+ </span>+ </div>+ <ul class="flex flex-col gap-2">+ <Index each={PLAN_FEATURES}>+ {(feature) => (+ <li class="flex items-center justify-between gap-2 text-xs">+ <span class="text-ink-muted">{feature().label}</span>+ <span class="text-ink font-medium">+ {feature().values[plan().tier]}+ </span>+ </li>+ )}+ </Index>+ </ul>+ </button>+ )}+ </Index>+ </div>++ <div class="flex flex-col gap-3">+ <Button variant="cta" disabled={props.finishing} onClick={finish}>+ {props.finishing+ ? 'Setting up your workspace…'+ : `Continue with ${selected() === 'free' ? 'Free' : 'Premium'}`}+ <ArrowRight class="size-4" />+ </Button>+ <SkipButton+ label="Decide later"+ disabled={props.finishing}+ onClick={() => props.onFree(true)}+ />+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/setup/flow/SummaryStep.tsx b/apps/web/src/features/setup/flow/SummaryStep.tsxnew file mode 100644index 0000000000..9d0a7b81e3--- /dev/null+++ b/apps/web/src/features/setup/flow/SummaryStep.tsx@@ -0,0 +1,217 @@+import { FEATURED_MCP_SERVERS } from '@core/component/AI/constant/mcpServers';+import GmailIcon from '@icon/mcp-gmail.svg';+import SpinnerIcon from '@phosphor/spinner-gap.svg';+import { useContacts } from '@queries/contacts/contacts';+import { getBackfillProgress } from '@queries/email/backfill';+import { useEmailLinksQuery } from '@queries/email/link';+import {+ type ImportEntity,+ type ImportRun,+ useImportQuery,+ useRetryGatherMutation,+} from '@queries/import';+import { createMemo, For, Match, Show, Switch } from 'solid-js';+import { ImportEntityPill } from '../ImportEntityPill';+import {+ FailureNote,+ ImportCard,+ PillGrid,+ SkeletonPills,+} from '../primitives';+import { SOURCE_SECTIONS, type SourceSection } from '../selection';+import { ContinueButton } from './shared';++/** What's landing in the workspace: auto-import owns the accepting, so the+ * cards just render live progress (gateway pushes + polling). */+export function SummaryStep(props: { onContinue: () => void }) {+ const importQuery = useImportQuery();+ const retryGather = useRetryGatherMutation();+ const linksQuery = useEmailLinksQuery();+ const contacts = useContacts();++ // No ownership filter — shared links carry the owner's macro_id.+ const links = createMemo(() => linksQuery.data?.links ?? []);++ // Undefined until any inbox reports backfill progress.+ const emailProgress = createMemo(() => {+ let completed = 0;+ let total = 0;+ let any = false;+ for (const link of links()) {+ const progress = getBackfillProgress(link.id);+ if (progress) {+ any = true;+ completed += progress.completed;+ total += progress.total;+ }+ }+ return any ? { completed, total } : undefined;+ });++ const sliceFor = (definition: SourceSection) => ({+ run: importQuery.data?.runs.find((run) => run.source === definition.source),+ entities: (importQuery.data?.entities ?? []).filter(+ (entity) =>+ entity.source === definition.source && entity.status !== 'discarded'+ ),+ });++ const visibleSections = createMemo(() =>+ SOURCE_SECTIONS.filter((definition) => {+ const slice = sliceFor(definition);+ return slice.run !== undefined || slice.entities.length > 0;+ })+ );++ const anythingToShow = () =>+ links().length > 0 || visibleSections().length > 0;++ return (+ <div class="flex flex-col gap-3">+ <Show when={links().length > 0}>+ <ImportCard+ icon={<GmailIcon />}+ title="Email & contacts"+ connected+ status={+ <span class="flex items-center gap-1.5">+ <Show+ when={emailProgress()}+ fallback={<>processing your inbox in the background</>}+ >+ {(progress) => (+ <>+ processing your inbox —{' '}+ {progress().completed.toLocaleString()} of{' '}+ {progress().total.toLocaleString()} emails+ </>+ )}+ </Show>+ <Show when={contacts().length > 0}>+ <span>+ · {contacts().length.toLocaleString()} contacts found so far+ </span>+ </Show>+ <SpinnerIcon class="size-3 shrink-0 animate-spin" />+ </span>+ }+ />+ </Show>++ <For each={visibleSections()}>+ {(definition) => (+ <AutoImportCard+ definition={definition}+ run={sliceFor(definition).run}+ entities={sliceFor(definition).entities}+ onRetryGather={() => retryGather.mutate(definition.source)}+ />+ )}+ </For>++ <Show when={!anythingToShow()}>+ <p class="py-4 text-center text-sm text-ink-extra-muted">+ Nothing queued — you can always ask Macro AI to bring things in later.+ </p>+ </Show>++ <ContinueButton onClick={props.onContinue} />+ </div>+ );+}++interface StatusCounts {+ staged: number;+ importing: number;+ imported: number;+}++/** One source's card: no accept toggle (auto-import owns accepting), the+ * blurb narrates gathering → importing → in your workspace. */+function AutoImportCard(props: {+ definition: SourceSection;+ run: ImportRun | undefined;+ entities: ImportEntity[];+ onRetryGather: () => void;+}) {+ const server = createMemo(() =>+ FEATURED_MCP_SERVERS.find(+ (candidate) => candidate.server_name === props.definition.serverName+ )+ );+ const serverIcon = () => {+ const found = server();+ return found ? <found.icon /> : undefined;+ };+ const counts = createMemo<StatusCounts>(() => {+ const tally: StatusCounts = { staged: 0, importing: 0, imported: 0 };+ for (const entity of props.entities) {+ if (entity.status === 'staged') tally.staged += 1;+ else if (entity.status === 'importing') tally.importing += 1;+ else if (entity.status === 'imported') tally.imported += 1;+ }+ return tally;+ });+ const gathering = () => props.run?.status === 'running';+ const importing = () =>+ props.run?.status === 'importing' || counts().importing > 0;++ return (+ <ImportCard+ icon={serverIcon()}+ title={props.definition.serverName}+ count={props.entities.length || undefined}+ connected+ status={+ <Switch>+ <Match when={props.run?.status === 'failed'}>+ <FailureNote+ message={`we couldn't look through your ${props.definition.serverName}.`}+ onRetry={() => props.onRetryGather()}+ />+ </Match>+ <Match when={gathering()}>+ <span class="flex items-center gap-1.5">+ looking through your {props.definition.serverName} for{' '}+ {props.definition.noun} worth importing…+ <SpinnerIcon class="size-3 shrink-0 animate-spin" />+ </span>+ </Match>+ <Match when={importing()}>+ <span class="flex items-center gap-1.5">+ importing {props.definition.noun} into your workspace…+ <SpinnerIcon class="size-3 shrink-0 animate-spin" />+ </span>+ </Match>+ <Match when={counts().imported > 0}>+ {counts().imported} {props.definition.noun} from{' '}+ {props.definition.serverName} are in your workspace.+ </Match>+ <Match when={counts().staged > 0}>+ <span class="flex items-center gap-1.5">+ found {counts().staged} {props.definition.noun} — importing+ shortly…+ <SpinnerIcon class="size-3 shrink-0 animate-spin" />+ </span>+ </Match>+ <Match when={true}>+ nothing new to bring over from {props.definition.serverName}.+ </Match>+ </Switch>+ }+ >+ <Show when={props.entities.length > 0 || gathering()}>+ <PillGrid>+ <For each={props.entities}>+ {(entity) => (+ <ImportEntityPill entity={entity} icon={serverIcon()} />+ )}+ </For>+ <Show when={gathering()}>+ <SkeletonPills count={props.entities.length > 0 ? 3 : 6} />+ </Show>+ </PillGrid>+ </Show>+ </ImportCard>+ );+}diff --git a/apps/web/src/features/setup/flow/TeamStep.tsx b/apps/web/src/features/setup/flow/TeamStep.tsxnew file mode 100644index 0000000000..61a82fbd95--- /dev/null+++ b/apps/web/src/features/setup/flow/TeamStep.tsx@@ -0,0 +1,288 @@+import { useAnalytics } from '@app/lib/analytics/analytics-context';+import { useEmail } from '@core/context/user';+import { idToDisplayName } from '@core/user/util';+import CheckIcon from '@phosphor/check.svg';+import Plus from '@phosphor/plus.svg';+import { useContacts } from '@queries/contacts/contacts';+import { useOnboardingQuery } from '@queries/onboarding';+import {+ useJoinTeamMutation,+ useUserInvitesQuery,+} from '@queries/team/invitations';+import {+ useCreateTeamWithInvitesMutation,+ useUserTeamsQuery,+} from '@queries/team/teams';+import type { TeamInviteDetails } from '@service-auth/generated/schemas/teamInviteDetails';+import { Button } from '@ui';+import {+ createEffect,+ createMemo,+ createSignal,+ For,+ Index,+ Show,+} from 'solid-js';+import {+ ContinueButton,+ deriveTeamName,+ emailDomain,+ FormInput,+ isPlausibleEmail,+ SkipButton,+} from './shared';++/** Set up your team: already a member → confirmation, pending invites →+ * join, otherwise create (with domain-derived prefill + suggestions). */+export function TeamStep(props: {+ onContinue: () => void;+ onSkip: () => void;+}) {+ const analytics = useAnalytics();+ const teamsQuery = useUserTeamsQuery();+ const invitesQuery = useUserInvitesQuery();++ const team = createMemo(() => teamsQuery.data?.[0]);+ const invites = createMemo(() => invitesQuery.data?.invites ?? []);++ // One-shot on the FIRST resolved teams payload, so a create/join later+ // in this step doesn't also read as auto-joined.+ let membershipReported = false;+ createEffect(() => {+ if (membershipReported || teamsQuery.data === undefined) return;+ membershipReported = true;+ if (teamsQuery.data.length > 0) {+ analytics.track('onboarding_v4_team', { action: 'already_on_team' });+ }+ });++ return (+ <Show+ when={!team()}+ fallback={+ <OnTeamPanel name={team()?.name} onContinue={props.onContinue} />+ }+ >+ <Show+ when={invites().length === 0}+ fallback={<InvitesPanel invites={invites()} onSkip={props.onSkip} />}+ >+ <CreateTeamForm onContinue={props.onContinue} onSkip={props.onSkip} />+ </Show>+ </Show>+ );+}++/** Already on a team — auto-joined by domain, or just created/joined here. */+function OnTeamPanel(props: { name?: string; onContinue: () => void }) {+ return (+ <div class="flex flex-col gap-3">+ <div class="flex flex-col items-center gap-2 py-4 text-center">+ <span class="flex size-10 items-center justify-center rounded-full bg-success/10 text-success">+ <CheckIcon class="size-5" />+ </span>+ <p class="text-sm font-medium text-ink">+ You're on {props.name ?? 'your team'}+ </p>+ {/* Copy must stay true for auto-join, invite-accept, and the+ optimistic mid-create flash alike. */}+ <p class="max-w-xs text-xs text-ink-muted leading-snug">+ Your team is set up — everything your teammates bring into Macro is+ shared with you.+ </p>+ </div>+ <ContinueButton onClick={props.onContinue} />+ </div>+ );+}++/** Pending team invites — join one and move on. */+function InvitesPanel(props: {+ invites: TeamInviteDetails[];+ onSkip: () => void;+}) {+ const analytics = useAnalytics();+ const joinTeam = useJoinTeamMutation({+ onSuccess: () => {+ analytics.track('onboarding_v4_team', { action: 'joined_invite' });+ },+ });++ return (+ <div class="flex flex-col gap-3">+ <For each={props.invites}>+ {(invite) => (+ <div class="flex items-center gap-2.5 rounded-lg border border-edge bg-surface px-4 py-3 text-sm">+ <span class="min-w-0 truncate text-ink">+ {idToDisplayName(invite.invited_by)} invited you to their team+ </span>+ <Button+ variant="cta"+ size="sm"+ class="ml-auto shrink-0"+ disabled={joinTeam.isPending}+ onClick={() => joinTeam.mutate({ teamInviteId: invite.id })}+ >+ Join+ </Button>+ </div>+ )}+ </For>+ <SkipButton onClick={props.onSkip} />+ </div>+ );+}++const INITIAL_INVITE_SLOTS = ['', ''];+const SUGGESTION_CAP = 6;++/** Create a team: pre-derived name + same-domain invite suggestions when the+ * user has a custom domain; the plain form otherwise. */+function CreateTeamForm(props: { onContinue: () => void; onSkip: () => void }) {+ const analytics = useAnalytics();+ const email = useEmail();+ const contacts = useContacts();+ const createTeam = useCreateTeamWithInvitesMutation();+ const onboardingQuery = useOnboardingQuery();++ // Server-judged with the same list the teams service uses for+ // auto-join/claiming, so we never suggest a team the server would refuse.+ const customDomain = () =>+ onboardingQuery.data?.suggested_team_domain ?? undefined;++ const [name, setName] = createSignal('');+ const [nameTouched, setNameTouched] = createSignal(false);+ // Prefill once the suggestion arrives, never over a typed name.+ createEffect(() => {+ const domain = customDomain();+ if (domain && !nameTouched()) setName(deriveTeamName(domain));+ });+ const [inviteSlots, setInviteSlots] = createSignal<string[]>([+ ...INITIAL_INVITE_SLOTS,+ ]);++ const validInvites = () =>+ [...new Set(inviteSlots().map((value) => value.trim()))].filter(+ (value) => isPlausibleEmail(value) && value !== email()+ );++ const suggestions = createMemo(() => {+ const suffix = customDomain();+ if (!suffix) return [];+ const own = email();+ const taken = new Set(inviteSlots().map((value) => value.trim()));+ return contacts()+ .filter(+ (contact) =>+ contact.email !== own &&+ emailDomain(contact.email) === suffix &&+ !taken.has(contact.email)+ )+ .slice(0, SUGGESTION_CAP);+ });++ const addInvite = (address: string) => {+ setInviteSlots((slots) => {+ const empty = slots.findIndex((value) => value.trim() === '');+ if (empty === -1) return [...slots, address];+ return slots.map((value, i) => (i === empty ? address : value));+ });+ };++ const create = async () => {+ if (createTeam.isPending || name().trim().length === 0) return;+ // The mutation owns its toasts; stay put (form intact) on failure.+ const invitesSent = validInvites().length;+ try {+ await createTeam.mutateAsync({+ name: name().trim(),+ invites: validInvites().map((address) => ({ email: address })),+ });+ } catch {+ return;+ }+ analytics.track('onboarding_v4_team', {+ action: 'created',+ invites_sent: invitesSent,+ used_domain_suggestion: customDomain() !== undefined,+ });+ props.onContinue();+ };++ return (+ <div class="flex flex-col gap-3">+ <FormInput+ id="team-name"+ placeholder="Team name"+ value={name()}+ autoFocus={!customDomain()}+ onInput={(value) => {+ setNameTouched(true);+ setName(value);+ }}+ />++ {/* Index, not For: slots are edited strings, and For keys by value —+ each keystroke would recreate the input node and drop focus. */}+ <Index each={inviteSlots()}>+ {(slot, i) => (+ <FormInput+ id={`invite-${i}`}+ type="email"+ placeholder="[email protected]"+ value={slot()}+ onInput={(value) =>+ setInviteSlots((slots) =>+ slots.map((v, j) => (j === i ? value : v))+ )+ }+ />+ )}+ </Index>++ <Button+ variant="ghost"+ size="sm"+ class="self-center text-ink-muted"+ onClick={() => setInviteSlots((slots) => [...slots, ''])}+ >+ <Plus class="size-4" />+ Add another teammate+ </Button>++ <Show when={suggestions().length > 0}>+ <div class="flex flex-col gap-1.5">+ <p class="text-xs text-ink-muted">+ From your contacts at {customDomain()}:+ </p>+ <div class="flex flex-wrap gap-1.5">+ <For each={suggestions()}>+ {(contact) => (+ <button+ type="button"+ title={`Invite ${contact.email}`}+ onClick={() => addInvite(contact.email)}+ class="inline-flex h-7 max-w-72 items-center gap-1.5 rounded-full border border-ink/10 bg-surface px-2.5 text-xs text-ink transition-colors hover:border-ink/20"+ >+ <Plus class="size-3 shrink-0 text-ink-extra-muted" />+ <span class="min-w-0 truncate">{contact.email}</span>+ </button>+ )}+ </For>+ </div>+ </div>+ </Show>++ <ContinueButton+ label={+ validInvites().length > 0+ ? `Create team & invite ${validInvites().length}`+ : 'Create team'+ }+ disabled={name().trim().length === 0 || createTeam.isPending}+ onClick={() => void create()}+ />+ <SkipButton onClick={props.onSkip} />+ </div>+ );+}diff --git a/apps/web/src/features/setup/flow/createFlowFinish.ts b/apps/web/src/features/setup/flow/createFlowFinish.tsnew file mode 100644index 0000000000..1eb5f9f674--- /dev/null+++ b/apps/web/src/features/setup/flow/createFlowFinish.ts@@ -0,0 +1,139 @@+import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';+import type { PaidPlanTier } from '@app/features/paywall/plans';+import { useAnalytics } from '@app/lib/analytics/analytics-context';+import { toast } from '@core/component/Toast/Toast';+import { authKeys } from '@queries/auth/keys';+import { useCompleteTutorialMutation } from '@queries/auth/tutorial';+import { useUserInfoQuery } from '@queries/auth/user-info';+import { queryClient } from '@queries/client';+import { useCompleteOnboardingMutation } from '@queries/onboarding';+import { stripeServiceClient } from '@service-stripe/client';+import { useNavigate, useSearchParams } from '@solidjs/router';+import { createEffect, createSignal } from 'solid-js';+import { FLOW_NEXT_STORAGE_KEY, FLOW_STEP_STORAGE_KEY } from './shared';++/**+ * The "leave onboarding" workflow: mark onboarding + the legacy tutorial+ * complete, then land in the app (the preserved `?next=` deep link, or+ * home). Imports never block the exit; auto-import keeps landing rows+ * server-side.+ */+export function createFlowFinish(options?: {+ /** Extra analytics context stamped onto `onboarding_v4_completed`. */+ completionRollup?: () => {+ emails_connected: number;+ connectors_connected: string[];+ };+}) {+ const navigate = useNavigate();+ const [searchParams] = useSearchParams();+ const userInfoQuery = useUserInfoQuery();+ const completeOnboarding = useCompleteOnboardingMutation();+ const completeTutorial = useCompleteTutorialMutation();+ const analytics = useAnalytics();+ const [finishing, setFinishing] = createSignal(false);++ const trackCompleted = (plan: 'free' | 'premium', planSkipped: boolean) => {+ analytics.track('onboarding_v4_completed', {+ plan,+ plan_skipped: planSkipped,+ emails_connected: 0,+ connectors_connected: [],+ ...options?.completionRollup?.(),+ });+ };++ // Same-app relative paths only.+ const sanitizeNext = (value: unknown): string | undefined =>+ typeof value === 'string' &&+ value.startsWith('/') &&+ !value.startsWith('//')+ ? value+ : undefined;++ // The inbox-OAuth callback returns to bare /onboarding — persist the+ // deep link so it survives the round-trip.+ createEffect(() => {+ const next = sanitizeNext(searchParams.next);+ if (next) sessionStorage.setItem(FLOW_NEXT_STORAGE_KEY, next);+ });++ const afterTarget = () =>+ sanitizeNext(searchParams.next) ??+ sanitizeNext(sessionStorage.getItem(FLOW_NEXT_STORAGE_KEY)) ??+ '/';++ /**+ * Mark the flow complete and verify it stuck: NewOnboardingRedirect keys+ * off tutorialComplete, so navigating before the cache reflects the PATCH+ * would bounce straight back here.+ */+ const completeFlow = async (): Promise<boolean> => {+ const [onboardingResult] = await Promise.allSettled([+ completeOnboarding.mutateAsync({ skipped: false }),+ completeTutorial.mutateAsync(),+ ]);+ // Exiting with the row still active would leave staged candidates+ // undiscarded and the flow resumable after the user thinks it's done.+ if (onboardingResult.status === 'rejected') {+ toast.failure("Couldn't finish setup — please try again");+ return false;+ }+ await queryClient+ .refetchQueries({ queryKey: authKeys.userInfo.queryKey })+ .catch(() => {});+ if (userInfoQuery.data?.tutorialComplete !== true) {+ toast.failure("Couldn't finish setup — please try again");+ return false;+ }+ sessionStorage.removeItem(FLOW_STEP_STORAGE_KEY);+ sessionStorage.removeItem(FLOW_NEXT_STORAGE_KEY);+ return true;+ };++ /** Finish on the free plan (or a skipped plan step) and enter the app. */+ const finishFree = async (planSkipped = false) => {+ if (finishing()) return;+ setFinishing(true);+ try {+ if (await completeFlow()) {+ trackCompleted('free', planSkipped);+ navigate(afterTarget(), { replace: true });+ }+ } finally {+ setFinishing(false);+ }+ };++ /**+ * Finish on a paid tier: complete the flow FIRST (the checkout round-trip+ * must not bounce back into onboarding), then hand the page to Stripe.+ */+ const finishPremium = async (tier: PaidPlanTier) => {+ if (finishing()) return;+ setFinishing(true);+ try {+ if (!(await completeFlow())) return;+ trackCompleted('premium', false);+ try {+ // /welcome bounces authenticated users into the app.+ const successUrl = `${window.location.origin}${ROUTER_BASE_CONCAT}welcome?subscriptionSuccess=true&type=${tier}`;+ const checkoutUrl = await stripeServiceClient.createCheckoutSession({+ tier,+ successUrl,+ });+ if (!checkoutUrl) throw new Error('No checkout URL returned');+ window.location.href = checkoutUrl;+ } catch {+ toast.failure(+ "Couldn't start checkout — you can upgrade anytime from settings"+ );+ navigate(afterTarget(), { replace: true });+ }+ } finally {+ setFinishing(false);+ }+ };++ return { finishing, finishFree, finishPremium, afterTarget };+}diff --git a/apps/web/src/features/setup/flow/shared.tsx b/apps/web/src/features/setup/flow/shared.tsxnew file mode 100644index 0000000000..92ab662b8f--- /dev/null+++ b/apps/web/src/features/setup/flow/shared.tsx@@ -0,0 +1,143 @@+import ArrowRight from '@phosphor/arrow-right.svg';+import CheckIcon from '@phosphor/check.svg';+import { Button, Layer } from '@ui';+import { For, onCleanup, onMount } from 'solid-js';++/** Where the flow persists its current step, so full-page OAuth round-trips+ * (adding a Gmail inbox, Stripe checkout aborts) resume where they left. */+export const FLOW_STEP_STORAGE_KEY = 'onboarding-flow-step';++/** Where the flow persists its `?next` deep link — the inbox-link OAuth+ * callback returns to bare /onboarding, which would otherwise drop it. */+export const FLOW_NEXT_STORAGE_KEY = 'onboarding-flow-next';++export const isPlausibleEmail = (value: string) =>+ /^\S+@\S+\.\S+$/.test(value.trim());++/** The part after `@`, lowercased — `undefined` when it isn't an address. */+export function emailDomain(address: string | undefined): string | undefined {+ const at = address?.lastIndexOf('@') ?? -1;+ if (!address || at < 1 || at === address.length - 1) return undefined;+ return address.slice(at + 1).toLowerCase();+}++/** "macro.com" → "Macro": the domain root, capitalized. Whether a domain+ * deserves a team suggestion at all is judged server-side+ * (`OnboardingState.suggested_team_domain`) — no domain list lives here. */+export function deriveTeamName(domain: string): string {+ const root = domain.split('.')[0] ?? domain;+ return root.charAt(0).toUpperCase() + root.slice(1);+}++export function FormInput(props: {+ id: string;+ type?: string;+ placeholder?: string;+ value: string;+ autoFocus?: boolean;+ onInput: (value: string) => void;+}) {+ let inputEl: HTMLInputElement | undefined;+ onMount(() => {+ if (!props.autoFocus) return;+ // The Stepper's outin Transition mounts this JSX before attaching it to+ // the document, so poll until connected — cancelled on unmount, or a+ // node discarded before attaching would keep the rAF loop alive.+ let cancelled = false;+ onCleanup(() => {+ cancelled = true;+ });+ const focusWhenConnected = () => {+ if (cancelled || !inputEl) return;+ if (inputEl.isConnected) inputEl.focus({ preventScroll: true });+ else requestAnimationFrame(focusWhenConnected);+ };+ focusWhenConnected();+ });+ return (+ <input+ ref={(el) => (inputEl = el)}+ id={props.id}+ name={props.id}+ type={props.type ?? 'text'}+ placeholder={props.placeholder}+ value={props.value}+ autocomplete={props.id}+ onInput={(e) => props.onInput(e.currentTarget.value)}+ class="obf-input w-full px-4 py-3 rounded-lg border border-edge bg-surface text-sm text-ink placeholder:text-ink-placeholder focus:border-accent focus:outline-none transition-colors"+ />+ );+}++/**+ * Marketing-hero backdrop: an ink/surface wash plus a film-grain tile.+ * Both layers are pointer-transparent; page content must sit at z-10,+ * between the wash (z-0) and the grain (z-20).+ */+export function NoiseBackground() {+ return (+ <>+ <div+ aria-hidden="true"+ class="pointer-events-none absolute inset-0 z-0"+ style={{+ background:+ 'radial-gradient(120% 90% at 50% 100%, color-mix(in srgb, var(--color-ink) 11%, var(--color-surface)) 0%, var(--color-surface) 75%)',+ }}+ />+ <div+ aria-hidden="true"+ style={`position:absolute;top:0;bottom:0;left:50%;transform:translateX(-50%);width:100vw;pointer-events:none;z-index:20;opacity:0.05;mix-blend-mode:screen;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='300'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.6' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");background-size:300px 300px;-webkit-mask:linear-gradient(to bottom, transparent 0%, #000 12%, #000 100%);mask:linear-gradient(to bottom, transparent 0%, #000 12%, #000 100%)`}+ />+ </>+ );+}++/** Bordered card listing what connecting a tool actually does. */+export function FeatureList(props: { features: string[] }) {+ return (+ <Layer depth={2}>+ <div class="rounded-xl border border-ink/[0.06] bg-surface">+ <For each={props.features}>+ {(feature) => (+ <div class="flex items-start gap-2.5 border-b border-edge-muted px-4 py-3 text-sm text-ink-muted last:border-b-0">+ <CheckIcon class="mt-0.5 size-3.5 shrink-0 text-accent" />+ <span class="leading-snug">{feature}</span>+ </div>+ )}+ </For>+ </div>+ </Layer>+ );+}++export function SkipButton(props: {+ label?: string;+ disabled?: boolean;+ onClick: () => void;+}) {+ return (+ <Button+ variant="ghost"+ size="sm"+ class="self-center text-ink-muted"+ disabled={props.disabled}+ onClick={props.onClick}+ >+ {props.label ?? 'Skip for now'}+ </Button>+ );+}++export function ContinueButton(props: {+ label?: string;+ disabled?: boolean;+ onClick: () => void;+}) {+ return (+ <Button variant="cta" disabled={props.disabled} onClick={props.onClick}>+ {props.label ?? 'Continue'}+ <ArrowRight class="size-4" />+ </Button>+ );+}diff --git a/apps/web/src/features/setup/useConnectorConnect.ts b/apps/web/src/features/setup/useConnectorConnect.tsnew file mode 100644index 0000000000..c5ef8323b8--- /dev/null+++ b/apps/web/src/features/setup/useConnectorConnect.ts@@ -0,0 +1,62 @@+import type { FeaturedMcpServer } from '@core/component/AI/constant/mcpServers';+import { toast } from '@core/component/Toast/Toast';+import {+ useAddMcpServerMutation,+ useStartMcpAuthMutation,+} from '@queries/mcp-servers';+import type { StartAuthResponse } from '@service-cognition/generated/schemas';+import { type Accessor, createSignal } from 'solid-js';++/**+ * The connect-a-tool workflow shared by the setup surfaces: add the MCP+ * server if needed, then run OAuth in a popup. The popup opens synchronously,+ * while the click's transient activation is still live — opening after the+ * awaited mutations gets rejected by strict popup blockers. The OAuth URL is+ * assigned once it's known; severing `opener` keeps the provider page from+ * reaching back into the app (reverse tabnabbing).+ *+ * Completion is observed, not returned: the server reconciles the moment+ * OAuth completes, and the caller's polled servers query flips the state.+ */+export function createConnectorConnect(options: {+ server: FeaturedMcpServer;+ connected: Accessor<boolean>;+ authenticated: Accessor<boolean>;+}) {+ const addMutation = useAddMcpServerMutation();+ const authMutation = useStartMcpAuthMutation();+ const [busy, setBusy] = createSignal(false);++ const connect = async () => {+ if (options.authenticated() || busy()) return;+ setBusy(true);+ const popup = window.open('about:blank', '_blank');+ if (popup) popup.opener = null;+ try {+ if (!options.connected()) {+ await addMutation.mutateAsync({+ server_name: options.server.server_name,+ url: options.server.url,+ });+ }+ const result: StartAuthResponse = await authMutation.mutateAsync({+ server_name: options.server.server_name,+ server_url: options.server.url,+ });+ if (popup) {+ popup.location.href = result.authorization_url;+ } else {+ // Popup was blocked outright — fall back to a plain open (may+ // still be blocked, but nothing else to try).+ window.open(result.authorization_url, '_blank', 'noopener,noreferrer');+ }+ } catch {+ popup?.close();+ toast.failure(`Failed to connect ${options.server.server_name}`);+ } finally {+ setBusy(false);+ }+ };++ return { connect, busy };+}diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.tsindex f366312b52..94ad9e592e 100644--- a/apps/web/src/lib/analytics/app-events.ts+++ b/apps/web/src/lib/analytics/app-events.ts@@ -46,6 +46,46 @@ export type AppEvents = {tutorial_completed: { isFirstTime: boolean };tutorial_skipped: Record<string, unknown>;+ // --- Onboarding v4 (the full-screen /onboarding stepper) -----------------+ /**+ * Flow entered. `signup_method` is inferred from the inbox state at+ * entry: a Google SSO signup arrives with its Gmail inbox already+ * linked, an email-code signup with none. `entry_step` is where the+ * user landed ('email' unless a persisted step was restored).+ */+ onboarding_v4_started: {+ signup_method: 'google' | 'email_code';+ entry_step: string;+ };+ /** One per step transition: viewed on entry, completed/skipped on exit. */+ onboarding_v4_step: {+ step: string;+ index: number;+ state: 'viewed' | 'completed' | 'skipped';+ };+ /** A connect-inbox row was clicked (OAuth may still be abandoned). */+ onboarding_v4_email_connect_clicked: { slot: string };+ /** An inbox finished linking while onboarding. */+ onboarding_v4_email_connected: { connected_count: number };+ /** A connector completed OAuth from its step. */+ onboarding_v4_connector_connected: { connector: string };+ /** What happened on the team step. */+ onboarding_v4_team: {+ action: 'created' | 'joined_invite' | 'already_on_team';+ invites_sent?: number;+ used_domain_suggestion?: boolean;+ };+ /**+ * The flow finished (free, premium, or plan skipped) with a rollup of+ * everything connected along the way.+ */+ onboarding_v4_completed: {+ plan: 'free' | 'premium';+ plan_skipped: boolean;+ emails_connected: number;+ connectors_connected: string[];+ };+subscription_start: Record<string, unknown>;subscription_cancel: Record<string, unknown>;subscription_success: Record<string, unknown>;diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 2ade02583c..918d7ef2ee 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -544,10 +544,10 @@ export const BOT_MANAGEMENT_FLAG = 'bot-management';export const BOT_MANAGEMENT_OVERRIDE =resolveFeatureFlag('BOT_MANAGEMENT', DEV_MODE_ENV) || undefined;-// New split-screen onboarding (/setup): connect tools on the left, pick-// what to import on the right. Dev-mode default; override with-// VITE_ENABLE_NEW_ONBOARDING_V3.-export const ENABLE_NEW_ONBOARDING_V3 = resolveFeatureFlag(- 'ENABLE_NEW_ONBOARDING_V3',+// Onboarding v4: the full-screen stepper new users land in after signup+// (unified with /login), driving the import machinery with auto-import.+// Dev-mode default; override with VITE_ENABLE_ONBOARDING_V4.+export const ENABLE_ONBOARDING_V4 = resolveFeatureFlag(+ 'ENABLE_ONBOARDING_V4',DEV_MODE_ENV);diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.tsindex c5868a9924..c94e6314f4 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts@@ -155,6 +155,7 @@ export * from './notionDocMetaUrl';export * from './onboardingRow';export * from './onboardingRowCompletedAt';export * from './onboardingState';+export * from './onboardingStateSuggestedTeamDomain';export * from './onboardingStatus';export * from './patchChatRequest';export * from './patchChatRequestName';diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/onboardingState.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/onboardingState.tsindex b9717113ab..c85eddef9f 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/onboardingState.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/onboardingState.ts@@ -6,6 +6,7 @@*/import type { ConnectedServer } from './connectedServer';import type { OnboardingRow } from './onboardingRow';+import type { OnboardingStateSuggestedTeamDomain } from './onboardingStateSuggestedTeamDomain';/*** The onboarding aggregate served to the setup page. Import runs and@@ -16,4 +17,10 @@ export interface OnboardingState {connected_servers: ConnectedServer[];/** The user's onboarding row. */row: OnboardingRow;+ /** The account email's domain when it can back a domain team — i.e. it+is not a generic consumer provider — `None` otherwise. Judged with+the same list the teams service uses for domain auto-join and+claiming, so the client never suggests a domain team the server+would refuse. */+ suggested_team_domain?: OnboardingStateSuggestedTeamDomain;}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/onboardingStateSuggestedTeamDomain.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/onboardingStateSuggestedTeamDomain.tsnew file mode 100644index 0000000000..2fe13855a5--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/onboardingStateSuggestedTeamDomain.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * The account email's domain when it can back a domain team — i.e. it+is not a generic consumer provider — `None` otherwise. Judged with+the same list the teams service uses for domain auto-join and+claiming, so the client never suggests a domain team the server+would refuse.+ */+export type OnboardingStateSuggestedTeamDomain = string | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/onboarding.ts b/apps/web/src/lib/service-clients/service-cognition/onboarding.tsindex 064c755924..dcf31c5975 100644--- a/apps/web/src/lib/service-clients/service-cognition/onboarding.ts+++ b/apps/web/src/lib/service-clients/service-cognition/onboarding.ts@@ -52,6 +52,10 @@ export type ConnectedServer = {export type OnboardingState = {row: OnboardingRow;connected_servers: ConnectedServer[];+ /** The account email's domain when it can back a domain team (not a+ * generic consumer provider), null otherwise. Server-judged with the same+ * list the teams service uses for auto-join/claiming. */+ suggested_team_domain?: string | null;};export const onboardingClient = {diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.jsonindex ea9b06e59b..ab420e15ff 100644--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json@@ -3540,6 +3540,10 @@"row": {"$ref": "#/components/schemas/OnboardingRow","description": "The user's onboarding row."+ },+ "suggested_team_domain": {+ "type": ["string", "null"],+ "description": "The account email's domain when it can back a domain team — i.e. it\nis not a generic consumer provider — `None` otherwise. Judged with\nthe same list the teams service uses for domain auto-join and\nclaiming, so the client never suggests a domain team the server\nwould refuse."}}},diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsxindex 5da5b1aa26..f8c5708a3a 100644--- a/apps/web/src/routes/Root.tsx+++ b/apps/web/src/routes/Root.tsx@@ -13,7 +13,7 @@ import { usePendingNotificationNavigationEffect } from '@app/features/notificatiimport { InteractiveOnboardingModal } from '@app/features/onboarding/InteractiveOnboardingModal';import MobileWebSignup from '@app/features/onboarding/MobileWebSignup';import { useCheckoutCompletionListener } from '@app/features/paywall/use-checkout-completion-listener';-import { SetupPage } from '@app/features/setup/SetupPage';+import { OnboardingFlow } from '@app/features/setup/flow/OnboardingFlow';import { TeamInviteAcceptance } from '@app/features/team-invitations/TeamInviteAcceptance';import {AnalyticsContextProvider,@@ -35,7 +35,7 @@ import { LAYOUT_ROUTE } from '@components/app/split-layout/SplitLayoutRoute';import { clearLocalAuthSession } from '@core/auth/logout';import { ChatAttachmentsInit } from '@core/component/AI/signal/globalAttachments';import { ToastRegion } from '@core/component/Toast/ToastRegion';-import { ENABLE_NEW_ONBOARDING_V3 } from '@core/constant/featureFlags';+import { ENABLE_ONBOARDING_V4 } from '@core/constant/featureFlags';import { ChannelsContextProvider } from '@core/context/channels';import { EmailLinksContextProvider } from '@core/context/emailLinks';import { QuickAccessProvider } from '@core/context/quickAccess';@@ -94,6 +94,7 @@ import {type RoutePreloadFunc,Router,type RouterProps,+ useLocation,useSearchParams,} from '@solidjs/router';import {@@ -300,6 +301,12 @@ const { EmailCallback, CALLBACK_PATH, EmailLinkCallback, LINK_CALLBACK_PATH } =successPath: '/',});+/** The retired /setup path forwards to the onboarding flow, query intact. */+function SetupRedirect() {+ const location = useLocation();+ return <Navigate href={`/onboarding${location.search}`} />;+}+const ROUTES: RouteDefinition[] = [LAYOUT_ROUTE,/** BEGIN - APP ROUTES */@@ -422,26 +429,26 @@ const ROUTES: RouteDefinition[] = [},{path: '/onboarding',+ // Flag-gated at the route, not just the redirect: with the flag off a+ // direct visit must not touch the onboarding backend (reading it+ // creates the flow's row and starts gathers).component: () =>isNativeMobilePlatform() ? (<MobileOnboarding />- ) : (+ ) : !ENABLE_ONBOARDING_V4 ? (<Navigate href="/login" />+ ) : (+ <OnboardingFlow />),},{+ // The old split-screen /setup surface is retired; the onboarding flow+ // lives at /onboarding now. Preserve the query (?next deep links).+ // Flag off, /setup must go home — forwarding would land flag-off web+ // users on /login and native users on the MobileOnboarding screen.path: '/setup',- // Flag-gated at the route, not just the redirect: with the flag off a- // direct /setup visit must not touch the onboarding backend (reading- // it creates the flow's row and starts gathers).component: () =>- !ENABLE_NEW_ONBOARDING_V3 ? (- <Navigate href="/" />- ) : isNativeMobilePlatform() ? (- <Navigate href="/onboarding" />- ) : (- <SetupPage />- ),+ ENABLE_ONBOARDING_V4 ? <SetupRedirect /> : <Navigate href="/" />,},{path: '/team-invite',@@ -578,7 +585,7 @@ function InitialInteractiveOnboardingModal() {open() &&// The new split-screen onboarding replaces this modal on desktop; the// Layout redirect sends first-time users to /setup instead.- (!ENABLE_NEW_ONBOARDING_V3 || isMobile()) &&+ (!ENABLE_ONBOARDING_V4 || isMobile()) &&!isNativeMobilePlatform() &&userInfoQuery.data?.authenticated === true &&(userInfoQuery.data.tutorialComplete === false || onboardingStarted());diff --git a/crates/generic_email_domains/Cargo.toml b/crates/generic_email_domains/Cargo.tomlnew file mode 100644index 0000000000..83277c2d3d--- /dev/null+++ b/crates/generic_email_domains/Cargo.toml@@ -0,0 +1,8 @@+[package]+name = "generic_email_domains"+version = "0.1.0"+publish = false+edition = "2024"++[dependencies]+workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/crates/generic_email_domains/src/lib.rs b/crates/generic_email_domains/src/lib.rsnew file mode 100644index 0000000000..fbcce058a7--- /dev/null+++ b/crates/generic_email_domains/src/lib.rs@@ -0,0 +1,86 @@+#![deny(missing_docs)]+//! The canonical list of generic (free / consumer) email provider domains.+//!+//! This is the single source of truth for "is this a company domain?"+//! wherever that judgment drives team behavior: signup-time domain+//! auto-join, claiming a domain on team creation, and the onboarding+//! flow's team suggestions all consult this list, so the UI can never+//! promise a domain team the server would refuse. (The CRM keeps its own,+//! much broader list for filtering bulk-mail senders — a different+//! concept; do not merge them.)++#[cfg(test)]+mod test;++/// Generic (free / consumer) email provider domains, sorted for binary+/// search. Keep entries lowercase and in order.+pub const GENERIC_EMAIL_DOMAINS: &[&str] = &[+ "126.com",+ "163.com",+ "aol.com",+ "att.net",+ "bellsouth.net",+ "btinternet.com",+ "charter.net",+ "comcast.net",+ "cox.net",+ "daum.net",+ "duck.com",+ "earthlink.net",+ "fastmail.com",+ "free.fr",+ "gmail.com",+ "gmx.com",+ "gmx.de",+ "gmx.net",+ "googlemail.com",+ "hey.com",+ "hotmail.co.uk",+ "hotmail.com",+ "hotmail.fr",+ "icloud.com",+ "laposte.net",+ "live.com",+ "mac.com",+ "mail.com",+ "mail.ru",+ "me.com",+ "msn.com",+ "naver.com",+ "orange.fr",+ "outlook.com",+ "pm.me",+ "proton.me",+ "protonmail.com",+ "qq.com",+ "rediffmail.com",+ "rocketmail.com",+ "sbcglobal.net",+ "seznam.cz",+ "sina.com",+ "sky.com",+ "t-online.de",+ "tuta.com",+ "tutanota.com",+ "verizon.net",+ "wanadoo.fr",+ "web.de",+ "yahoo.co.in",+ "yahoo.co.uk",+ "yahoo.com",+ "yahoo.fr",+ "yandex.com",+ "yandex.ru",+ "ymail.com",+ "zoho.com",+];++/// Returns true when the email domain belongs to a generic (free /+/// consumer) email provider that may not be used for automatic team+/// joining. Matching is case-insensitive.+pub fn is_generic_email_domain(domain: &str) -> bool {+ let domain = domain.to_ascii_lowercase();+ GENERIC_EMAIL_DOMAINS+ .binary_search(&domain.as_str())+ .is_ok()+}diff --git a/crates/generic_email_domains/src/test.rs b/crates/generic_email_domains/src/test.rsnew file mode 100644index 0000000000..a0671185fd--- /dev/null+++ b/crates/generic_email_domains/src/test.rs@@ -0,0 +1,31 @@+use super::*;++#[test]+fn list_is_sorted_and_lowercase() {+ // binary_search only works on a sorted list; a bad edit here would+ // silently misclassify domains.+ let mut sorted = GENERIC_EMAIL_DOMAINS.to_vec();+ sorted.sort_unstable();+ assert_eq!(GENERIC_EMAIL_DOMAINS, sorted.as_slice());+ for domain in GENERIC_EMAIL_DOMAINS {+ assert_eq!(*domain, domain.to_ascii_lowercase());+ }+}++#[test]+fn matches_generic_providers() {+ assert!(is_generic_email_domain("gmail.com"));+ assert!(is_generic_email_domain("outlook.com"));+ assert!(is_generic_email_domain("yahoo.co.uk"));+}++#[test]+fn is_case_insensitive() {+ assert!(is_generic_email_domain("Gmail.COM"));+}++#[test]+fn allows_company_domains() {+ assert!(!is_generic_email_domain("macro.com"));+ assert!(!is_generic_email_domain("acme.dev"));+}diff --git a/crates/onboarding/Cargo.toml b/crates/onboarding/Cargo.tomlindex 8919f15ab8..6bc3e9468d 100644--- a/crates/onboarding/Cargo.toml+++ b/crates/onboarding/Cargo.toml@@ -8,6 +8,7 @@ version = "0.1.0"anyhow = { workspace = true }axum = { workspace = true }chrono = { workspace = true }+generic_email_domains = { path = "../generic_email_domains" }import = { path = "../import" }macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum",diff --git a/crates/onboarding/src/domain/models.rs b/crates/onboarding/src/domain/models.rsindex 07ca125184..c8e4974b2c 100644--- a/crates/onboarding/src/domain/models.rs+++ b/crates/onboarding/src/domain/models.rs@@ -58,4 +58,10 @@ pub struct OnboardingState {pub row: OnboardingRow,/// The user's MCP server connections.pub connected_servers: Vec<ConnectedServer>,+ /// The account email's domain when it can back a domain team — i.e. it+ /// is not a generic consumer provider — `None` otherwise. Judged with+ /// the same list the teams service uses for domain auto-join and+ /// claiming, so the client never suggests a domain team the server+ /// would refuse.+ pub suggested_team_domain: Option<String>,}diff --git a/crates/onboarding/src/domain/service.rs b/crates/onboarding/src/domain/service.rsindex 8292d88b63..2079723229 100644--- a/crates/onboarding/src/domain/service.rs+++ b/crates/onboarding/src/domain/service.rs@@ -9,8 +9,10 @@use super::models::{ConnectedServer, OnboardingRow, OnboardingState, OnboardingStatus};use super::ports::{OnboardingError, OnboardingRepo, Result};+use generic_email_domains::is_generic_email_domain;use import::domain::models::{ImportSource, Initiator};use import::domain::service::ImportService;+use macro_user_id::email::ReadEmailParts;use macro_user_id::user_id::MacroUserIdStr;use mcp_client::domain::ports::McpServerStore;use std::sync::Arc;@@ -18,6 +20,15 @@ use std::sync::Arc;#[cfg(test)]mod test;+/// The account email's domain when it can back a domain team (not a+/// generic consumer provider), `None` otherwise. The same judgment the+/// teams service applies to domain auto-join and claiming.+fn suggested_team_domain(user: &MacroUserIdStr<'_>) -> Option<String> {+ let email = user.email_part().lowercase();+ let domain = email.domain_part();+ (!is_generic_email_domain(domain)).then(|| domain.to_owned())+}+/// The API the onboarding router (and host-service hooks) talk to.pub trait OnboardingService: Send + Sync + 'static {/// The full aggregate for the user. While the flow is active this also@@ -124,6 +135,7 @@ whereOk(OnboardingState {row,connected_servers,+ suggested_team_domain: suggested_team_domain(&user),})}diff --git a/crates/onboarding/src/domain/service/test.rs b/crates/onboarding/src/domain/service/test.rsindex 5302bb6f9a..2af0e6aefa 100644--- a/crates/onboarding/src/domain/service/test.rs+++ b/crates/onboarding/src/domain/service/test.rs@@ -273,3 +273,27 @@ async fn reconcile_ignores_users_who_never_entered_the_flow() {service.reconcile(user()).await.expect("reconcile");assert!(import.gathers.lock().unwrap().is_empty());}++#[test]+fn suggested_team_domain_offers_custom_domains_only() {+ // Custom domain: worth suggesting a domain team — the same judgment+ // the teams service applies when claiming a domain on create.+ assert_eq!(suggested_team_domain(&user()).as_deref(), Some("macro.com"));++ // Generic consumer provider: no domain team to suggest.+ let gmail =+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).expect("valid test user id");+ assert_eq!(suggested_team_domain(&gmail), None);+}++#[tokio::test]+async fn get_state_carries_the_suggested_team_domain() {+ let service = OnboardingServiceImpl::new(+ MockRepo::new(OnboardingStatus::Active),+ Arc::new(MockStore { records: vec![] }),+ Arc::new(MockImport::default()),+ );++ let state = service.get_state(user()).await.expect("get_state");+ assert_eq!(state.suggested_team_domain.as_deref(), Some("macro.com"));+}diff --git a/crates/teams/Cargo.toml b/crates/teams/Cargo.tomlindex 0b25e0af47..35ae8000dd 100644--- a/crates/teams/Cargo.toml+++ b/crates/teams/Cargo.toml@@ -71,6 +71,7 @@ tracing = { workspace = true }uuid = { workspace = true }entity_access = { path = "../entity_access", default-features = false }+generic_email_domains = { path = "../generic_email_domains" }# Async runtime (for ports)tokio = { workspace = true, optional = true }diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rsindex e045a9ec41..ed6114a268 100644--- a/crates/teams/src/domain/model.rs+++ b/crates/teams/src/domain/model.rs@@ -298,82 +298,11 @@ pub struct TeamCheckoutSessionRequest {pub team_plan: TeamPlan,}-/// Email domains of generic (free / consumer) email providers.-///-/// Teams may not enable automatic domain joining for these domains — a-/// match on e.g. `gmail.com` would auto-join complete strangers to the-/// team. Entries must be lowercase and sorted (verified by test) so-/// [`is_generic_email_domain`] can binary search.-pub const GENERIC_EMAIL_DOMAINS: &[&str] = &[- "126.com",- "163.com",- "aol.com",- "att.net",- "bellsouth.net",- "btinternet.com",- "charter.net",- "comcast.net",- "cox.net",- "daum.net",- "duck.com",- "earthlink.net",- "fastmail.com",- "free.fr",- "gmail.com",- "gmx.com",- "gmx.de",- "gmx.net",- "googlemail.com",- "hey.com",- "hotmail.co.uk",- "hotmail.com",- "hotmail.fr",- "icloud.com",- "laposte.net",- "live.com",- "mac.com",- "mail.com",- "mail.ru",- "me.com",- "msn.com",- "naver.com",- "orange.fr",- "outlook.com",- "pm.me",- "proton.me",- "protonmail.com",- "qq.com",- "rediffmail.com",- "rocketmail.com",- "sbcglobal.net",- "seznam.cz",- "sina.com",- "sky.com",- "t-online.de",- "tuta.com",- "tutanota.com",- "verizon.net",- "wanadoo.fr",- "web.de",- "yahoo.co.in",- "yahoo.co.uk",- "yahoo.com",- "yahoo.fr",- "yandex.com",- "yandex.ru",- "ymail.com",- "zoho.com",-];--/// Returns true when the email domain belongs to a generic (free /-/// consumer) email provider that may not be used for automatic team-/// joining. Matching is case-insensitive.-pub fn is_generic_email_domain(domain: &str) -> bool {- let domain = domain.to_ascii_lowercase();- GENERIC_EMAIL_DOMAINS- .binary_search(&domain.as_str())- .is_ok()-}+// Teams may not enable automatic domain joining for generic domains — a+// match on e.g. `gmail.com` would auto-join complete strangers to the+// team. The list lives in its own crate so lightweight consumers (the+// onboarding flow's team suggestion) share the same judgment.+pub use generic_email_domains::{GENERIC_EMAIL_DOMAINS, is_generic_email_domain};/// The Team struct#[derive(Debug, Clone, serde::Serialize)]