Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(onboarding): 30-day trial, layered onboarding + auth with isolated browser tests (#7507)

teo7628c4344555
diff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.yml
index 089a0bdc07..31612ad4ee 100644
--- a/.github/workflows/web-app-check-main.yml
+++ b/.github/workflows/web-app-check-main.yml
@@ -191,6 +191,9 @@ jobs:
- name: Test
run: bunx vitest
working-directory: apps/web
+ - name: Sign-up Browser Tests
+ run: just test-signup-browser
+ working-directory: apps/web
- name: Teardown Nix
if: always()
uses: './.github/actions/teardown-nix'
diff --git a/apps/docs/account/billing.mdx b/apps/docs/account/billing.mdx
index 033e04348e..32ce7552a0 100644
--- a/apps/docs/account/billing.mdx
+++ b/apps/docs/account/billing.mdx
@@ -1,12 +1,12 @@
---
title: "Billing & Plans"
icon: "credit-card"
-description: "Macro's free and Premium plans, how AI usage is included, and how to manage your subscription."
+description: "Macro's Guest access and Premium subscriptions, how AI usage is included, and how to manage your subscription."
---
-Macro offers one paid plan for new subscriptions, priced per person. The price is the same whether you're solo or on a team.
+Join a workspace as a Guest for free. Macro offers one paid plan for new subscriptions, priced per person. The price is the same whether you're solo or on a team.
-| | Free | Premium |
+| | Guest | Premium |
| --- | --- | --- |
| Price | \$0 | \$40 / month |
| AI agent | Fast model only | All models |
@@ -14,7 +14,7 @@ Macro offers one paid plan for new subscriptions, priced per person. The price i
| Beyond included AI | — | Credits or usage billing |
| Storage | 5 GB | 1 TB |
-Paid teams require a paid seat for every member. Free teams can include unpaid members. New paid seats use Premium. Max is unavailable for new purchases and upgrades. Existing Max seats keep their plan and can move to Premium from **Settings → Team**. Moving a seat is prorated for the rest of the billing period. Your current plan is shown in **Settings → Billing**, with an **Upgrade** button if you're on the free plan and a **Switch to Premium** option if you're on Max.
+Paid teams require a paid seat for every member. Free teams can include unpaid members. New paid seats use Premium. Max is unavailable for new purchases and upgrades. Existing Max seats keep their plan and can move to Premium from **Settings → Team**. Moving a seat is prorated for the rest of the billing period. Your current plan is shown in **Settings → Billing**, with an **Upgrade** button if you have Guest access and a **Switch to Premium** option if you're on Max.
## AI usage
diff --git a/apps/docs/account/teams.mdx b/apps/docs/account/teams.mdx
index 47c05a621f..c52edbcddb 100644
--- a/apps/docs/account/teams.mdx
+++ b/apps/docs/account/teams.mdx
@@ -13,7 +13,7 @@ Macro works solo, but everything is better with friends. Teams get auto-shared t
Click **Team** in the bottom left to create a team. You can add the first members right there, or invite more later by email from **Settings → Team**. Invitees see the pending invitation when they sign in. Owners can also copy an invite link for any pending invite and share it directly, instead of relying on email.
<Note>
- There's no free plan for teams; every member needs a paid seat. See [Billing & plans](/account/billing).
+ Team subscriptions require a paid seat for every member. See [Billing & plans](/account/billing).
</Note>
## Auto-join on domain
diff --git a/apps/docs/faq.mdx b/apps/docs/faq.mdx
index d51ec93499..18c96c7cfb 100644
--- a/apps/docs/faq.mdx
+++ b/apps/docs/faq.mdx
@@ -69,7 +69,7 @@ description: "How Macro compares to Notion, Superhuman, and Slack, plus licensin
</Accordion>
<Accordion title='How do teams work in Macro? Do I need a "team"?'>
- Macro is designed for solo and team use. Of course, everything is better with friends. The pricing for Macro whether you are on a team or personal plan is the same; Teams exist just to help you collaborate better as a group. Keep in mind there is no free plan for teams, however. Teams give:
+ Macro is designed for solo and team use. Of course, everything is better with friends. The pricing for Macro whether you are on a team or personal plan is the same; Teams exist just to help you collaborate better as a group. Team subscriptions require a paid seat for every member. Teams give:
1. Auto-shared emails, tasks and calls, without having to explicitly share everything. For example, when you're working as a team you want all emails to be shared in our CRM module, engineering tasks should be visible by everyone, and having all calls transcribed and stored to the Team gives you a nice team-level memory of all of your conversations.
2. Team-level memory for your agents. Agents remember not just your personal chat history (like with Claude or ChatGPT's memory system), but everything going on across tasks your team is working on, emails, docs, and calls that the team has had recently!
diff --git a/apps/docs/product/agents.mdx b/apps/docs/product/agents.mdx
index 0da43c30eb..f9ec0e5ae9 100644
--- a/apps/docs/product/agents.mdx
+++ b/apps/docs/product/agents.mdx
@@ -77,7 +77,7 @@ Agents can run on a schedule. An automation is a saved prompt that runs on its o
A model picker sits in the chat input. You can choose a model per chat depending on how difficult you deem the question. Your choice is remembered for that chat and carried forward when you start a new one from the composer.
-On the free plan you can only use Haiku, the fast model. Premium and existing Max subscriptions unlock the rest, including Opus 5, Fable 5.1 (Anthropic's most capable model), and GPT-6 Astra (OpenAI's). Heavier models draw down your included AI faster, and the picker shows by how much: Opus uses about 2.5×, and Fable and Astra about 5×, what Sonnet does for the same conversation.
+With Guest access you can only use Haiku, the fast model. Premium and existing Max subscriptions unlock the rest, including Opus 5, Fable 5.1 (Anthropic's most capable model), and GPT-6 Astra (OpenAI's). Heavier models draw down your included AI faster, and the picker shows by how much: Opus uses about 2.5×, and Fable and Astra about 5×, what Sonnet does for the same conversation.
<Frame>
![The model picker, showing the available models](/images/model_options.png)
diff --git a/apps/marketing/src/app/main/App.tsx b/apps/marketing/src/app/main/App.tsx
index 85a92c33d3..4824c17379 100644
--- a/apps/marketing/src/app/main/App.tsx
+++ b/apps/marketing/src/app/main/App.tsx
@@ -29,7 +29,7 @@ import {
function JourneyEntry() {
onMount(() => {
- window.location.replace('/start');
+ window.location.replace('/app/signup');
});
return null;
}
diff --git a/apps/marketing/src/app/routes/RouteEmail.tsx b/apps/marketing/src/app/routes/RouteEmail.tsx
index 12a6394ce5..46c8543c75 100644
--- a/apps/marketing/src/app/routes/RouteEmail.tsx
+++ b/apps/marketing/src/app/routes/RouteEmail.tsx
@@ -74,10 +74,10 @@ const faqItems = [
),
},
{
- q: 'Is there a free plan?',
+ q: 'Can I join as a Guest for free?',
a: (
<>
- Yes. The free plan includes email alongside chat, documents, tasks, and
+ Yes. Guest access includes email alongside chat, documents, tasks, and
AI, with usage limits. See <a href="/pricing">pricing</a> for current
account, storage, and AI limits.
</>
diff --git a/apps/marketing/src/app/routes/RoutePricing.tsx b/apps/marketing/src/app/routes/RoutePricing.tsx
index 8d131e6c14..a4317bdfaf 100644
--- a/apps/marketing/src/app/routes/RoutePricing.tsx
+++ b/apps/marketing/src/app/routes/RoutePricing.tsx
@@ -71,6 +71,7 @@ function PlanCard(props: {
secondaryLine?: string;
note: JSX.Element;
buttonName: string;
+ buttonLabel?: string;
}) {
return (
<section
@@ -189,7 +190,7 @@ function PlanCard(props: {
width: '100%',
}}
>
- Get started
+ {props.buttonLabel ?? 'Get started'}
</a>
</div>
</section>
@@ -218,17 +219,18 @@ function PricingPlans() {
}}
>
<PlanCard
- eyebrow="Free"
+ eyebrow="Guest"
price="$0"
- primaryLine="for personal use"
- secondaryLine="free forever"
+ primaryLine="to join a workspace"
+ secondaryLine="no subscription required"
note={
<>
- <strong>Free includes:</strong> "Sent with Macro" in email
+ <strong>Guest access includes:</strong> "Sent with Macro" in email
signatures, limits on storage and AI.
</>
}
buttonName="pricing_free_connect_google"
+ buttonLabel="Join as Guest"
/>
<PlanCard
accent
@@ -369,7 +371,7 @@ function ComparisonGrid() {
return (
<section
- aria-label="Free versus paid comparison"
+ aria-label="Guest access versus paid comparison"
style={{
'box-sizing': 'border-box',
display: 'grid',
@@ -399,7 +401,7 @@ function ComparisonGrid() {
>
<div aria-hidden="true" />
<div style={{ 'text-align': 'center' }}>
- <div style={comparisonPlanHeadingStyle('var(--c1)')}>Free</div>
+ <div style={comparisonPlanHeadingStyle('var(--c1)')}>Guest</div>
<div
style={{
color: 'var(--c4)',
@@ -797,8 +799,8 @@ const faqItems: Array<{ q: string; a: JSX.Element }> = [
Macro works great solo or as a team, and pricing is the same either way.
Teams share email, tasks, documents, and calls through workspace
permissions. Agents can search and read the work you have access to, and
- use memory built from your workspace activity. Note there is no free
- plan for teams.
+ use memory built from your workspace activity. Team subscriptions
+ require a paid seat for every member.
</>
),
},
@@ -971,7 +973,7 @@ export const RoutePricing: Component = () => {
setPageSeo({
title: 'Pricing — Macro',
description:
- 'Macro is free for personal use. The paid plan is $40 per seat per month for the first 5 seats, then $80. Every module is included on every plan — we charge for limits and team features, not feature gates.',
+ 'Join a workspace as a Guest for free. The paid plan is $40 per seat per month for the first 5 seats, then $80. Every module is included on every plan — we charge for limits and team features, not feature gates.',
path: '/pricing',
});
diff --git a/apps/marketing/src/app/routes/RouteTasks.tsx b/apps/marketing/src/app/routes/RouteTasks.tsx
index 322825fd3a..8054210fe1 100644
--- a/apps/marketing/src/app/routes/RouteTasks.tsx
+++ b/apps/marketing/src/app/routes/RouteTasks.tsx
@@ -69,11 +69,11 @@ const tasksFaq = [
a: 'No. Our code is public. Your tasks, messages, and docs are not, and they follow your sharing settings.',
},
{
- q: 'Is there a free plan?',
+ q: 'Can I join as a Guest for free?',
a: (
<>
- Yes. Tasks come with email, chat, docs, and agents. See{' '}
- <a href="/pricing">pricing</a> for the current limits.
+ Yes. Guest access includes tasks with email, chat, docs, and agents.
+ See <a href="/pricing">pricing</a> for the current limits.
</>
),
},
diff --git a/apps/marketing/src/features/marketing/components/SiteHeader.tsx b/apps/marketing/src/features/marketing/components/SiteHeader.tsx
index d29eb98676..3feea58980 100644
--- a/apps/marketing/src/features/marketing/components/SiteHeader.tsx
+++ b/apps/marketing/src/features/marketing/components/SiteHeader.tsx
@@ -180,7 +180,7 @@ export function SiteHeader(props: { hideOpenApp?: boolean }) {
<a
class="site-nav-start"
target="_self"
- href={import.meta.env.DEV ? '/onboarding-preview.html' : '/app'}
+ href="/app/signup"
onPointerEnter={moveGlow}
onPointerMove={moveGlow}
onPointerLeave={stopGlow}
diff --git a/apps/marketing/src/features/marketing/components/email/EmailComparison.tsx b/apps/marketing/src/features/marketing/components/email/EmailComparison.tsx
index 6a2785b280..547e589007 100644
--- a/apps/marketing/src/features/marketing/components/email/EmailComparison.tsx
+++ b/apps/marketing/src/features/marketing/components/email/EmailComparison.tsx
@@ -29,7 +29,7 @@ const comparisonRows: ComparisonRow[] = [
feature: 'Agents draft & send for you',
cells: [true, 'partial', 'partial', 'partial'],
},
- { feature: 'Free plan', cells: [true, false, true, true] },
+ { feature: 'No-cost access', cells: [true, false, true, true] },
{
feature: 'Email, chat & tasks in one place',
cells: [true, false, 'partial', false],
diff --git a/apps/marketing/src/features/marketing/core/navigation.ts b/apps/marketing/src/features/marketing/core/navigation.ts
index ff5f7619e8..8ecf56d584 100644
--- a/apps/marketing/src/features/marketing/core/navigation.ts
+++ b/apps/marketing/src/features/marketing/core/navigation.ts
@@ -21,7 +21,7 @@ export const RESOURCE_PAGES = [
/** Full document navigation keeps the app and marketing CSS independent. */
export function journeyHref() {
- if (typeof window === 'undefined') return '/start';
+ if (typeof window === 'undefined') return '/app/signup';
try {
const active = JSON.parse(
sessionStorage.getItem('onboarding-flow-step') ?? 'null'
@@ -30,5 +30,5 @@ export function journeyHref() {
} catch {
// An old or unavailable storage record must not prevent navigation.
}
- return '/start';
+ return '/app/signup';
}
diff --git a/apps/marketing/src/features/marketing/views/ProductChannelsPage.tsx b/apps/marketing/src/features/marketing/views/ProductChannelsPage.tsx
index deba0380a5..6f6a670ab8 100644
--- a/apps/marketing/src/features/marketing/views/ProductChannelsPage.tsx
+++ b/apps/marketing/src/features/marketing/views/ProductChannelsPage.tsx
@@ -202,11 +202,11 @@ export function RouteChannels() {
a: 'No. Everything on this page is a local sample. Nothing you type here leaves your browser.',
},
{
- q: 'Is there a free plan?',
+ q: 'Can I join as a Guest for free?',
a: (
<>
- Yes. See <a href="/pricing">pricing</a> for current plans and
- limits.
+ Yes. Guest access is free. See <a href="/pricing">pricing</a>{' '}
+ for current access and limits.
</>
),
},
diff --git a/apps/marketing/src/features/setup/Homepage.tsx b/apps/marketing/src/features/setup/Homepage.tsx
index 9b9a93fbf4..d9b9cf053a 100644
--- a/apps/marketing/src/features/setup/Homepage.tsx
+++ b/apps/marketing/src/features/setup/Homepage.tsx
@@ -34,10 +34,7 @@ export function Homepage() {
onContinue={() => {}}
action={
<div class="homepage-hero-action mt-6 flex justify-center pb-5">
- <a
- class="site-nav-start homepage-hero-cta"
- href={import.meta.env.DEV ? '/onboarding-preview.html' : '/app'}
- >
+ <a class="site-nav-start homepage-hero-cta" href="/app/signup">
Get Started
</a>
</div>
diff --git a/apps/marketing/src/features/setup/components/OnboardingShell.tsx b/apps/marketing/src/features/setup/components/OnboardingShell.tsx
index 5700e139d7..068988c4c9 100644
--- a/apps/marketing/src/features/setup/components/OnboardingShell.tsx
+++ b/apps/marketing/src/features/setup/components/OnboardingShell.tsx
@@ -15,6 +15,7 @@ export function OnboardingShell(props: {
heroFooter?: JSX.Element;
below?: JSX.Element;
explainer?: JSX.Element;
+ explainerLabel?: string;
}) {
const detailsId = createUniqueId();
const explainer = createMemo(() => props.explainer);
@@ -133,7 +134,7 @@ export function OnboardingShell(props: {
});
}}
>
- Read more
+ {props.explainerLabel ?? 'Read more'}
<ArrowDownIcon class="size-5" aria-hidden="true" />
</button>
</Show>
diff --git a/apps/marketing/src/features/setup/components/PaymentPreview.test.tsx b/apps/marketing/src/features/setup/components/PaymentPreview.test.tsx
new file mode 100644
index 0000000000..41fdd882b7
--- /dev/null
+++ b/apps/marketing/src/features/setup/components/PaymentPreview.test.tsx
@@ -0,0 +1,26 @@
+import { cleanup, fireEvent, render } from '@solidjs/testing-library';
+import { afterEach, expect, it } from 'vitest';
+import { PaymentPreview } from './PaymentPreview';
+
+afterEach(cleanup);
+
+it('reveals billing details after a full test number and hides them when cleared', () => {
+ const view = render(() => <PaymentPreview />);
+ const card = view.getByRole('textbox', { name: 'Card number' });
+ const details = [
+ 'Expiration',
+ 'Security code',
+ 'Country or region',
+ 'ZIP code',
+ ];
+ for (const label of details) expect(view.queryByText(label)).toBeNull();
+
+ fireEvent.input(card, { target: { value: '4242' } });
+ expect(view.queryByText('Expiration')).toBeNull();
+
+ fireEvent.input(card, { target: { value: '4242 4242 4242 4242' } });
+ for (const label of details) expect(view.getByText(label)).toBeTruthy();
+
+ fireEvent.input(card, { target: { value: '' } });
+ for (const label of details) expect(view.queryByText(label)).toBeNull();
+});
diff --git a/apps/marketing/src/features/setup/components/PaymentPreview.tsx b/apps/marketing/src/features/setup/components/PaymentPreview.tsx
new file mode 100644
index 0000000000..d0bc0f5af8
--- /dev/null
+++ b/apps/marketing/src/features/setup/components/PaymentPreview.tsx
@@ -0,0 +1,100 @@
+import GoogleIcon from '@icon/macro-google.svg';
+import CardIcon from '@phosphor/credit-card.svg';
+import AppleIcon from '@phosphor-fill/apple-logo-fill.svg';
+import { createSignal, For, Show } from 'solid-js';
+
+/** Local-only payment interaction for the development-only onboarding preview. */
+export function PaymentPreview() {
+ const [wallet, setWallet] = createSignal<string>();
+ const [hasCardNumber, setHasCardNumber] = createSignal(false);
+ return (
+ <div class="flex flex-col gap-4">
+ <div class="grid grid-cols-2 gap-3">
+ <button
+ type="button"
+ aria-label="Preview Apple Pay"
+ onClick={() => setWallet('Apple Pay')}
+ class="flex h-11 items-center justify-center gap-1 rounded-lg bg-ink text-lg font-medium text-surface focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ink"
+ >
+ <AppleIcon class="size-5" aria-hidden="true" /> Pay
+ </button>
+ <button
+ type="button"
+ aria-label="Preview Google Pay"
+ onClick={() => setWallet('Google Pay')}
+ class="flex h-11 items-center justify-center gap-1.5 rounded-lg border border-edge bg-surface text-lg font-medium text-ink focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ink"
+ >
+ <GoogleIcon class="size-4" aria-hidden="true" /> Pay
+ </button>
+ </div>
+ <Show when={wallet()}>
+ <p role="status" class="text-xs leading-5 text-ink-muted">
+ {wallet()} is shown for preview. No payment will be taken.
+ </p>
+ </Show>
+ <div class="flex items-center gap-3 text-[11px] text-ink-extra-muted">
+ <span class="h-px flex-1 bg-edge" />
+ Or pay with card
+ <span class="h-px flex-1 bg-edge" />
+ </div>
+ <div
+ class="flex flex-col gap-3"
+ role="group"
+ aria-label="Card payment preview"
+ >
+ <label class="flex flex-col gap-1.5">
+ <span class="text-xs text-ink-muted">Card number</span>
+ <div class="relative">
+ <input
+ type="text"
+ inputmode="numeric"
+ autocomplete="off"
+ placeholder="4242 4242 4242 4242"
+ maxlength="23"
+ onInput={(event) => {
+ const digits = event.currentTarget.value.replace(/\D/g, '');
+ setHasCardNumber(digits.length >= 15);
+ }}
+ class="h-11 w-full rounded-lg border border-edge bg-ink/[0.025] pl-3 pr-11 text-sm text-ink placeholder:text-ink-extra-muted focus:outline-2 focus:outline-ink"
+ />
+ <CardIcon
+ class="pointer-events-none absolute right-3 top-1/2 size-5 -translate-y-1/2 text-ink-extra-muted"
+ aria-hidden="true"
+ />
+ </div>
+ </label>
+ <Show when={hasCardNumber()}>
+ <div class="grid grid-cols-2 gap-3">
+ <For
+ each={[
+ ['Expiration', 'MM / YY'],
+ ['Security code', 'CVC'],
+ ]}
+ >
+ {([label, placeholder]) => (
+ <div class="flex flex-col gap-1.5">
+ <span class="text-xs text-ink-muted">{label}</span>
+ <div class="flex h-11 items-center rounded-lg border border-edge bg-ink/[0.025] px-3 text-sm text-ink-extra-muted">
+ {placeholder}
+ </div>
+ </div>
+ )}
+ </For>
+ </div>
+ <div class="flex flex-col gap-1.5">
+ <span class="text-xs text-ink-muted">Country or region</span>
+ <div class="flex h-11 items-center rounded-lg border border-edge bg-ink/[0.025] px-3 text-sm text-ink-muted">
+ United States
+ </div>
+ </div>
+ <div class="flex flex-col gap-1.5">
+ <span class="text-xs text-ink-muted">ZIP code</span>
+ <div class="flex h-11 items-center rounded-lg border border-edge bg-ink/[0.025] px-3 text-sm text-ink-extra-muted">
+ 12345
+ </div>
+ </div>
+ </Show>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/marketing/src/features/setup/components/PlanComparison.tsx b/apps/marketing/src/features/setup/components/PlanComparison.tsx
new file mode 100644
index 0000000000..85a34029ed
--- /dev/null
+++ b/apps/marketing/src/features/setup/components/PlanComparison.tsx
@@ -0,0 +1,108 @@
+import { For } from 'solid-js';
+import { PLAN_COMPARISON } from '../core/planComparison';
+
+export function PlanComparison(props: {
+ onContinueGuest: () => void;
+ onBackToPro: () => void;
+}) {
+ return (
+ <section class="mx-auto w-full max-w-[608px] px-6 pb-20 pt-20 font-[Inter_Variable] text-sm leading-7 text-ink-muted sm:pb-28 sm:pt-24 sm:text-[15px]">
+ <div class="mb-10 h-px w-12 bg-edge" aria-hidden="true" />
+ <p class="mb-4 text-xs text-ink-extra-muted">Guest & Pro</p>
+ <h2
+ tabindex="-1"
+ class="mb-7 text-2xl font-medium leading-8 tracking-tight text-ink outline-none sm:text-[28px] sm:leading-9"
+ >
+ Choose what works for you.
+ </h2>
+ <p>
+ Join your workspace as a Guest for free, with no credit card needed.
+ Connect up to two email accounts, use Haiku, and keep up to 5 GB of
+ files. Emails you send include a “Sent with Macro” footer.
+ </p>
+ <p class="mt-5">
+ Pro removes the email watermark and account limit, unlocks every AI
+ model, and gives you more storage and team features.
+ </p>
+
+ <div class="mt-10">
+ <table class="w-full table-fixed border-collapse text-left text-xs leading-5 sm:text-sm sm:leading-6">
+ <caption class="sr-only">
+ Compare Guest access and Pro features
+ </caption>
+ <thead>
+ <tr class="border-b border-edge">
+ <th
+ scope="col"
+ class="w-[38%] pb-5 pr-3 align-top font-medium text-ink sm:pr-6"
+ >
+ What’s included
+ </th>
+ <th
+ scope="col"
+ class="w-[31%] pb-5 pr-3 align-top font-medium text-ink sm:pr-6"
+ >
+ Guest
+ <span class="mt-1.5 block text-xs font-normal leading-5 text-ink-muted">
+ Free
+ </span>
+ </th>
+ <th
+ scope="col"
+ class="w-[31%] pb-5 align-top font-medium text-ink"
+ >
+ Pro
+ <span class="mt-1.5 block text-xs font-normal leading-5 text-ink-muted [overflow-wrap:anywhere]">
+ 30 days free, then $40/user/month
+ </span>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <For each={PLAN_COMPARISON}>
+ {(row) => (
+ <tr class="border-b border-edge-muted last:border-b-0">
+ <th
+ scope="row"
+ class="py-4 pr-3 align-top font-normal text-ink-muted sm:py-5 sm:pr-6"
+ >
+ {row.feature}
+ </th>
+ <td class="py-4 pr-3 align-top text-ink-muted sm:py-5 sm:pr-6">
+ {row.guest}
+ </td>
+ <td class="py-4 align-top text-ink-muted sm:py-5">
+ {row.pro}
+ </td>
+ </tr>
+ )}
+ </For>
+ </tbody>
+ <tfoot>
+ <tr>
+ <td />
+ <td class="pt-6 pr-3 align-top sm:pr-6">
+ <button
+ type="button"
+ onClick={props.onContinueGuest}
+ class="flex min-h-10 w-full max-w-40 items-center justify-center gap-2 rounded-full border border-edge px-2 py-2 text-center text-[11px] font-medium leading-4 text-ink-muted hover:border-ink-muted hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ink sm:px-3"
+ >
+ <span>Continue as Guest</span>
+ </button>
+ </td>
+ <td class="pt-6 align-top">
+ <button
+ type="button"
+ onClick={props.onBackToPro}
+ class="flex min-h-10 w-full max-w-40 items-center justify-center gap-2 rounded-full bg-ink px-2 py-2 text-center text-[11px] font-medium leading-4 text-surface hover:bg-ink/90 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ink sm:px-3"
+ >
+ <span>Continue with Pro</span>
+ </button>
+ </td>
+ </tr>
+ </tfoot>
+ </table>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/marketing/src/features/setup/components/PlanSelection.tsx b/apps/marketing/src/features/setup/components/PlanSelection.tsx
new file mode 100644
index 0000000000..2cea823174
--- /dev/null
+++ b/apps/marketing/src/features/setup/components/PlanSelection.tsx
@@ -0,0 +1,47 @@
+import type { JSX } from 'solid-js';
+import { ContinueButton } from '../flow/shared';
+
+/** Presentation only: the host supplies payment UI and handles completion. */
+export function PlanSelection(props: {
+ onContinue: () => void;
+ payment: JSX.Element;
+ disabled?: boolean;
+}) {
+ return (
+ <section class="mx-auto flex w-full max-w-lg flex-col py-2 sm:py-4">
+ <header class="text-center">
+ <h1
+ tabindex="-1"
+ class="font-[Roboto_Slab_Variable] text-[clamp(1.75rem,8vw,3rem)] font-[315] leading-[1.12] tracking-tight text-balance outline-none"
+ >
+ Free Claude &amp; GPT for 30 days.
+ </h1>
+ <p class="mx-auto mt-6 max-w-[400px] text-sm leading-6 text-ink-muted text-balance sm:text-[15px]">
+ Every feature, every AI model and 1 TB of storage. Your first 30 days
+ on us then $40/user month.
+ </p>
+ </header>
+
+ <div class="glass-input mt-9 overflow-hidden rounded-2xl bg-ink/[0.065]">
+ <div
+ role="region"
+ aria-label="Payment details"
+ tabindex="0"
+ class="max-h-[min(360px,50svh)] overflow-y-auto overscroll-contain p-5 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ink"
+ >
+ {props.payment}
+ </div>
+ </div>
+
+ <ContinueButton
+ label="Start 30 day trial"
+ disabled={props.disabled}
+ onClick={props.onContinue}
+ />
+ <p class="mx-auto mt-3 max-w-52 text-center text-xs leading-5 text-ink-extra-muted">
+ <span class="block">$40/user/month, billed monthly</span>
+ <span class="block">after the trial. Cancel anytime.</span>
+ </p>
+ </section>
+ );
+}
diff --git a/apps/marketing/src/features/setup/components/TeamSetup.tsx b/apps/marketing/src/features/setup/components/TeamSetup.tsx
index 9bed67a972..0a77485867 100644
--- a/apps/marketing/src/features/setup/components/TeamSetup.tsx
+++ b/apps/marketing/src/features/setup/components/TeamSetup.tsx
@@ -16,8 +16,8 @@ export function TeamSetup(props: { children: JSX.Element }) {
Built for teams.
</h1>
<h2 class="mt-6 max-w-[440px] text-sm font-normal leading-6 text-ink-muted text-balance sm:text-[15px]">
- Invite your team now to make the most of the free plan. Update if you
- need more AI/storage.
+ Bring your team into one workspace. Choose Guest access or upgrade for
+ more AI and storage.
</h2>
</header>
<div class="mt-9 w-full">{props.children}</div>
diff --git a/apps/marketing/src/features/setup/core/planComparison.ts b/apps/marketing/src/features/setup/core/planComparison.ts
new file mode 100644
index 0000000000..5a9ede82f0
--- /dev/null
+++ b/apps/marketing/src/features/setup/core/planComparison.ts
@@ -0,0 +1,19 @@
+/** Preview copy aligned with the app's plan definitions and paywall messages.
+ * Email limits: authentication_service/api/link/gmail.rs; branding:
+ * email-compose/core/constants.ts; other gates: PaywallState and PaywallComponent.
+ * Keep this local to the standalone website, which cannot import app modules. */
+export const PLAN_COMPARISON = [
+ { feature: 'Connected email accounts', guest: 'Up to 2', pro: 'Unlimited' },
+ {
+ feature: 'Email branding',
+ guest: '“Sent with Macro” footer',
+ pro: 'No watermark',
+ },
+ { feature: 'AI models', guest: 'Haiku', pro: 'All models' },
+ { feature: 'Storage', guest: '5 GB', pro: '1 TB' },
+ {
+ feature: 'Calls, recording & transcription',
+ guest: 'Not included',
+ pro: 'Included',
+ },
+] as const;
diff --git a/apps/marketing/src/features/setup/views/PublicOnboarding.tsx b/apps/marketing/src/features/setup/views/PublicOnboarding.tsx
index 34a57dec29..99b82baa5d 100644
--- a/apps/marketing/src/features/setup/views/PublicOnboarding.tsx
+++ b/apps/marketing/src/features/setup/views/PublicOnboarding.tsx
@@ -2,6 +2,9 @@ import { createSignal, Match, onCleanup, Show, Switch } from 'solid-js';
import { GoogleAccountsStep } from '../components/GoogleAccountsStep';
import { OnboardingShell } from '../components/OnboardingShell';
import { OnboardingTrustDetails } from '../components/OnboardingTrustDetails';
+import { PaymentPreview } from '../components/PaymentPreview';
+import { PlanComparison } from '../components/PlanComparison';
+import { PlanSelection } from '../components/PlanSelection';
import { StoryStage } from '../components/StoryStage';
import { buildGoogleWorkOnboardingUrl } from '../core/onboardingHandoff';
import type { OnboardingIntegration } from '../core/onboardingIntegrations';
@@ -25,6 +28,7 @@ export function PublicOnboarding(props: {
'personal',
'tools',
'team',
+ 'plan',
] as const;
type Step = (typeof steps)[number];
const [step, setStep] = createSignal<Step>('welcome');
@@ -76,12 +80,29 @@ export function PublicOnboarding(props: {
: undefined
}
explainer={
- ['security', 'work', 'personal'].includes(step()) ? (
+ props.preview && step() === 'plan' ? (
+ <PlanComparison
+ onContinueGuest={() => window.location.assign(props.loginUrl)}
+ onBackToPro={() => {
+ content
+ .querySelector<HTMLElement>('h1')
+ ?.focus({ preventScroll: true });
+ content.closest('[data-onboarding-scroll]')?.scrollTo({
+ top: 0,
+ behavior: window.matchMedia('(prefers-reduced-motion: reduce)')
+ .matches
+ ? 'instant'
+ : 'smooth',
+ });
+ }}
+ />
+ ) : ['security', 'work', 'personal'].includes(step()) ? (
<OnboardingTrustDetails
topic={step() === 'security' ? 'security' : 'google'}
/>
) : undefined
}
+ explainerLabel={step() === 'plan' ? 'Continue as Guest' : undefined}
>
<div ref={content} class="flex flex-col gap-8">
<Switch>
@@ -139,7 +160,11 @@ export function PublicOnboarding(props: {
</StoryStage>
</Match>
<Match when={props.preview && step() === 'team'}>
- <PublicTeamStep
+ <PublicTeamStep onContinue={() => goTo('plan')} />
+ </Match>
+ <Match when={props.preview && step() === 'plan'}>
+ <PlanSelection
+ payment={<PaymentPreview />}
onContinue={() => window.location.assign(props.loginUrl)}
/>
</Match>
diff --git a/apps/marketing/src/features/setup/views/PublicTeamStep.tsx b/apps/marketing/src/features/setup/views/PublicTeamStep.tsx
index 6a6556470f..ec750eeca0 100644
--- a/apps/marketing/src/features/setup/views/PublicTeamStep.tsx
+++ b/apps/marketing/src/features/setup/views/PublicTeamStep.tsx
@@ -85,7 +85,7 @@ export function PublicTeamStep(props: { onContinue: () => void }) {
</Show>
</TeamSetupFields>
<ContinueButton
- label="Finish preview"
+ label="Continue"
disabled={!name().trim() || invalid() || tooManyInvites()}
onClick={props.onContinue}
/>
diff --git a/apps/marketing/src/routes/posts/entries/macro-vs-clickup/index.tsx b/apps/marketing/src/routes/posts/entries/macro-vs-clickup/index.tsx
index 256298aa44..4b902e7ae4 100644
--- a/apps/marketing/src/routes/posts/entries/macro-vs-clickup/index.tsx
+++ b/apps/marketing/src/routes/posts/entries/macro-vs-clickup/index.tsx
@@ -35,8 +35,8 @@ const comparisonRows: ComparisonRow[] = [
them: '$10–$19 per seat, plus AI at $14–$33',
},
{
- feature: 'Free plan',
- macro: 'Full workspace for personal use, with storage and AI limits',
+ feature: 'No-cost access',
+ macro: 'Free Guest access to a workspace, with storage and AI limits',
them: 'Free with storage capped at 60MB and limited AI',
},
{
@@ -499,10 +499,9 @@ export default function MacroVsClickUpPost() {
item, no module matrix.
</p>
<p>
- We also offer a free plan that covers all you need for personal use
- with some limits on storage and the AI models you can access. Finally,
- enterprises can get a custom deployment that adds SSO, compliance and
- self-hosting.
+ You can also join a workspace as a Guest for free, with limits on
+ storage and the AI models you can access. Finally, enterprises can get
+ a custom deployment that adds SSO, compliance and self-hosting.
</p>
<p>
ClickUp's seat price starts lower — $10 to $19 before AI — but the
@@ -601,13 +600,12 @@ export default function MacroVsClickUpPost() {
</p>
</PostFaqItem>
- <PostFaqItem question="How do ClickUp and Macro's free plans compare?">
+ <PostFaqItem question="How does Macro Guest access compare with ClickUp's free plan?">
<p>
ClickUp's free plan is built for testing the product. You get
unlimited tasks and members, but storage is capped at 60MB, and
- you get limited access to AI tools. Our free plan gives you full
- workspace access with a "Sent with Macro" signature and limits on
- storage and AI.
+ you get limited access to AI tools. Guest access in Macro is free,
+ with a "Sent with Macro" signature and limits on storage and AI.
</p>
</PostFaqItem>
diff --git a/apps/marketing/src/routes/posts/entries/macro-vs-superhuman/index.tsx b/apps/marketing/src/routes/posts/entries/macro-vs-superhuman/index.tsx
index d9c242b9cb..6038d28257 100644
--- a/apps/marketing/src/routes/posts/entries/macro-vs-superhuman/index.tsx
+++ b/apps/marketing/src/routes/posts/entries/macro-vs-superhuman/index.tsx
@@ -43,9 +43,9 @@ const comparisonRows: ComparisonRow[] = [
them: '$40 per seat per month (as part of the new Superhuman Suite)',
},
{
- feature: 'Free plan',
+ feature: 'No-cost access',
macro:
- 'Full workspace access for personal use, with limits on storage and AI',
+ 'Free Guest access to a workspace, with limits on storage and AI',
them: "Covers Grammarly, Docs, and Go — Mail isn't included until Business",
},
{
@@ -234,8 +234,8 @@ export default function MacroVsSuperhumanPost() {
Macro has a <strong>unified inbox</strong> so you can triage all your
accounts at once using familiar <code>j</code>, <code>k</code> and{' '}
<code>e</code> shortcuts. You can also view accounts individually if
- you want. Connect 2 emails under Macro's free plan or unlimited emails
- with a paid plan.
+ you want. Connect 2 emails as a Guest or unlimited emails with a paid
+ plan.
</p>
<PostScreenshot
src={accountsSidebar}
@@ -482,12 +482,12 @@ export default function MacroVsSuperhumanPost() {
<p>
Macro is one flat $40 per seat, and that includes every module: email,
chat, docs, tasks, CRM, calls, all of it, with all AI features
- included. We also have a free plan that covers everything for personal
- use with some limits on storage and AI. Superhuman is also $40 a month
- which includes Superhuman and Grammarly. Some people might use both of
- those products but the kinds of users that need Superhuman —
- salespeople, founders, execs — and Grammarly (more junior or foreign
- language people) might have limited overlap.
+ included. You can also join a workspace as a Guest for free, with
+ limits on storage and AI. Superhuman is also $40 a month which
+ includes Superhuman and Grammarly. Some people might use both of those
+ products but the kinds of users that need Superhuman — salespeople,
+ founders, execs — and Grammarly (more junior or foreign language
+ people) might have limited overlap.
</p>
<h2>When to choose Macro</h2>
diff --git a/apps/web/justfile b/apps/web/justfile
index d0827fb17e..77b5680055 100644
--- a/apps/web/justfile
+++ b/apps/web/justfile
@@ -171,6 +171,15 @@ bundle-smoke-server *ARGS:
test-watch:
bunx --bun vitest
+# Sign-in, sign-up, and onboarding in Chromium against fake backends (no network).
+# Flags pass through to Playwright: `--ui` to watch and step through, `--headed`
+# to see the browser. With --ui, closing the onboarding window opens auth's.
+# The Linux dev shell points LD_LIBRARY_PATH at Nix libraries, which Playwright's
+# system-glibc Chromium can't load; Nix binaries find theirs through RPATH.
+test-signup-browser *ARGS:
+ env -u LD_LIBRARY_PATH bunx playwright test --config src/features/onboarding/browser-test/playwright.config.ts {{ARGS}}
+ env -u LD_LIBRARY_PATH bunx playwright test --config src/features/auth/browser-test/playwright.config.ts {{ARGS}}
+
test-email-rendering:
bun run --cwd ../../packages/email-renderer test
bun run --cwd ../../packages/email-renderer test:browser
diff --git a/apps/web/knip.ts b/apps/web/knip.ts
index 47a5d72ad0..74880e5eb8 100644
--- a/apps/web/knip.ts
+++ b/apps/web/knip.ts
@@ -9,6 +9,8 @@ const config: KnipConfig = {
// block reachable without hiding dead block-local files from Knip.
'src/features/block-*/definition.ts',
'src/lib/workers/**/*.{js,ts,tsx}',
+ // Feature browser harnesses load from their own HTML and Playwright specs.
+ 'src/features/*/browser-test/*.{ts,tsx}',
],
project: ['src/**/*.{js,ts,tsx}'],
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index bb2401207c..cffcc3ec33 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -29,7 +29,6 @@ import { PropertyEditorModal } from '@app/features/property/editor/PropertyEdito
import { ReminderComposerModal } from '@app/features/reminders/ReminderComposerModal';
import { MobileSettingsProvider } from '@app/features/settings/context/mobile-settings';
import { MobileSettings } from '@app/features/settings/MobileSettings';
-import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';
import { NativeShareSheet } from '@app/features/sharing/native-share-sheet/NativeShareSheet';
import { ShowFeatureFlag } from '@app/lib/analytics/posthog';
import { mountGlobalFocusListener } from '@app/signal/focus';
@@ -141,19 +140,15 @@ function NewOnboardingRedirect() {
const userInfoQuery = useUserInfoQuery();
const navigate = useNavigate();
const location = useLocation();
- const onboardingV4 = useOnboardingV4Flag();
-
createEffect(() => {
- if (!onboardingV4().enabled || isMobile() || isNativeMobilePlatform()) {
- return;
- }
+ if (isMobile() || isNativeMobilePlatform()) return;
const data = userInfoQuery.data;
if (data?.authenticated !== true || data.tutorialComplete !== false) {
return;
}
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
+ // onboarding carries it as ?next and its finish() returns there instead of
// the post-setup landing. Base-relative so navigate() can resolve it
// against the router.
const target =
diff --git a/apps/web/src/features/auth/EmailAuth.test.tsx b/apps/web/src/features/auth/EmailAuth.test.tsx
index c5531e0909..1d28e412bf 100644
--- a/apps/web/src/features/auth/EmailAuth.test.tsx
+++ b/apps/web/src/features/auth/EmailAuth.test.tsx
@@ -51,9 +51,6 @@ vi.mock('@queries/auth/user-info', () => ({
invalidateAllAfterLogin: vi.fn(),
useUserInfoQuery: () => ({ data: { tutorialComplete: true } }),
}));
-vi.mock('@app/features/setup/flow/useOnboardingV4Flag', () => ({
- useOnboardingV4Flag: () => () => ({ enabled: false }),
-}));
vi.mock('@ui', () => ({
Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (
<button {...props} />
diff --git a/apps/web/src/features/auth/EmailAuth.tsx b/apps/web/src/features/auth/EmailAuth.tsx
index 54ce341dc5..98bd4fef9a 100644
--- a/apps/web/src/features/auth/EmailAuth.tsx
+++ b/apps/web/src/features/auth/EmailAuth.tsx
@@ -1,6 +1,5 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
import { ShareInboxConflictDialog } from '@app/features/inbox/ShareInboxConflictDialog';
-import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { updateUserAuth } from '@core/auth';
import { redirectToEmailAuth } from '@core/auth/email';
@@ -138,7 +137,6 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
};
const userInfoQuery = useUserInfoQuery();
- const onboardingV4 = useOnboardingV4Flag();
// Return to the layout the flow left from, if this callback belongs to a
// flow that stashed one. Consent replaced the page, so nothing in memory
@@ -161,7 +159,6 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
// return straight to it. Landing in mail settings would mount the app
// shell mid-onboarding just for NewOnboardingRedirect to bounce back.
if (
- onboardingV4().enabled &&
!isMobile() &&
!isNativeMobilePlatform() &&
userInfoQuery.data?.tutorialComplete === false
diff --git a/apps/web/src/features/auth/EmailForm.tsx b/apps/web/src/features/auth/EmailForm.tsx
deleted file mode 100644
index d3ee11cdb3..0000000000
--- a/apps/web/src/features/auth/EmailForm.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import { SERVER_HOSTS } from '@core/constant/servers';
-import { platformFetch } from '@core/util/platformFetch';
-import { authServiceClient } from '@service-auth/client';
-import { action, useSubmission } from '@solidjs/router';
-import { Stage } from './Shared';
-
-// Construct the redirect uri to use for passwordless login.
-// This will send us back to the application after clicking the magic link.
-const REDIRECT_URI = `${window.location.origin}/app`;
-
-async function isPasswordLogin(email?: string | null) {
- if (!email) return false;
-
- const encodedEmail = new TextEncoder().encode(email.toLowerCase());
- const hashedBuffer = await crypto.subtle.digest('SHA-256', encodedEmail);
- const hashedEmail = Array.from(new Uint8Array(hashedBuffer))
- .map((b) => b.toString(16).padStart(2, '0'))
- .join('');
- return (
- hashedEmail ===
- '0d10222b5594dbb0eb5d2bccbc9b5d8e9ff83e99421b573fb32c8a7b74491c81'
- );
-}
-
-// Initiates the passwordless login flow.
-// Redirecting to the requested identity provider endpoint.
-export const sendEmailCode = action(async (formData: FormData) => {
- const email = formData.get('email');
- if (!email || typeof email !== 'string') throw new Error('Invalid email');
-
- if (typeof email === 'string' && (await isPasswordLogin(email))) {
- const password = formData.get('password');
- if (!password || typeof password !== 'string') return 'isPasswordLogin';
-
- const maybeTokens = await authServiceClient.passwordLogin({
- password,
- email,
- });
- if (maybeTokens.isErr())
- throw new Error(
- 'Failed to login. Check your email and password then try again.'
- );
-
- return 'LoggedIn';
- }
-
- const url = new URL(window.location.href);
- const referral_code = url.searchParams.get('referral_code');
-
- const response = await platformFetch(
- `${SERVER_HOSTS['auth-service']}/login/passwordless`,
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- redirect_uri: REDIRECT_URI,
- email,
- ...(referral_code && { referral_code }),
- }),
- }
- );
-
- if (!response.ok) throw new Error(await response.text());
-
- // If the passwordless call returns 202,
- // the email needs to login through a dedicated identity provider.
- if (response.status === 202) {
- const body: unknown = await response.json().catch(() => undefined);
- if (
- !body ||
- typeof body !== 'object' ||
- !('idp_id' in body) ||
- typeof body.idp_id !== 'string' ||
- !body.idp_id
- ) {
- throw new Error('Unable to start SSO login for this email.');
- }
- const ssoUrl = new URL(`${SERVER_HOSTS['auth-service']}/login/sso`);
- ssoUrl.searchParams.set('idp_id', body.idp_id);
- ssoUrl.searchParams.set('login_hint', email);
- if (referral_code) ssoUrl.searchParams.set('referral_code', referral_code);
- window.location.href = ssoUrl.toString();
- return false; // passwordless login flow is not reached
- }
-
- // Local backends return the one-time code so dev tooling (seeded persona
- // tabs) can finish the login without the email round-trip.
- if (import.meta.env.DEV) {
- const body = (await response.json().catch(() => undefined)) as
- | { code?: string }
- | undefined;
- if (body?.code) return { autoCode: body.code };
- }
-
- return true;
-}, 'passwordless-login');
-
-/// True when the email step succeeded and the verify step should show.
-export function sentEmailCode(
- result: Awaited<ReturnType<typeof sendEmailCode>> | undefined
-): boolean {
- return result === true || (typeof result === 'object' && !!result);
-}
-
-/// The local-backend auto-login code, when the email step returned one.
-export function autoLoginCode(
- result: Awaited<ReturnType<typeof sendEmailCode>> | undefined
-): string | undefined {
- if (typeof result === 'object' && result && 'autoCode' in result) {
- return result.autoCode;
- }
-}
-
-export function useResetEmailCode(setStage: (next: Stage) => void) {
- const submission = useSubmission(sendEmailCode);
- return () => {
- submission.clear();
- setStage(Stage.Email);
- };
-}
diff --git a/apps/web/src/features/auth/Login.tsx b/apps/web/src/features/auth/Login.tsx
deleted file mode 100644
index d20a2a1422..0000000000
--- a/apps/web/src/features/auth/Login.tsx
+++ /dev/null
@@ -1,680 +0,0 @@
-import { OnboardingFlow } from '@app/features/setup/flow/OnboardingFlow';
-import { NoiseBackground } from '@app/features/setup/flow/shared';
-import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { GOOGLE_GMAIL_IDP } from '@core/auth/email';
-import { LoadingBlock } from '@core/component/LoadingBlock';
-import { toast } from '@core/component/Toast/Toast';
-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';
-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 ArrowLeft from '@phosphor/arrow-left.svg';
-import ArrowRight from '@phosphor/arrow-right.svg';
-import { useUserInfo } from '@queries/auth';
-import {
- invalidateAllAfterLogin,
- useUserInfoQuery,
-} from '@queries/auth/user-info';
-import { authServiceClient } from '@service-auth/client';
-import {
- action,
- useAction,
- useNavigate,
- useSearchParams,
- useSubmission,
-} from '@solidjs/router';
-import { Button } from '@ui';
-import { Stepper } from '@ui/components/Stepper';
-import { detect } from 'detect-browser';
-import {
- createEffect,
- createMemo,
- createSignal,
- on,
- onCleanup,
- onMount,
- Show,
- Suspense,
- untrack,
-} from 'solid-js';
-import { match } from 'ts-pattern';
-import {
- autoLoginCode,
- sendEmailCode,
- sentEmailCode,
- useResetEmailCode,
-} from './EmailForm';
-import { OtpInput } from './OtpInput';
-import { Stage } from './Shared';
-import { useSsoLogin } from './useSsoLogin';
-
-function PostLoginRedirect() {
- const navigate = useNavigate();
-
- // Login init is owned by the per-method handlers (the session-token effect and
- // onComplete); this redirect only navigates, so login doesn't fire init twice.
- onMount(() => {
- navigate('/', { replace: true });
- });
-
- 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 onboardingV4 = useOnboardingV4Flag();
-
- const isFirstTimeDesktopUser = () =>
- !isMobile() &&
- !isNativeMobilePlatform() &&
- userInfoQuery.data?.authenticated === true &&
- userInfoQuery.data.tutorialComplete === false;
-
- const needsOnboarding = () =>
- onboardingV4().enabled && isFirstTimeDesktopUser();
-
- // Don't redirect into the app while the gate is still unknown: a first-time
- // user would land on home for a beat and then get yanked to /onboarding.
- const waitingOnFlag = () =>
- onboardingV4().loading && isFirstTimeDesktopUser();
-
- return (
- <Suspense fallback={<LoadingBlock />}>
- <Show when={userInfoQuery.data} fallback={<LoadingBlock />}>
- <Show when={!waitingOnFlag()} fallback={<LoadingBlock />}>
- <Show when={needsOnboarding()} fallback={<PostLoginRedirect />}>
- <OnboardingFlow />
- </Show>
- </Show>
- </Show>
- </Suspense>
- );
-}
-
-function LoginPicker(props: {
- setStage: (next: Stage) => void;
- signupMode?: boolean;
-}) {
- const analytics = useAnalytics();
- const startSsoLogin = useSsoLogin({ signupMode: props.signupMode });
- // Apple sign-in is iOS-only: it's required there for App Store review,
- // and intentionally absent on desktop.
- const showApple = getNativeMobilePlatform() === 'ios';
-
- const continueWithEmail = () => {
- if (props.signupMode) {
- analytics.track('sign_up_click', { method: 'email' });
- }
- props.setStage(Stage.Email);
- };
-
- return (
- <div class="flex flex-col gap-3">
- <Button
- variant="cta"
- size="xl"
- autofocus
- onClick={() => startSsoLogin(GOOGLE_GMAIL_IDP)}
- >
- <IconGoogle class="size-fit" />
- Continue with Google
- </Button>
-
- <Show when={showApple}>
- <Button
- variant="outline"
- size="xl"
- class="bg-surface"
- onClick={() => startSsoLogin('Apple')}
- >
- <IconApple class="size-fit" />
- Continue with Apple
- </Button>
- </Show>
-
- <Button
- variant="outline"
- size="xl"
- class="bg-surface"
- onClick={continueWithEmail}
- >
- Continue with email
- </Button>
- </div>
- );
-}
-
-function FormInput(props: {
- id: string;
- type?: string;
- placeholder?: string;
- required?: boolean;
- value?: string;
- autoFocus?: boolean;
-}) {
- let inputEl: HTMLInputElement | undefined;
- onMount(() => {
- if (props.autoFocus === false) return;
- let cancelled = false;
- onCleanup(() => {
- cancelled = true;
- });
- // The Stepper's outin Transition resolves this step's JSX (firing onMount)
- // before attaching it to the document, so the input is still detached
- // here. Poll until it's connected, then focus.
- 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 ?? ''}
- required={props.required ?? true}
- autocomplete={props.id}
- class="ln-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 user-invalid:border-failure"
- />
- );
-}
-
-function FormError(props: { msg?: string }) {
- return (
- <Show when={props.msg}>
- <p role="alert" class="text-xs text-failure leading-snug">
- {props.msg}
- </p>
- </Show>
- );
-}
-
-function EmailFormNew(props: {
- setStage: (next: Stage) => void;
- onBack: () => void;
-}) {
- const [isPasswordLogin, setIsPasswordLogin] = createSignal(false);
- const submission = useSubmission(sendEmailCode);
- const send = useAction(sendEmailCode);
- const [searchParams] = useSearchParams();
- const searchParamsEmail = untrack(() => {
- const email = searchParams.email;
- if (typeof email === 'string') return email;
- });
-
- // Dev builds auto-start the flow for `?email=` links (the seeder prints
- // them per persona); combined with the local backend returning the code,
- // opening the link logs straight in.
- createEffect(() => {
- if (
- import.meta.env.DEV &&
- searchParamsEmail &&
- !submission.pending &&
- !submission.result &&
- !submission.error
- ) {
- const formData = new FormData();
- formData.append('email', searchParamsEmail);
- send(formData);
- }
- });
-
- createEffect(() => {
- if (sentEmailCode(submission.result)) {
- props.setStage(Stage.Verify);
- } else if (submission.result === 'isPasswordLogin') {
- setIsPasswordLogin(true);
- } else if (submission.result === 'LoggedIn') {
- props.setStage(Stage.Done);
- }
- });
-
- return (
- <form
- action={sendEmailCode}
- method="post"
- noValidate={false}
- class="flex flex-col gap-3"
- >
- <p class="text-xs text-ink-muted leading-snug">
- We’ll send a one-time code to verify.
- </p>
- <FormInput
- id="email"
- type="email"
- placeholder="[email protected]"
- value={searchParamsEmail}
- />
- <Show when={isPasswordLogin()}>
- <FormInput
- id="password"
- type="password"
- placeholder="Password"
- required={isPasswordLogin()}
- />
- </Show>
- <FormError msg={submission.error?.message} />
- <Button
- variant="cta"
- size="xl"
- type="submit"
- disabled={submission.pending}
- >
- Continue
- <ArrowRight class="size-5" />
- </Button>
- <Button
- variant="outline"
- size="xl"
- class="bg-surface"
- onClick={props.onBack}
- >
- <ArrowLeft class="size-5" />
- Back to sign in
- </Button>
- </form>
- );
-}
-
-const verifyCode = action(async (formData: FormData) => {
- const code = formData.get('one-time-code');
- if (typeof code !== 'string') throw new Error('Invalid code');
- const email = formData.get('email');
- if (typeof email !== 'string') throw new Error('Invalid email');
-
- const result = await authServiceClient.passwordlessCallback({ code, email });
- if (result.isErr()) {
- if (result.error.some((err) => err.code === 'UNAUTHORIZED')) {
- throw new Error('Invalid code.');
- }
- throw new Error('Unable to perform verification.');
- }
-
- return true;
-}, 'verify-code-login-new');
-
-const RESEND_TIMER = 45;
-
-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);
- const submission = useSubmission(verifyCode);
- const emailSubmission = useSubmission(sendEmailCode);
- const resend = useAction(sendEmailCode);
- const submit = useAction(verifyCode);
-
- const email = () => {
- const value = emailSubmission.input?.[0].get('email');
- return typeof value === 'string' ? value : undefined;
- };
-
- // Local backends return the code with the email step; submit it
- // automatically so seeded persona logins are one click.
- createEffect(() => {
- const code = autoLoginCode(emailSubmission.result);
- const submittedEmail = email();
- if (
- code &&
- submittedEmail &&
- !submission.pending &&
- !submission.result &&
- !submission.error
- ) {
- const formData = new FormData();
- formData.append('email', submittedEmail);
- formData.append('one-time-code', code);
- submit(formData);
- }
- });
-
- createEffect(() => {
- if (!showResendCode()) {
- const timer = setTimeout(() => {
- setResendTimer(0);
- setShowResendCode(true);
- }, RESEND_TIMER * 1000);
- const pTimer = setInterval(
- () => setResendTimer((t) => (t > 0 ? t - 1 : 0)),
- 1000
- );
- onCleanup(() => {
- clearTimeout(timer);
- clearInterval(pTimer);
- });
- }
- });
-
- const handleResendCode = async () => {
- const submittedEmail = email();
- if (!submittedEmail) {
- setResendError('Email address is unavailable. Go back and try again.');
- return;
- }
- submission.clear();
- setResendError();
- setResendTimer(RESEND_TIMER);
- setShowResendCode(false);
- const formData = new FormData();
- formData.append('email', submittedEmail);
- try {
- await resend(formData);
- } catch (e) {
- console.error(e);
- setResendTimer(0);
- setShowResendCode(true);
- setResendError(
- e instanceof Error
- ? e.message
- : 'Failed to resend code. Please try again.'
- );
- }
- };
-
- createEffect(() => {
- if (submission.result) {
- props.setStage(Stage.Done);
- const url = new URL(window.location.href);
- const sp = new URLSearchParams(url.search);
- const referral = sp.get('referral');
- if (referral) window.location.href = `/app?referral=${referral}`;
- }
- });
-
- let formEl: HTMLFormElement | undefined;
-
- return (
- <form
- ref={formEl}
- action={verifyCode}
- method="post"
- 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>
- <OtpInput
- value={code()}
- disabled={submission.pending}
- onInput={setCode}
- onComplete={(value) => {
- const submittedEmail = email();
- if (!submittedEmail) return;
- const formData = new FormData(formEl);
- formData.set('email', submittedEmail);
- 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?{' '}
- <button
- type="button"
- onClick={handleResendCode}
- disabled={
- emailSubmission.pending ||
- submission.pending ||
- !showResendCode() ||
- !email()
- }
- class="font-medium text-ink transition-colors hover:text-ink-muted disabled:text-ink-extra-muted"
- >
- <Show when={resendTimer() > 0} fallback="Resend">
- Resend ({resendTimer()})
- </Show>
- </button>
- </p>
- <FormError msg={submission.error?.message ?? resendError()} />
- {/* 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"
- size="xl"
- type="submit"
- disabled={submission.pending || code().length !== 6 || !email()}
- >
- Verify
- <ArrowRight class="size-5" />
- </Button>
- <Button
- variant="outline"
- size="xl"
- class="bg-surface"
- onClick={props.onBack}
- >
- <ArrowLeft class="size-5" />
- Change email
- </Button>
- </form>
- );
-}
-
-export function Login(props: { signupMode?: boolean }) {
- const [searchParams] = useSearchParams();
- const [stage, setStage] = createSignal(
- searchParams.email ? Stage.Email : Stage.None
- );
- const userInfo = useUserInfo();
- const analytics = useAnalytics();
- const authenticatedUserId = createMemo(() => {
- const user = userInfo();
- return user?.authenticated ? user.id : undefined;
- });
-
- onMount(() => {
- analytics.pageView(props.signupMode ? 'signup' : 'login');
- });
-
- const identifyUser = () => {
- const user = userInfo();
-
- if (!user || !user.authenticated) return;
-
- const platform = detect(navigator.userAgent);
- analytics.identify(user.id, {
- email: user.email,
- os: platform?.os?.replaceAll(' ', ''),
- });
- };
-
- createEffect(
- on(authenticatedUserId, (userId) => {
- if (userId) identifyUser();
- })
- );
-
- createEffect(() => {
- // token may be an array if the redirect URL contained duplicate token params;
- // take the last one as it is the most recently appended by the auth service
- const rawToken = searchParams.token;
- const session_code = Array.isArray(rawToken)
- ? rawToken[rawToken.length - 1]
- : rawToken;
- if (session_code && typeof session_code === 'string') {
- authServiceClient.sessionLogin({ session_code }).then(async (res) => {
- if (res.isOk()) {
- // Reset token state only after the session cookies have actually
- // changed — resetting before sessionLogin opens a window where a
- // visibility-triggered refresh re-latches under the new generation.
- unsetTokenPromise();
- await invalidateAllAfterLogin();
- await initEmailLink().match(
- () => {},
- (err) => {
- if (err.tag !== 'AlreadyInitialized') {
- console.error('Failed to init email link on login', err);
- }
- }
- );
- } else {
- console.error('Failed to redeem session code', res.error);
- toast.failure('Sign-in failed. Please try again.');
- }
- });
- }
- });
-
- const { initEmailLink } = useEmailLinks();
-
- const onComplete = async () => {
- unsetTokenPromise();
- await invalidateAllAfterLogin();
- await initEmailLink().match(
- () => {},
- (err) => {
- if (err.tag !== 'AlreadyInitialized') {
- console.error('Failed to init email link on login', err);
- }
- }
- );
- const user = userInfo();
-
- if (!user || !user.authenticated) return;
-
- analytics.track('login', {
- method: 'email',
- });
- identifyUser();
- };
-
- onCleanup(() => {
- setStage(Stage.Email);
- });
-
- const onStageChange = (next: Stage) => {
- if (next === Stage.Done) {
- onComplete();
- }
- setStage(next);
- };
-
- const stepIndex = () =>
- match(stage())
- .with(Stage.None, () => 0)
- .with(Stage.Email, () => 1)
- .with(Stage.Verify, () => 2)
- .with(Stage.Done, () => 2)
- .exhaustive();
-
- const emailSubmission = useSubmission(sendEmailCode);
- const verifySubmission = useSubmission(verifyCode);
- const resetEmailCode = useResetEmailCode(setStage);
-
- const onBack = () => {
- if (stage() === Stage.Verify) {
- verifySubmission.clear();
- resetEmailCode();
- } else if (stage() === Stage.Email) {
- emailSubmission.clear();
- setStage(Stage.None);
- }
- };
-
- return (
- <Show when={!userInfo()?.authenticated} fallback={<PostAuthGate />}>
- <div class="flex items-center justify-center size-full overflow-hidden relative">
- <style>{
- /*css*/ `
- @keyframes ln-card-in {
- from { opacity: 0; transform: translateY(14px) scale(0.985); }
- to { opacity: 1; transform: translateY(0) scale(1); }
- }
- .ln-card { animation: ln-card-in 520ms cubic-bezier(0.22, 1, 0.36, 1) both; }
-
- /* Override browser autofill yellow with our surface/ink palette */
- .ln-input:-webkit-autofill,
- .ln-input:-webkit-autofill:hover,
- .ln-input:-webkit-autofill:focus,
- .ln-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 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 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>
-
- <Stepper
- step={stepIndex()}
- transition={Stepper.transitions.scale}
- >
- <Stepper.Step>
- <LoginPicker
- setStage={onStageChange}
- signupMode={props.signupMode}
- />
- </Stepper.Step>
- <Stepper.Step>
- <EmailFormNew setStage={onStageChange} onBack={onBack} />
- </Stepper.Step>
- <Stepper.Step>
- <VerifyFormNew setStage={onStageChange} onBack={onBack} />
- </Stepper.Step>
- </Stepper>
- </div>
-
- <div class="text-center text-xs text-ink/50 wrap-break-word">
- By continuing, you agree to our{' '}
- <a
- class="text-link hover:text-link-hover visited:text-link-visited underline underline-offset-2 focus-visible:text-link-hover"
- href="/terms"
- >
- terms
- </a>{' '}
- and{' '}
- <a
- class="text-link hover:text-link-hover visited:text-link-visited underline underline-offset-2 focus-visible:text-link-hover"
- href="/privacy"
- >
- privacy policy
- </a>
- .
- </div>
- </div>
- </div>
- </div>
- </Show>
- );
-}
diff --git a/apps/web/src/features/auth/Shared.tsx b/apps/web/src/features/auth/Shared.tsx
deleted file mode 100644
index 30d9040624..0000000000
--- a/apps/web/src/features/auth/Shared.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-export function setCookie(name: string, value: string, days: number) {
- const expires = days
- ? `; expires=${new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString()}`
- : '';
- document.cookie = `${name}=${encodeURIComponent(value)}${expires}; path=/`;
-}
-
-export enum Stage {
- Verify = 'verify',
- Email = 'email',
- Done = 'done',
- None = 'none',
-}
diff --git a/apps/web/src/features/auth/auth.tsx b/apps/web/src/features/auth/auth.tsx
new file mode 100644
index 0000000000..755dd0b367
--- /dev/null
+++ b/apps/web/src/features/auth/auth.tsx
@@ -0,0 +1,89 @@
+import {
+ clearSignupDraft,
+ Onboarding,
+ OnboardingSignup,
+} from '@app/features/onboarding/onboarding';
+import { LoadingBlock } from '@core/component/LoadingBlock';
+import { isMobile } from '@core/mobile/isMobile';
+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
+import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
+import { getNativeMobilePlatform } from '@core/util/platform';
+import { getWebOrigin } from '@core/util/webOrigin';
+import { useNavigate, useSearchParams } from '@solidjs/router';
+import { onMount, Show } from 'solid-js';
+import { AuthProvider, type AuthUser } from './context/auth-context';
+import { sessionTokenParam } from './core/email-code';
+import { createAppAuthContext } from './create-app-auth-context';
+import { AuthView } from './views/auth-view';
+import { MobileWebSignupView } from './views/mobile-web-signup-view';
+
+/**
+ * /login and /signup. Once authenticated, first-time desktop users continue
+ * into onboarding in place; everyone else proceeds into the app.
+ */
+export function Login(props: { signupMode?: boolean }) {
+ const [params] = useSearchParams();
+ const email = typeof params.email === 'string' ? params.email : undefined;
+ const desktopSignup = () =>
+ props.signupMode === true && !isMobile() && !isNativeMobilePlatform();
+ return (
+ <AuthProvider value={createAppAuthContext()}>
+ <AuthView
+ intent={props.signupMode ? 'signup' : 'login'}
+ showApple={getNativeMobilePlatform() === 'ios'}
+ compact={virtualKeyboardVisible()}
+ initialEmail={email}
+ // Dev persona links (`?email=`) sign straight in against a local backend.
+ autoStart={import.meta.env.DEV && email !== undefined}
+ token={sessionTokenParam(params.token)}
+ onVerified={() => {
+ const referral = new URLSearchParams(window.location.search).get(
+ 'referral'
+ );
+ if (referral) window.location.href = `/app?referral=${referral}`;
+ }}
+ signupJourney={
+ desktopSignup()
+ ? (slots) => <OnboardingSignup {...slots} />
+ : undefined
+ }
+ signedIn={(user) => <PostAuthGate user={user} />}
+ />
+ </AuthProvider>
+ );
+}
+
+function PostAuthGate(props: { user: AuthUser }) {
+ const needsOnboarding = () =>
+ !isMobile() && !isNativeMobilePlatform() && !props.user.tutorialComplete;
+ return (
+ <Show when={needsOnboarding()} fallback={<PostLoginRedirect />}>
+ <Onboarding />
+ </Show>
+ );
+}
+
+/** Login init runs in the per-method handlers; this only navigates. */
+function PostLoginRedirect() {
+ const navigate = useNavigate();
+ onMount(() => {
+ clearSignupDraft();
+ navigate('/', { replace: true });
+ });
+ return <LoadingBlock />;
+}
+
+/** Mobile-web visitors get a desktop link instead of signing up on a phone. */
+export function MobileWebSignup() {
+ const navigate = useNavigate();
+ return (
+ <AuthProvider value={createAppAuthContext()}>
+ <MobileWebSignupView
+ onLogin={() => navigate('/login')}
+ onBackHome={() => {
+ window.location.href = getWebOrigin();
+ }}
+ />
+ </AuthProvider>
+ );
+}
diff --git a/apps/web/src/features/auth/browser-test/.gitignore b/apps/web/src/features/auth/browser-test/.gitignore
new file mode 100644
index 0000000000..6419da1a8e
--- /dev/null
+++ b/apps/web/src/features/auth/browser-test/.gitignore
@@ -0,0 +1,3 @@
+.vite/
+.dist/
+test-results/
diff --git a/apps/web/src/features/auth/browser-test/README.md b/apps/web/src/features/auth/browser-test/README.md
new file mode 100644
index 0000000000..442caa04b9
--- /dev/null
+++ b/apps/web/src/features/auth/browser-test/README.md
@@ -0,0 +1,27 @@
+# Sign-in and sign-up browser tests
+
+The fixture mounts the real `AuthView` and `MobileWebSignupView` under
+`AuthProvider` with the fake backend from `tests/fake-auth-context.ts`. New users
+continue into the real onboarding views over onboarding's own fake. No module is
+aliased or mocked, and nothing touches the network.
+
+SSO is a real round trip. Google and Apple reload the page with the `?token=` the
+auth service would append, and the view redeems it. Both fake backends persist in
+sessionStorage across these reloads. When a signed-in user would enter the app,
+the fixture renders a `landed` marker instead.
+
+Run the suite from `apps/web` (the config starts or reuses the fixture server).
+Add `--ui` to watch and step through each test, or `--headed` to see the browser:
+
+```sh
+bunx playwright test --config src/features/auth/browser-test/playwright.config.ts
+```
+
+To click through by hand, run
+`bunx vite --config src/features/auth/browser-test/vite.config.ts` and open
+`http://127.0.0.1:3022/`:
+
+- `/?page=login` is sign-in. Use `[email protected]` with code `424242`; any
+ other address signs up as a first-time user.
+- `/?page=signup` is the desktop sign-up through onboarding's opening slides.
+- `/?page=mobile-signup` is the mobile-web email capture.
diff --git a/apps/web/src/features/auth/browser-test/auth.browser.e2e.ts b/apps/web/src/features/auth/browser-test/auth.browser.e2e.ts
new file mode 100644
index 0000000000..fbc6d38b5e
--- /dev/null
+++ b/apps/web/src/features/auth/browser-test/auth.browser.e2e.ts
@@ -0,0 +1,119 @@
+import { expect, test } from '@playwright/test';
+import {
+ expectLanded,
+ fakeAuth,
+ fakeCalls,
+ openFixture,
+ signInWithCode,
+} from './fixture-page';
+
+test('a returning user signs in with an emailed code', async ({ page }) => {
+ await openFixture(page, '/?page=login');
+ await page.getByRole('button', { name: 'Continue with email' }).click();
+ await signInWithCode(page, '[email protected]', '424242');
+ await expectLanded(page, '/');
+});
+
+test('a wrong code can be corrected without starting over', async ({
+ page,
+}) => {
+ await openFixture(page, '/?page=login');
+ await page.getByRole('button', { name: 'Continue with email' }).click();
+ await signInWithCode(page, '[email protected]', '111111');
+ await expect(page.getByRole('alert')).toHaveText('Invalid code.');
+ await page.getByLabel('One-time code').fill('424242');
+ await expectLanded(page, '/');
+});
+
+test('Google sign-in comes back with a session code the page redeems', async ({
+ page,
+}) => {
+ await openFixture(page, '/?page=login', { ssoEmail: '[email protected]' });
+ await page.getByRole('button', { name: 'Continue with Google' }).click();
+ await expectLanded(page, '/');
+ const world = await fakeAuth(page);
+ expect(Object.keys(world.sessionTokens)).toEqual([
+ expect.stringMatching(/^google-/),
+ ]);
+ expect(world.user?.email).toBe('[email protected]');
+});
+
+test('an expired session code leaves the visitor on sign-in', async ({
+ page,
+}) => {
+ await openFixture(page, '/?page=login&token=expired');
+ await expect(page.getByRole('status', { name: 'Notifications' })).toHaveText(
+ 'Sign-in failed. Please try again.'
+ );
+ await expect(
+ page.getByRole('button', { name: 'Continue with Google' })
+ ).toBeVisible();
+});
+
+test('a password account signs in with its password', async ({ page }) => {
+ await openFixture(page, '/?page=login', {
+ passwordAccounts: { '[email protected]': 'hunter2' },
+ accounts: { '[email protected]': { tutorialComplete: true } },
+ });
+ await page.getByRole('button', { name: 'Continue with email' }).click();
+ await page.getByPlaceholder('[email protected]').fill('[email protected]');
+ await page.getByRole('button', { name: 'Continue', exact: true }).click();
+ await page.getByPlaceholder('Password').fill('hunter2');
+ await page.getByRole('button', { name: 'Continue', exact: true }).click();
+ await expectLanded(page, '/');
+});
+
+test('a new user who signs in by email continues into onboarding', async ({
+ page,
+}) => {
+ await openFixture(page, '/?page=login');
+ await page.getByRole('button', { name: 'Continue with email' }).click();
+ await signInWithCode(page, '[email protected]', '424242');
+ await expect(
+ page.getByRole('heading', { level: 1, name: 'Create your workspace' })
+ ).toBeVisible();
+});
+
+test('desktop sign-up: slides, Google, then onboarding resumes at the work inbox', async ({
+ page,
+}) => {
+ await openFixture(page, '/?page=signup', { ssoEmail: '[email protected]' });
+ await page
+ .locator('label')
+ .filter({ has: page.getByRole('radio', { name: 'Lilac' }) })
+ .click();
+ await page.getByRole('button', { name: 'Get started' }).click();
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await page.getByRole('button', { name: 'Connect work email' }).click();
+
+ // Back from Google: signed in, onboarding picks up where sign-up left off.
+ await expect(
+ page.getByRole('heading', { level: 1, name: /Connect your work/ })
+ ).toBeVisible();
+ await page.getByRole('button', { name: 'Connect work email' }).click();
+ await expect(page.getByText('[email protected]')).toBeVisible();
+ expect((await fakeAuth(page)).user).toMatchObject({
+ email: '[email protected]',
+ tutorialComplete: false,
+ });
+ expect(
+ await page.evaluate(
+ () =>
+ JSON.parse(sessionStorage.getItem('auth-fixture:onboarding') ?? '{}')
+ .accent
+ )
+ ).toBe('#b8a1ed');
+});
+
+test('a mobile-web visitor gets a desktop link instead of signing up', async ({
+ page,
+}) => {
+ await openFixture(page, '/?page=mobile-signup');
+ await page.getByLabel('Email address').fill('[email protected]');
+ await page.getByRole('button', { name: 'Sign Up' }).click();
+ await expect(
+ page.getByRole('heading', { name: 'Macro is better on desktop.' })
+ ).toBeVisible();
+ expect(await fakeCalls(page)).toContain('lead:[email protected]');
+});
diff --git a/apps/web/src/features/auth/browser-test/fixture-keys.ts b/apps/web/src/features/auth/browser-test/fixture-keys.ts
new file mode 100644
index 0000000000..0dd17f18f2
--- /dev/null
+++ b/apps/web/src/features/auth/browser-test/fixture-keys.ts
@@ -0,0 +1,11 @@
+/** sessionStorage keys shared by the fixture page and its Playwright tests. */
+export const FIXTURE_KEYS = {
+ /** Partial auth world merged over the defaults on the first load. */
+ seed: 'auth-fixture:seed',
+ auth: 'auth-fixture:auth',
+ /** The onboarding backend a new user continues into. */
+ onboarding: 'auth-fixture:onboarding',
+ /** Who Google/Apple sign in as. */
+ ssoEmail: 'auth-fixture:sso-email',
+ landed: 'auth-fixture:landed',
+} as const;
diff --git a/apps/web/src/features/auth/browser-test/fixture-page.ts b/apps/web/src/features/auth/browser-test/fixture-page.ts
new file mode 100644
index 0000000000..d1e124913b
--- /dev/null
+++ b/apps/web/src/features/auth/browser-test/fixture-page.ts
@@ -0,0 +1,45 @@
+import { expect, type Page } from '@playwright/test';
+import type { FakeAuthWorld } from '../tests/fake-auth-context';
+import { FIXTURE_KEYS } from './fixture-keys';
+
+/** Open the fixture with `seed` merged over the default fake auth world. */
+export async function openFixture(
+ page: Page,
+ path: string,
+ seed: Partial<FakeAuthWorld> & { ssoEmail?: string } = {}
+) {
+ page.on('pageerror', (error) => {
+ throw error;
+ });
+ const { ssoEmail, ...world } = seed;
+ // Init scripts rerun on every load; only the first may seed, or the SSO
+ // round-trip would reset the fake backend.
+ await page.addInitScript(
+ ([keys, world, ssoEmail]) => {
+ if (sessionStorage.getItem(keys.seed) !== null) return;
+ sessionStorage.setItem(keys.seed, JSON.stringify(world));
+ if (ssoEmail) sessionStorage.setItem(keys.ssoEmail, ssoEmail);
+ },
+ [FIXTURE_KEYS, world, ssoEmail] as const
+ );
+ await page.goto(path);
+}
+
+export const fakeAuth = (page: Page) =>
+ page.evaluate(() => window.authFixture.auth());
+
+export const fakeCalls = (page: Page) =>
+ page.evaluate(() => window.authFixture.calls());
+
+export async function expectLanded(page: Page, target: string) {
+ await expect(page.getByTestId('landed')).toHaveText(
+ `Entered Macro at ${target}`
+ );
+}
+
+export async function signInWithCode(page: Page, email: string, code: string) {
+ await page.getByPlaceholder('[email protected]').fill(email);
+ await page.getByRole('button', { name: 'Continue', exact: true }).click();
+ await expect(page.getByText(email)).toBeVisible();
+ await page.getByLabel('One-time code').fill(code);
+}
diff --git a/apps/web/src/features/auth/browser-test/fixture.tsx b/apps/web/src/features/auth/browser-test/fixture.tsx
new file mode 100644
index 0000000000..fb346226b7
--- /dev/null
+++ b/apps/web/src/features/auth/browser-test/fixture.tsx
@@ -0,0 +1,178 @@
+import '@fontsource-variable/inter';
+import '../../../index.css';
+import { For, Match, onMount, Show, Switch } from 'solid-js';
+import { unwrap } from 'solid-js/store';
+import { render } from 'solid-js/web';
+import { OnboardingProvider } from '../../onboarding/context/onboarding-context';
+import { createFakeOnboarding } from '../../onboarding/tests/fake-onboarding-context';
+import { renderInviteOfferStub } from '../../onboarding/tests/invite-offer-stub';
+import { OnboardingFlowView } from '../../onboarding/views/onboarding-flow-view';
+import { SignupJourneyView } from '../../onboarding/views/signup-journey-view';
+import { AuthProvider, type AuthUser } from '../context/auth-context';
+import { sessionTokenParam } from '../core/email-code';
+import {
+ createFakeAuth,
+ defaultFakeAuthWorld,
+ type FakeAuthWorld,
+} from '../tests/fake-auth-context';
+import { AuthView } from '../views/auth-view';
+import { MobileWebSignupView } from '../views/mobile-web-signup-view';
+import { FIXTURE_KEYS } from './fixture-keys';
+
+/**
+ * The real sign-in, sign-up, and onboarding views over fake backends persisted
+ * in sessionStorage. SSO is a real round-trip: the page reloads with the
+ * `?token=` the auth service would append, and the view redeems it.
+ */
+const params = Object.fromEntries(new URLSearchParams(location.search));
+const page = params.page ?? 'login';
+const read = <T,>(key: string): T | undefined => {
+ const raw = sessionStorage.getItem(key);
+ return raw ? (JSON.parse(raw) as T) : undefined;
+};
+const write = (key: string, value: unknown) =>
+ sessionStorage.setItem(key, JSON.stringify(value));
+const land = (target: string) => {
+ write(FIXTURE_KEYS.landed, target);
+ location.assign(`${location.pathname}?page=landed`);
+};
+
+const auth = createFakeAuth(
+ read<FakeAuthWorld>(FIXTURE_KEYS.auth) ?? {
+ ...defaultFakeAuthWorld(),
+ ...read<Partial<FakeAuthWorld>>(FIXTURE_KEYS.seed),
+ },
+ {
+ onChange: (world) => write(FIXTURE_KEYS.auth, world),
+ ssoEmail: sessionStorage.getItem(FIXTURE_KEYS.ssoEmail) ?? undefined,
+ // The identity provider returns to the same page with a session code.
+ ssoRedirect: async (provider, _intent, email) => {
+ const token = `${provider}-${Date.now()}`;
+ auth.update((draft) => {
+ draft.sessionTokens[token] = email;
+ });
+ location.assign(`${location.pathname}?page=${page}&token=${token}`);
+ await new Promise(() => {});
+ },
+ }
+);
+write(FIXTURE_KEYS.auth, structuredClone(unwrap(auth.world)));
+
+/** The onboarding backend, which sees the account auth just signed in. */
+function createOnboardingFor(user: AuthUser) {
+ const fake = createFakeOnboarding(
+ read<Parameters<typeof createFakeOnboarding>[0]>(
+ FIXTURE_KEYS.onboarding
+ ) ?? {
+ viewer: {
+ id: user.id,
+ email: user.email ?? '',
+ tutorialComplete: user.tutorialComplete,
+ licensed: false,
+ },
+ inboxesToConnect: user.email ? [user.email] : [],
+ },
+ {
+ onChange: (world) => write(FIXTURE_KEYS.onboarding, world),
+ roundTrip: async (apply) => {
+ apply();
+ location.reload();
+ await new Promise(() => {});
+ },
+ }
+ );
+ write(FIXTURE_KEYS.onboarding, structuredClone(unwrap(fake.world)));
+ return fake;
+}
+
+declare global {
+ interface Window {
+ authFixture: {
+ auth: () => FakeAuthWorld;
+ calls: () => string[];
+ };
+ }
+}
+window.authFixture = {
+ auth: () => structuredClone(unwrap(auth.world)),
+ calls: auth.calls,
+};
+
+/** Desktop first-run users continue into onboarding; everyone else enters the app. */
+function SignedIn(props: { user: AuthUser }) {
+ const onboarding = createOnboardingFor(props.user);
+ return (
+ <Show when={!props.user.tutorialComplete} fallback={<EnterApp />}>
+ <OnboardingProvider value={onboarding.context}>
+ <OnboardingFlowView
+ next={undefined}
+ checkoutReturn={undefined}
+ onNavigate={land}
+ onRedirect={(url) => location.assign(url)}
+ onSignedOut={() => land('/login')}
+ renderInviteOffer={renderInviteOfferStub}
+ />
+ </OnboardingProvider>
+ </Show>
+ );
+}
+
+function EnterApp() {
+ onMount(() => land('/'));
+ return null;
+}
+
+/** The signed-out slides only read presentation state; nothing to persist. */
+function SignupJourney(props: Parameters<typeof SignupJourneyView>[0]) {
+ return (
+ <OnboardingProvider value={createFakeOnboarding({ viewer: null }).context}>
+ <SignupJourneyView {...props} />
+ </OnboardingProvider>
+ );
+}
+
+function Fixture() {
+ return (
+ <AuthProvider value={auth.context}>
+ <Switch>
+ <Match when={page === 'landed'}>
+ <main data-testid="landed" class="p-8 text-ink">
+ Entered Macro at {read<string>(FIXTURE_KEYS.landed)}
+ </main>
+ </Match>
+ <Match when={page === 'mobile-signup'}>
+ <MobileWebSignupView
+ onLogin={() => location.assign(`${location.pathname}?page=login`)}
+ onBackHome={() => land('/home-page')}
+ />
+ </Match>
+ <Match when={true}>
+ <AuthView
+ intent={page === 'signup' ? 'signup' : 'login'}
+ showApple={params.apple !== undefined}
+ compact={false}
+ initialEmail={params.email}
+ token={sessionTokenParam(params.token)}
+ signupJourney={
+ page === 'signup'
+ ? (slots) => <SignupJourney {...slots} />
+ : undefined
+ }
+ signedIn={(user) => <SignedIn user={user} />}
+ />
+ </Match>
+ </Switch>
+ <div
+ role="status"
+ aria-label="Notifications"
+ class="fixed top-4 left-1/2 z-[2000] -translate-x-1/2 text-sm text-ink"
+ >
+ <For each={auth.notifications()}>
+ {(message) => <p class="rounded bg-input px-3 py-2">{message}</p>}
+ </For>
+ </div>
+ </AuthProvider>
+ );
+}
+
+render(() => <Fixture />, document.getElementById('root')!);
diff --git a/apps/web/src/features/auth/browser-test/index.html b/apps/web/src/features/auth/browser-test/index.html
new file mode 100644
index 0000000000..d52fe4e4bc
--- /dev/null
+++ b/apps/web/src/features/auth/browser-test/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en" data-modality="keyboard">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Auth fixture</title>
+ </head>
+ <body>
+ <div id="root" style="height: 100svh"></div>
+ <script type="module" src="/fixture.tsx"></script>
+ </body>
+</html>
diff --git a/apps/web/src/features/auth/browser-test/playwright.config.ts b/apps/web/src/features/auth/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..814e0799c3
--- /dev/null
+++ b/apps/web/src/features/auth/browser-test/playwright.config.ts
@@ -0,0 +1,41 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const port = Number(process.env.AUTH_BROWSER_PORT ?? 3022);
+
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: `${directory}/test-results`,
+ timeout: 60_000,
+ fullyParallel: true,
+ forbidOnly: !!process.env.CI,
+ reporter: process.env.CI ? [['list'], ['github']] : 'line',
+ use: {
+ baseURL: `http://127.0.0.1:${port}`,
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ contextOptions: { reducedMotion: 'reduce' },
+ },
+ webServer: {
+ command: `bunx vite --config src/features/auth/browser-test/vite.config.ts --port ${port}`,
+ cwd: webDirectory,
+ url: `http://127.0.0.1:${port}`,
+ reuseExistingServer: !process.env.CI,
+ timeout: 120_000,
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: {
+ ...devices['Desktop Chrome'],
+ viewport: { width: 1280, height: 900 },
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ },
+ ],
+});
diff --git a/apps/web/src/features/auth/browser-test/vite.config.ts b/apps/web/src/features/auth/browser-test/vite.config.ts
new file mode 100644
index 0000000000..2f5f5695c7
--- /dev/null
+++ b/apps/web/src/features/auth/browser-test/vite.config.ts
@@ -0,0 +1,31 @@
+import { fileURLToPath } from 'node:url';
+import tailwind from '@tailwindcss/vite';
+import { defineConfig } from 'vite';
+import solidPlugin from 'vite-plugin-solid';
+import solidSvg from 'vite-plugin-solid-svg';
+import tsconfigPaths from 'vite-tsconfig-paths';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const workspaceDirectory = fileURLToPath(
+ new URL('../../../../../../', import.meta.url)
+);
+
+/** The real auth (and onboarding) views over fake backends; no module is replaced. */
+export default defineConfig({
+ root: directory,
+ cacheDir: `${directory}/.vite`,
+ plugins: [
+ solidPlugin(),
+ solidSvg({ defaultAsComponent: true }),
+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),
+ tailwind(),
+ ],
+ resolve: { dedupe: ['solid-js'] },
+ server: {
+ host: '127.0.0.1',
+ port: 3022,
+ strictPort: true,
+ fs: { allow: [workspaceDirectory] },
+ },
+});
diff --git a/apps/web/src/features/auth/components/email-form.tsx b/apps/web/src/features/auth/components/email-form.tsx
new file mode 100644
index 0000000000..4c5100d60d
--- /dev/null
+++ b/apps/web/src/features/auth/components/email-form.tsx
@@ -0,0 +1,61 @@
+import ArrowLeft from '@phosphor/arrow-left.svg';
+import ArrowRight from '@phosphor/arrow-right.svg';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+import { FormError, FormInput } from './form-fields';
+
+export function EmailForm(props: {
+ email: string;
+ password: string;
+ passwordRequired: boolean;
+ sending: boolean;
+ error?: string;
+ onEmailInput: (value: string) => void;
+ onPasswordInput: (value: string) => void;
+ onSubmit: () => void;
+ onBack: () => void;
+}) {
+ return (
+ <form
+ class="flex flex-col gap-3"
+ onSubmit={(event) => {
+ event.preventDefault();
+ props.onSubmit();
+ }}
+ >
+ <p class="text-xs text-ink-muted leading-snug">
+ We’ll send a one-time code to verify.
+ </p>
+ <FormInput
+ id="email"
+ type="email"
+ placeholder="[email protected]"
+ value={props.email}
+ onInput={props.onEmailInput}
+ />
+ <Show when={props.passwordRequired}>
+ <FormInput
+ id="password"
+ type="password"
+ placeholder="Password"
+ value={props.password}
+ onInput={props.onPasswordInput}
+ />
+ </Show>
+ <FormError message={props.error} />
+ <Button variant="cta" size="xl" type="submit" disabled={props.sending}>
+ Continue
+ <ArrowRight class="size-5" />
+ </Button>
+ <Button
+ variant="outline"
+ size="xl"
+ class="bg-surface"
+ onClick={props.onBack}
+ >
+ <ArrowLeft class="size-5" />
+ Back to sign in
+ </Button>
+ </form>
+ );
+}
diff --git a/apps/web/src/features/auth/components/form-fields.tsx b/apps/web/src/features/auth/components/form-fields.tsx
new file mode 100644
index 0000000000..2e7a817184
--- /dev/null
+++ b/apps/web/src/features/auth/components/form-fields.tsx
@@ -0,0 +1,53 @@
+import { onCleanup, onMount, Show } from 'solid-js';
+
+export function FormInput(props: {
+ id: string;
+ type?: string;
+ placeholder?: string;
+ required?: boolean;
+ value: string;
+ autoFocus?: boolean;
+ onInput: (value: string) => void;
+}) {
+ let inputEl: HTMLInputElement | undefined;
+ onMount(() => {
+ if (props.autoFocus === false) return;
+ let cancelled = false;
+ onCleanup(() => {
+ cancelled = true;
+ });
+ // The Stepper's outin Transition resolves this step's JSX (firing onMount)
+ // before attaching it to the document, so the input is still detached
+ // here. Poll until it's connected, then focus.
+ 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}
+ required={props.required ?? true}
+ autocomplete={props.id}
+ onInput={(event) => props.onInput(event.currentTarget.value)}
+ class="ln-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 user-invalid:border-failure"
+ />
+ );
+}
+
+export function FormError(props: { message?: string }) {
+ return (
+ <Show when={props.message}>
+ <p role="alert" class="text-xs text-failure leading-snug">
+ {props.message}
+ </p>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/auth/components/login-card.tsx b/apps/web/src/features/auth/components/login-card.tsx
new file mode 100644
index 0000000000..e04a6f9059
--- /dev/null
+++ b/apps/web/src/features/auth/components/login-card.tsx
@@ -0,0 +1,72 @@
+import { NoiseBackground } from '@core/component/NoiseBackground';
+import LogoIcon from '@icon/macro-logo.svg';
+import { type JSX, Show } from 'solid-js';
+
+/** The centered sign-in card: brand header, the active step, legal footer. */
+export function LoginCard(props: {
+ /** The header yields to the on-screen keyboard on phones. */
+ compact: boolean;
+ children: JSX.Element;
+}) {
+ return (
+ <div class="flex items-center justify-center size-full overflow-hidden relative">
+ <style>{
+ /*css*/ `
+ @keyframes ln-card-in {
+ from { opacity: 0; transform: translateY(14px) scale(0.985); }
+ to { opacity: 1; transform: translateY(0) scale(1); }
+ }
+ .ln-card { animation: ln-card-in 520ms cubic-bezier(0.22, 1, 0.36, 1) both; }
+
+ /* Override browser autofill yellow with our surface/ink palette */
+ .ln-input:-webkit-autofill,
+ .ln-input:-webkit-autofill:hover,
+ .ln-input:-webkit-autofill:focus,
+ .ln-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 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={!props.compact}>
+ <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>
+ {props.children}
+ </div>
+
+ <div class="text-center text-xs text-ink/50 wrap-break-word">
+ By continuing, you agree to our{' '}
+ <a
+ class="text-link hover:text-link-hover visited:text-link-visited underline underline-offset-2 focus-visible:text-link-hover"
+ href="/terms"
+ >
+ terms
+ </a>{' '}
+ and{' '}
+ <a
+ class="text-link hover:text-link-hover visited:text-link-visited underline underline-offset-2 focus-visible:text-link-hover"
+ href="/privacy"
+ >
+ privacy policy
+ </a>
+ .
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/auth/components/login-picker.tsx b/apps/web/src/features/auth/components/login-picker.tsx
new file mode 100644
index 0000000000..bfca54de41
--- /dev/null
+++ b/apps/web/src/features/auth/components/login-picker.tsx
@@ -0,0 +1,40 @@
+import IconApple from '@icon/macro-apple.svg';
+import IconGoogle from '@icon/macro-google.svg';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+
+export function LoginPicker(props: {
+ /** Sign in with Apple is required for App Store review and iOS-only. */
+ showApple: boolean;
+ onGoogle: () => void;
+ onApple: () => void;
+ onEmail: () => void;
+}) {
+ return (
+ <div class="flex flex-col gap-3">
+ <Button variant="cta" size="xl" autofocus onClick={props.onGoogle}>
+ <IconGoogle class="size-fit" />
+ Continue with Google
+ </Button>
+ <Show when={props.showApple}>
+ <Button
+ variant="outline"
+ size="xl"
+ class="bg-surface"
+ onClick={props.onApple}
+ >
+ <IconApple class="size-fit" />
+ Continue with Apple
+ </Button>
+ </Show>
+ <Button
+ variant="outline"
+ size="xl"
+ class="bg-surface"
+ onClick={props.onEmail}
+ >
+ Continue with email
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/auth/components/mobile-web-signup-sent.tsx b/apps/web/src/features/auth/components/mobile-web-signup-sent.tsx
new file mode 100644
index 0000000000..2def12e563
--- /dev/null
+++ b/apps/web/src/features/auth/components/mobile-web-signup-sent.tsx
@@ -0,0 +1,26 @@
+import LogoIcon from '@icon/macro-logo.svg';
+
+export function MobileWebSignupSent(props: { onBackHome: () => void }) {
+ return (
+ <div class="flex flex-col size-full p-6 overflow-hidden relative">
+ <div class="flex flex-col items-start gap-4 w-full max-w-md mx-auto mt-6">
+ <LogoIcon class="size-16 text-accent self-center" />
+ <h2 class="text-3xl font-semibold text-ink mt-3">
+ Macro is better on desktop.
+ </h2>
+ <p class="text-base text-ink/60 mt-4">
+ We sent a link to your inbox - open it on your computer for the full
+ Macro experience.
+ </p>
+
+ <button
+ type="button"
+ onClick={() => props.onBackHome()}
+ class="w-full px-3 py-2.5 text-lg font-bold rounded-xs bg-accent text-surface border-none mt-16"
+ >
+ Back to Home
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/onboarding/MobileWebWelcome.tsx b/apps/web/src/features/auth/components/mobile-web-welcome.tsx
similarity index 78%
rename from apps/web/src/features/onboarding/MobileWebWelcome.tsx
rename to apps/web/src/features/auth/components/mobile-web-welcome.tsx
index 5a27a87bb7..7dbeacba11 100644
--- a/apps/web/src/features/onboarding/MobileWebWelcome.tsx
+++ b/apps/web/src/features/auth/components/mobile-web-welcome.tsx
@@ -1,20 +1,13 @@
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
import LogoIcon from '@icon/macro-logo.svg';
-import { A } from '@solidjs/router';
-import { createSignal, onMount } from 'solid-js';
+import { createSignal } from 'solid-js';
-interface MobileWebWelcomeProps {
+export function MobileWebWelcome(props: {
+ pending: boolean;
onSignUp: (email: string) => void;
-}
-
-export default function MobileWebWelcome(props: MobileWebWelcomeProps) {
- const analytics = useAnalytics();
+ onLogin: () => void;
+}) {
const [email, setEmail] = createSignal('');
- onMount(() => {
- analytics.track('mobile_web_welcome_viewed');
- });
-
const handleSignUp = () => {
props.onSignUp(email());
};
@@ -46,6 +39,7 @@ export default function MobileWebWelcome(props: MobileWebWelcomeProps) {
/>
<button
type="submit"
+ disabled={props.pending}
class="w-full px-3 py-2.5 text-lg font-bold rounded-xs bg-accent text-surface border-none"
>
Sign Up
@@ -53,13 +47,16 @@ export default function MobileWebWelcome(props: MobileWebWelcomeProps) {
</form>
<p class="text-sm text-ink/50 mt-20">Already have an account?</p>
- <A
- href="/login"
- onClick={() => analytics.track('login_from_onboarding')}
+ <a
+ href="/app/login"
+ onClick={(event) => {
+ event.preventDefault();
+ props.onLogin();
+ }}
class="w-full px-3 py-2.5 text-lg rounded-xs flex items-center justify-between gap-2 border border-edge-muted bg-transparent text-ink/50 hover:bg-hover/60"
>
Login
- </A>
+ </a>
</div>
</div>
);
diff --git a/apps/web/src/features/auth/OtpInput.tsx b/apps/web/src/features/auth/components/otp-input.tsx
similarity index 100%
rename from apps/web/src/features/auth/OtpInput.tsx
rename to apps/web/src/features/auth/components/otp-input.tsx
diff --git a/apps/web/src/features/auth/components/verify-form.tsx b/apps/web/src/features/auth/components/verify-form.tsx
new file mode 100644
index 0000000000..82c137865e
--- /dev/null
+++ b/apps/web/src/features/auth/components/verify-form.tsx
@@ -0,0 +1,68 @@
+import ArrowLeft from '@phosphor/arrow-left.svg';
+import ArrowRight from '@phosphor/arrow-right.svg';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+import { FormError } from './form-fields';
+import { OtpInput } from './otp-input';
+
+export function VerifyForm(props: {
+ email: string;
+ code: string;
+ verifying: boolean;
+ canVerify: boolean;
+ resendIn: number;
+ resending: boolean;
+ error?: string;
+ onCodeInput: (value: string) => void;
+ onVerify: (code?: string) => void;
+ onResend: () => void;
+ onBack: () => void;
+}) {
+ return (
+ <form
+ class="flex flex-col gap-3"
+ onSubmit={(event) => {
+ event.preventDefault();
+ props.onVerify();
+ }}
+ >
+ <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">{props.email}</span>.
+ </p>
+ <OtpInput
+ value={props.code}
+ disabled={props.verifying}
+ onInput={props.onCodeInput}
+ onComplete={(code) => props.onVerify(code)}
+ />
+ <p class="text-center text-xs text-ink-muted" aria-live="polite">
+ Didn't receive a code?{' '}
+ <button
+ type="button"
+ onClick={() => props.onResend()}
+ disabled={props.resending || props.verifying || props.resendIn > 0}
+ class="font-medium text-ink transition-colors hover:text-ink-muted disabled:text-ink-extra-muted"
+ >
+ <Show when={props.resendIn > 0} fallback="Resend">
+ Resend ({props.resendIn})
+ </Show>
+ </button>
+ </p>
+ <FormError message={props.error} />
+ <Button variant="cta" size="xl" type="submit" disabled={!props.canVerify}>
+ Verify
+ <ArrowRight class="size-5" />
+ </Button>
+ <Button
+ variant="outline"
+ size="xl"
+ class="bg-surface"
+ onClick={props.onBack}
+ >
+ <ArrowLeft class="size-5" />
+ Change email
+ </Button>
+ </form>
+ );
+}
diff --git a/apps/web/src/features/auth/context/auth-context.tsx b/apps/web/src/features/auth/context/auth-context.tsx
new file mode 100644
index 0000000000..b6911f088f
--- /dev/null
+++ b/apps/web/src/features/auth/context/auth-context.tsx
@@ -0,0 +1,80 @@
+import type { AppEvents } from '@app/lib/analytics/app-events';
+import { type Accessor, createContext, useContext } from 'solid-js';
+import type { MobileWelcomeResult } from '../core/mobile-welcome';
+
+export type AuthUser = {
+ id: string;
+ email: string | undefined;
+ tutorialComplete: boolean;
+};
+
+export type AuthSession =
+ | { t: 'loading' }
+ | { t: 'signed-out' }
+ | { t: 'signed-in'; user: AuthUser };
+
+export type SsoProvider = 'google' | 'apple';
+export type AuthIntent = 'login' | 'signup';
+
+export type SendCodeResult =
+ /** `autoCode`: local backends return the code so dev logins are one click. */
+ | { t: 'code-sent'; autoCode?: string }
+ /** This address signs in with a password; ask for it and send again. */
+ | { t: 'password-required' }
+ /** A password login finished without a code. */
+ | { t: 'signed-in' }
+ /** The address belongs to an SSO domain; the page is navigating there. */
+ | { t: 'redirected' }
+ | { t: 'failed'; message: string };
+
+export type VerifyCodeResult =
+ | { t: 'verified' }
+ | { t: 'invalid-code' }
+ | { t: 'failed' };
+
+type AuthEventName =
+ | 'login'
+ | 'sign_up_click'
+ | 'mobile_web_welcome_viewed'
+ | 'mobile_web_signup_sent_viewed'
+ | 'login_from_onboarding';
+type TrackAuth = <E extends AuthEventName>(
+ event: E,
+ data?: E extends keyof AppEvents ? AppEvents[E] : Record<string, unknown>
+) => void;
+
+/** Everything sign-in and sign-up need from the app. */
+export type AuthContext = {
+ session: Accessor<AuthSession>;
+ /** Leaves for the identity provider; on web the page navigates away. */
+ startSso(provider: SsoProvider, intent: AuthIntent): Promise<void>;
+ sendEmailCode(input: {
+ email: string;
+ password?: string;
+ }): Promise<SendCodeResult>;
+ verifyEmailCode(input: {
+ email: string;
+ code: string;
+ }): Promise<VerifyCodeResult>;
+ /** Exchanges the auth service's return-URL code for session cookies. */
+ redeemSessionToken(token: string): Promise<boolean>;
+ /** Refreshes everything that depends on who is signed in. */
+ completeLogin(): Promise<void>;
+ sendMobileWelcomeEmail(email: string): Promise<MobileWelcomeResult>;
+ identify(user: { id: string; email: string | undefined }): void;
+ /** Ad conversions for a mobile-web lead, deduplicated by email. */
+ trackMobileSignupLead(email: string): void;
+ pageView(name: 'login' | 'signup'): void;
+ track: TrackAuth;
+ notifyFailure(message: string): void;
+};
+
+const Context = createContext<AuthContext>();
+
+export const AuthProvider = Context.Provider;
+
+export function useAuthContext(): AuthContext {
+ const context = useContext(Context);
+ if (!context) throw new Error('AuthProvider is required');
+ return context;
+}
diff --git a/apps/web/src/features/auth/core/email-code.test.ts b/apps/web/src/features/auth/core/email-code.test.ts
new file mode 100644
index 0000000000..d83a69debb
--- /dev/null
+++ b/apps/web/src/features/auth/core/email-code.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+import { isCompleteCode, sessionTokenParam } from './email-code';
+
+describe('sessionTokenParam', () => {
+ it.each([
+ [undefined, undefined],
+ ['', undefined],
+ ['abc', 'abc'],
+ [['old', 'new'], 'new'],
+ [[], undefined],
+ ])('%o → %o', (value, expected) => {
+ expect(sessionTokenParam(value)).toBe(expected);
+ });
+});
+
+describe('isCompleteCode', () => {
+ it('accepts exactly six digits', () => {
+ expect(isCompleteCode('12345')).toBe(false);
+ expect(isCompleteCode('123456')).toBe(true);
+ });
+});
diff --git a/apps/web/src/features/auth/core/email-code.ts b/apps/web/src/features/auth/core/email-code.ts
new file mode 100644
index 0000000000..ff38ec3b00
--- /dev/null
+++ b/apps/web/src/features/auth/core/email-code.ts
@@ -0,0 +1,16 @@
+/** One-time codes are six digits. */
+const CODE_LENGTH = 6;
+
+/** Seconds before the verify step offers to resend the code. */
+export const RESEND_AFTER_SECONDS = 45;
+
+export const isCompleteCode = (code: string) => code.length === CODE_LENGTH;
+
+/**
+ * The session code the auth service appended to the return URL. A redirect
+ * URL with duplicate `token` params yields an array; the last is the newest.
+ */
+export function sessionTokenParam(value: unknown): string | undefined {
+ const token = Array.isArray(value) ? value[value.length - 1] : value;
+ return typeof token === 'string' && token.length > 0 ? token : undefined;
+}
diff --git a/apps/web/src/features/auth/core/mobile-welcome.ts b/apps/web/src/features/auth/core/mobile-welcome.ts
new file mode 100644
index 0000000000..87d8e8f08f
--- /dev/null
+++ b/apps/web/src/features/auth/core/mobile-welcome.ts
@@ -0,0 +1,22 @@
+/** What sending the desktop link to a mobile-web visitor did. */
+export type MobileWelcomeResult =
+ /** `alreadySent`: this address was emailed before; the confirmation still holds. */
+ | { t: 'sent'; alreadySent: boolean }
+ | { t: 'invalid-email' }
+ | { t: 'rate-limited' }
+ | { t: 'failed' };
+
+export function mobileWelcomeFailure(
+ result: MobileWelcomeResult
+): string | undefined {
+ switch (result.t) {
+ case 'sent':
+ return undefined;
+ case 'invalid-email':
+ return 'Invalid email address.';
+ case 'rate-limited':
+ return 'Too many attempts. Please try again later.';
+ case 'failed':
+ return 'Something went wrong. Please try again.';
+ }
+}
diff --git a/apps/web/src/features/auth/create-app-auth-context.ts b/apps/web/src/features/auth/create-app-auth-context.ts
new file mode 100644
index 0000000000..f52c44cb68
--- /dev/null
+++ b/apps/web/src/features/auth/create-app-auth-context.ts
@@ -0,0 +1,113 @@
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { MOBILE_WEB_SIGNUP_LEAD_VALUE } from '@app/lib/analytics/leadValues';
+import { GOOGLE_GMAIL_IDP } from '@core/auth/email';
+import { toast } from '@core/component/Toast/Toast';
+import { deriveIsAuthenticated } from '@core/context/user';
+import { useEmailLinks } from '@core/email-link';
+import { unsetTokenPromise } from '@core/util/fetchWithToken';
+import { useSendMobileWelcomeEmail } from '@queries/auth';
+import {
+ invalidateAllAfterLogin,
+ useUserInfoQuery,
+} from '@queries/auth/user-info';
+import { detect } from 'detect-browser';
+import type { AuthContext, AuthSession } from './context/auth-context';
+import {
+ exchangeSessionCode,
+ sendEmailCode,
+ verifyEmailCode,
+} from './queries/auth-requests';
+import { useSsoLogin } from './useSsoLogin';
+
+/** Real auth service, analytics, and session refresh behind the auth contract. */
+export function createAppAuthContext(): AuthContext {
+ const analytics = useAnalytics();
+ const userInfo = useUserInfoQuery();
+ const { initEmailLink } = useEmailLinks();
+ const loginSso = useSsoLogin();
+ const signupSso = useSsoLogin({ signupMode: true });
+ const sendWelcomeEmail = useSendMobileWelcomeEmail();
+
+ const session = (): AuthSession => {
+ const data = userInfo.isSuccess ? userInfo.data : undefined;
+ // A signed-out visitor's request 401s rather than answering unauthenticated.
+ const authenticated = deriveIsAuthenticated({
+ isLoading: userInfo.isLoading,
+ isError: userInfo.isError,
+ error: userInfo.error,
+ data,
+ });
+ if (authenticated === false) return { t: 'signed-out' };
+ if (!data?.userId) return { t: 'loading' };
+ return {
+ t: 'signed-in',
+ user: {
+ id: data.userId,
+ email: data.email ?? undefined,
+ tutorialComplete: data.tutorialComplete === true,
+ },
+ };
+ };
+
+ const completeLogin = async () => {
+ // Reset token state only after the session cookies have changed; resetting
+ // earlier lets a visibility-triggered refresh re-latch the old generation.
+ unsetTokenPromise();
+ await invalidateAllAfterLogin();
+ await initEmailLink().match(
+ () => {},
+ (error) => {
+ if (error.tag !== 'AlreadyInitialized')
+ console.error('Failed to init email link on login', error);
+ }
+ );
+ };
+
+ return {
+ session,
+ startSso: (provider, intent) =>
+ (intent === 'signup' ? signupSso : loginSso)(
+ provider === 'google' ? GOOGLE_GMAIL_IDP : 'Apple'
+ ),
+ sendEmailCode,
+ verifyEmailCode,
+ redeemSessionToken: async (token) => {
+ if (!(await exchangeSessionCode(token))) return false;
+ await completeLogin();
+ return true;
+ },
+ completeLogin,
+ sendMobileWelcomeEmail: async (email) => {
+ const result = await sendWelcomeEmail.mutateAsync(email);
+ if (result.isOk()) return { t: 'sent', alreadySent: !result.value.sent };
+ const code = result.error[0]?.code;
+ if (code === 'INVALID_EMAIL') return { t: 'invalid-email' };
+ if (code === 'RATE_LIMITED') return { t: 'rate-limited' };
+ return { t: 'failed' };
+ },
+ identify: (user) =>
+ analytics.identify(user.id, {
+ email: user.email,
+ os: detect(navigator.userAgent)?.os?.replaceAll(' ', ''),
+ }),
+ trackMobileSignupLead: (email) => {
+ // Lead feeds an existing custom conversion; Meta's Maximize Value
+ // campaigns need CompleteRegistration, so both fire.
+ const lead = {
+ content_name: 'mobile_web_signup',
+ value: MOBILE_WEB_SIGNUP_LEAD_VALUE,
+ currency: 'USD',
+ };
+ analytics.trackMeta('Lead', lead);
+ analytics.trackMeta('CompleteRegistration', lead);
+ analytics.trackGoogleConversion('mobile_web_lead', {
+ value: MOBILE_WEB_SIGNUP_LEAD_VALUE,
+ currency: 'USD',
+ transaction_id: email,
+ });
+ },
+ pageView: (name) => analytics.pageView(name),
+ track: (event, data) => analytics.track(event, data),
+ notifyFailure: (message) => toast.failure(message),
+ };
+}
diff --git a/apps/web/src/features/auth/primitives/email-login.ts b/apps/web/src/features/auth/primitives/email-login.ts
new file mode 100644
index 0000000000..c4ad4d6f01
--- /dev/null
+++ b/apps/web/src/features/auth/primitives/email-login.ts
@@ -0,0 +1,168 @@
+import { createSignal, onCleanup } from 'solid-js';
+import type { AuthContext, AuthIntent } from '../context/auth-context';
+import { isCompleteCode, RESEND_AFTER_SECONDS } from '../core/email-code';
+
+export type LoginStep = 'choose' | 'email' | 'verify';
+
+type EmailLoginCapabilities = Pick<
+ AuthContext,
+ | 'session'
+ | 'sendEmailCode'
+ | 'verifyEmailCode'
+ | 'completeLogin'
+ | 'identify'
+ | 'track'
+>;
+
+/**
+ * Sign-in by emailed one-time code (or, for a few accounts, a password):
+ * choose a method, send the code, verify it, then refresh the session.
+ */
+export function createEmailLogin(
+ context: EmailLoginCapabilities,
+ options: {
+ intent: AuthIntent;
+ initialEmail?: string;
+ /** Send the code for `initialEmail` right away (dev persona links). */
+ autoStart?: boolean;
+ /** After a verified sign-in, before the session swaps the page. */
+ onVerified?: () => void;
+ }
+) {
+ const [step, setStep] = createSignal<LoginStep>(
+ options.initialEmail ? 'email' : 'choose'
+ );
+ const [email, setEmail] = createSignal(options.initialEmail ?? '');
+ const [password, setPassword] = createSignal('');
+ const [passwordRequired, setPasswordRequired] = createSignal(false);
+ const [sending, setSending] = createSignal(false);
+ const [sendError, setSendError] = createSignal<string>();
+ const [code, setCode] = createSignal('');
+ const [verifying, setVerifying] = createSignal(false);
+ const [verifyError, setVerifyError] = createSignal<string>();
+ const [resendIn, setResendIn] = createSignal(0);
+
+ let countdown: ReturnType<typeof setInterval> | undefined;
+ const startResendCountdown = () => {
+ clearInterval(countdown);
+ setResendIn(RESEND_AFTER_SECONDS);
+ countdown = setInterval(() => {
+ setResendIn((seconds) => Math.max(0, seconds - 1));
+ if (resendIn() === 0) clearInterval(countdown);
+ }, 1000);
+ };
+ onCleanup(() => clearInterval(countdown));
+
+ const finish = async () => {
+ await context.completeLogin();
+ const session = context.session();
+ if (session.t === 'signed-in') {
+ context.track('login', { method: 'email' });
+ context.identify(session.user);
+ }
+ options.onVerified?.();
+ };
+
+ const verify = async (value = code()) => {
+ const address = email();
+ if (verifying() || !isCompleteCode(value) || !address) return;
+ setVerifying(true);
+ setVerifyError();
+ const result = await context.verifyEmailCode({
+ email: address,
+ code: value,
+ });
+ if (result.t === 'verified') {
+ await finish();
+ return;
+ }
+ setVerifying(false);
+ setVerifyError(
+ result.t === 'invalid-code'
+ ? 'Invalid code.'
+ : 'Unable to perform verification.'
+ );
+ };
+
+ /** Send (or resend) the code; reports whether a code went out. */
+ const send = async (): Promise<boolean> => {
+ const address = email().trim();
+ if (sending() || !address) return false;
+ setSending(true);
+ setSendError();
+ try {
+ const result = await context.sendEmailCode({
+ email: address,
+ password: passwordRequired() ? password() : undefined,
+ });
+ switch (result.t) {
+ case 'code-sent':
+ setEmail(address);
+ setCode('');
+ setStep('verify');
+ startResendCountdown();
+ if (result.autoCode) {
+ setCode(result.autoCode);
+ void verify(result.autoCode);
+ }
+ return true;
+ case 'password-required':
+ setPasswordRequired(true);
+ return false;
+ case 'signed-in':
+ await finish();
+ return false;
+ case 'redirected':
+ return false;
+ case 'failed':
+ setSendError(result.message);
+ return false;
+ }
+ } finally {
+ setSending(false);
+ }
+ };
+
+ if (options.autoStart && options.initialEmail) void send();
+
+ return {
+ step,
+ email,
+ setEmail,
+ password,
+ setPassword,
+ passwordRequired,
+ sending,
+ sendError,
+ code,
+ setCode,
+ verifying,
+ verifyError,
+ resendIn,
+ canVerify: () => isCompleteCode(code()) && !verifying(),
+ chooseEmail: () => {
+ if (options.intent === 'signup')
+ context.track('sign_up_click', { method: 'email' });
+ setStep('email');
+ },
+ submitEmail: () => void send(),
+ verify: (value?: string) => void verify(value),
+ resend: async () => {
+ setVerifyError();
+ // A failed resend may be retried at once; a sent one restarts the wait.
+ if (!(await send())) setResendIn(0);
+ },
+ back: () => {
+ if (step() === 'verify') {
+ setCode('');
+ setVerifyError();
+ setStep('email');
+ } else {
+ setSendError();
+ setStep('choose');
+ }
+ },
+ };
+}
+
+export type EmailLogin = ReturnType<typeof createEmailLogin>;
diff --git a/apps/web/src/features/auth/primitives/mobile-signup.ts b/apps/web/src/features/auth/primitives/mobile-signup.ts
new file mode 100644
index 0000000000..2b224d5b04
--- /dev/null
+++ b/apps/web/src/features/auth/primitives/mobile-signup.ts
@@ -0,0 +1,35 @@
+import { createSignal } from 'solid-js';
+import type { AuthContext } from '../context/auth-context';
+import { mobileWelcomeFailure } from '../core/mobile-welcome';
+
+/**
+ * Mobile-web visitors leave their email and get a link to open on desktop,
+ * instead of signing up on a phone.
+ */
+export function createMobileSignup(
+ context: Pick<
+ AuthContext,
+ 'sendMobileWelcomeEmail' | 'identify' | 'notifyFailure'
+ >
+) {
+ const [pending, setPending] = createSignal(false);
+ const [submitted, setSubmitted] = createSignal<string>();
+
+ const submit = async (email: string) => {
+ const address = email.trim();
+ // An empty submit keeps the visitor on the capture step.
+ if (!address || pending()) return;
+ context.identify({ id: address, email: address });
+ setPending(true);
+ try {
+ const result = await context.sendMobileWelcomeEmail(address);
+ const failure = mobileWelcomeFailure(result);
+ if (failure) context.notifyFailure(failure);
+ else setSubmitted(address);
+ } finally {
+ setPending(false);
+ }
+ };
+
+ return { pending, submitted, submit };
+}
diff --git a/apps/web/src/features/auth/primitives/session.ts b/apps/web/src/features/auth/primitives/session.ts
new file mode 100644
index 0000000000..defc95cbe1
--- /dev/null
+++ b/apps/web/src/features/auth/primitives/session.ts
@@ -0,0 +1,30 @@
+import { createEffect, on } from 'solid-js';
+import type { AuthContext } from '../context/auth-context';
+
+/** Redeem the session code an SSO return put on the URL. */
+export function redeemSessionToken(
+ context: Pick<AuthContext, 'redeemSessionToken' | 'notifyFailure'>,
+ token: string | undefined
+) {
+ if (!token) return;
+ void context.redeemSessionToken(token).then((ok) => {
+ if (!ok) context.notifyFailure('Sign-in failed. Please try again.');
+ });
+}
+
+/** Tell analytics who signed in, once per user. */
+export function createSessionIdentity(
+ context: Pick<AuthContext, 'session' | 'identify'>
+) {
+ createEffect(
+ on(
+ () => {
+ const session = context.session();
+ return session.t === 'signed-in' ? session.user : undefined;
+ },
+ (user) => {
+ if (user) context.identify(user);
+ }
+ )
+ );
+}
diff --git a/apps/web/src/features/auth/queries/auth-requests.ts b/apps/web/src/features/auth/queries/auth-requests.ts
new file mode 100644
index 0000000000..5702ee889d
--- /dev/null
+++ b/apps/web/src/features/auth/queries/auth-requests.ts
@@ -0,0 +1,110 @@
+import { SERVER_HOSTS } from '@core/constant/servers';
+import { platformFetch } from '@core/util/platformFetch';
+import { authServiceClient } from '@service-auth/client';
+import type { SendCodeResult, VerifyCodeResult } from '../context/auth-context';
+
+/** Where the passwordless magic link returns. */
+const REDIRECT_URI = `${window.location.origin}/app`;
+
+/** The one account that signs in with a password instead of a code. */
+const PASSWORD_LOGIN_EMAIL_SHA256 =
+ '0d10222b5594dbb0eb5d2bccbc9b5d8e9ff83e99421b573fb32c8a7b74491c81';
+
+async function isPasswordLogin(email: string) {
+ const digest = await crypto.subtle.digest(
+ 'SHA-256',
+ new TextEncoder().encode(email.toLowerCase())
+ );
+ const hex = Array.from(new Uint8Array(digest))
+ .map((byte) => byte.toString(16).padStart(2, '0'))
+ .join('');
+ return hex === PASSWORD_LOGIN_EMAIL_SHA256;
+}
+
+const referralCode = () =>
+ new URL(window.location.href).searchParams.get('referral_code');
+
+/** Starts passwordless sign-in, or signs in a password account directly. */
+export async function sendEmailCode(input: {
+ email: string;
+ password?: string;
+}): Promise<SendCodeResult> {
+ const { email, password } = input;
+ if (await isPasswordLogin(email)) {
+ if (!password) return { t: 'password-required' };
+ const tokens = await authServiceClient.passwordLogin({ password, email });
+ return tokens.isErr()
+ ? {
+ t: 'failed',
+ message:
+ 'Failed to login. Check your email and password then try again.',
+ }
+ : { t: 'signed-in' };
+ }
+
+ const referral_code = referralCode();
+ const response = await platformFetch(
+ `${SERVER_HOSTS['auth-service']}/login/passwordless`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ redirect_uri: REDIRECT_URI,
+ email,
+ ...(referral_code && { referral_code }),
+ }),
+ }
+ ).catch(() => undefined);
+ if (!response) return { t: 'failed', message: 'Unable to reach Macro.' };
+ if (!response.ok) return { t: 'failed', message: await response.text() };
+
+ // 202: the address must sign in through its organization's identity provider.
+ if (response.status === 202) {
+ const body: unknown = await response.json().catch(() => undefined);
+ if (
+ !body ||
+ typeof body !== 'object' ||
+ !('idp_id' in body) ||
+ typeof body.idp_id !== 'string' ||
+ !body.idp_id
+ )
+ return {
+ t: 'failed',
+ message: 'Unable to start SSO login for this email.',
+ };
+ const sso = new URL(`${SERVER_HOSTS['auth-service']}/login/sso`);
+ sso.searchParams.set('idp_id', body.idp_id);
+ sso.searchParams.set('login_hint', email);
+ if (referral_code) sso.searchParams.set('referral_code', referral_code);
+ window.location.href = sso.toString();
+ return { t: 'redirected' };
+ }
+
+ // Local backends return the code so seeded persona logins skip the inbox.
+ if (import.meta.env.DEV) {
+ const body = (await response.json().catch(() => undefined)) as
+ | { code?: string }
+ | undefined;
+ if (body?.code) return { t: 'code-sent', autoCode: body.code };
+ }
+ return { t: 'code-sent' };
+}
+
+export async function verifyEmailCode(input: {
+ email: string;
+ code: string;
+}): Promise<VerifyCodeResult> {
+ const result = await authServiceClient.passwordlessCallback(input);
+ if (result.isOk()) return { t: 'verified' };
+ return result.error.some((error) => error.code === 'UNAUTHORIZED')
+ ? { t: 'invalid-code' }
+ : { t: 'failed' };
+}
+
+/** Exchanges the session code an SSO return carries for session cookies. */
+export async function exchangeSessionCode(token: string): Promise<boolean> {
+ const result = await authServiceClient.sessionLogin({ session_code: token });
+ if (result.isErr())
+ console.error('Failed to redeem session code', result.error);
+ return result.isOk();
+}
diff --git a/apps/web/src/features/auth/tests/fake-auth-context.ts b/apps/web/src/features/auth/tests/fake-auth-context.ts
new file mode 100644
index 0000000000..b2682ef7c9
--- /dev/null
+++ b/apps/web/src/features/auth/tests/fake-auth-context.ts
@@ -0,0 +1,167 @@
+import { createSignal } from 'solid-js';
+import { createStore, produce, unwrap } from 'solid-js/store';
+import type {
+ AuthContext,
+ AuthIntent,
+ AuthSession,
+ AuthUser,
+ SsoProvider,
+} from '../context/auth-context';
+import type { MobileWelcomeResult } from '../core/mobile-welcome';
+
+/** The fake auth backend's state. Plain JSON, so a harness can persist it. */
+export type FakeAuthWorld = {
+ user: AuthUser | null;
+ /** Accounts that exist; an unknown email signs up as a first-time user. */
+ accounts: Record<string, { tutorialComplete: boolean }>;
+ /** The code the fake mailer "sends". */
+ code: string;
+ /** Addresses that sign in with a password instead of a code. */
+ passwordAccounts: Record<string, string>;
+ /** Addresses whose organization signs in through its own identity provider. */
+ ssoDomains: string[];
+ /** Return the code with the send, like a local backend. */
+ autoCode: boolean;
+ /** Session tokens the fake auth service will redeem, keyed to an email. */
+ sessionTokens: Record<string, string>;
+ /** Pending email login across a page reload. */
+ pendingEmail: string | undefined;
+ mobileWelcome: MobileWelcomeResult['t'];
+ failures: Partial<Record<'sendCode' | 'verify', string>>;
+};
+
+export type FakeAuthEvent = { event: string; data: unknown };
+
+export function defaultFakeAuthWorld(): FakeAuthWorld {
+ return {
+ user: null,
+ accounts: { '[email protected]': { tutorialComplete: true } },
+ code: '424242',
+ passwordAccounts: {},
+ ssoDomains: [],
+ autoCode: false,
+ sessionTokens: {},
+ pendingEmail: undefined,
+ mobileWelcome: 'sent',
+ failures: {},
+ };
+}
+
+const userFor = (
+ email: string,
+ account: { tutorialComplete: boolean } | undefined
+): AuthUser => ({
+ id: `macro|${email}`,
+ email,
+ tutorialComplete: account?.tutorialComplete ?? false,
+});
+
+/**
+ * An in-memory auth backend behind the real contract. `ssoRedirect` models
+ * leaving for the identity provider; without it, SSO signs in immediately.
+ */
+export function createFakeAuth(
+ overrides: Partial<FakeAuthWorld> = {},
+ options: {
+ onChange?: (world: FakeAuthWorld) => void;
+ /** Who Google/Apple sign in as. */
+ ssoEmail?: string;
+ ssoRedirect?: (
+ provider: SsoProvider,
+ intent: AuthIntent,
+ email: string
+ ) => Promise<void>;
+ } = {}
+) {
+ const [world, setWorld] = createStore<FakeAuthWorld>({
+ ...defaultFakeAuthWorld(),
+ ...overrides,
+ });
+ const [events, setEvents] = createSignal<FakeAuthEvent[]>([]);
+ const [notifications, setNotifications] = createSignal<string[]>([]);
+ const [calls, setCalls] = createSignal<string[]>([]);
+ const call = (name: string) => setCalls((list) => [...list, name]);
+
+ const update = (change: (draft: FakeAuthWorld) => void) => {
+ setWorld(produce(change));
+ options.onChange?.(structuredClone(unwrap(world)));
+ };
+ const signIn = (email: string) =>
+ update((draft) => {
+ draft.accounts[email] ??= { tutorialComplete: false };
+ draft.user = userFor(email, draft.accounts[email]);
+ draft.pendingEmail = undefined;
+ });
+
+ const session = (): AuthSession =>
+ world.user
+ ? { t: 'signed-in', user: { ...world.user } }
+ : { t: 'signed-out' };
+
+ const context: AuthContext = {
+ session,
+ startSso: async (provider, intent) => {
+ call(`sso:${provider}:${intent}`);
+ const email = options.ssoEmail ?? '[email protected]';
+ if (options.ssoRedirect)
+ return options.ssoRedirect(provider, intent, email);
+ signIn(email);
+ },
+ sendEmailCode: async ({ email, password }) => {
+ call(`sendCode:${email}`);
+ const failure = world.failures.sendCode;
+ if (failure !== undefined) return { t: 'failed', message: failure };
+ const expected = world.passwordAccounts[email];
+ if (expected !== undefined) {
+ if (password === undefined) return { t: 'password-required' };
+ if (password !== expected)
+ return {
+ t: 'failed',
+ message:
+ 'Failed to login. Check your email and password then try again.',
+ };
+ signIn(email);
+ return { t: 'signed-in' };
+ }
+ if (world.ssoDomains.some((domain) => email.endsWith(`@${domain}`)))
+ return { t: 'redirected' };
+ update((draft) => {
+ draft.pendingEmail = email;
+ });
+ return world.autoCode
+ ? { t: 'code-sent', autoCode: world.code }
+ : { t: 'code-sent' };
+ },
+ verifyEmailCode: async ({ email, code }) => {
+ call(`verify:${email}:${code}`);
+ if (world.failures.verify !== undefined) return { t: 'failed' };
+ if (code !== world.code) return { t: 'invalid-code' };
+ signIn(email);
+ return { t: 'verified' };
+ },
+ redeemSessionToken: async (token) => {
+ call(`redeem:${token}`);
+ const email = world.sessionTokens[token];
+ if (!email) return false;
+ signIn(email);
+ return true;
+ },
+ completeLogin: async () => {
+ call('completeLogin');
+ },
+ sendMobileWelcomeEmail: async (email) => {
+ call(`mobileWelcome:${email}`);
+ const outcome = world.mobileWelcome;
+ return outcome === 'sent'
+ ? { t: 'sent', alreadySent: false }
+ : { t: outcome };
+ },
+ identify: (user) => call(`identify:${user.id}`),
+ trackMobileSignupLead: (email) => call(`lead:${email}`),
+ pageView: (name) => call(`pageView:${name}`),
+ track: (event, data) => setEvents((list) => [...list, { event, data }]),
+ notifyFailure: (message) => setNotifications((list) => [...list, message]),
+ };
+
+ return { context, world, update, events, notifications, calls };
+}
diff --git a/apps/web/src/features/auth/tests/render.tsx b/apps/web/src/features/auth/tests/render.tsx
new file mode 100644
index 0000000000..0197538264
--- /dev/null
+++ b/apps/web/src/features/auth/tests/render.tsx
@@ -0,0 +1,17 @@
+import { render } from '@solidjs/testing-library';
+import type { JSX } from 'solid-js';
+import { AuthProvider } from '../context/auth-context';
+import { createFakeAuth, type FakeAuthWorld } from './fake-auth-context';
+
+/** Render `ui` under a fake auth backend seeded with `world`. */
+export function renderWithFakeAuth(
+ ui: () => JSX.Element,
+ world: Partial<FakeAuthWorld> = {},
+ options: Parameters<typeof createFakeAuth>[1] = {}
+) {
+ const fake = createFakeAuth(world, options);
+ const result = render(() => (
+ <AuthProvider value={fake.context}>{ui()}</AuthProvider>
+ ));
+ return { ...result, fake };
+}
diff --git a/apps/web/src/features/auth/views/auth-view.test.tsx b/apps/web/src/features/auth/views/auth-view.test.tsx
new file mode 100644
index 0000000000..9b2d8337fc
--- /dev/null
+++ b/apps/web/src/features/auth/views/auth-view.test.tsx
@@ -0,0 +1,234 @@
+import { cleanup, fireEvent, screen, waitFor } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { AuthIntent } from '../context/auth-context';
+import type { FakeAuthWorld } from '../tests/fake-auth-context';
+import { renderWithFakeAuth } from '../tests/render';
+import { AuthView, type SignupJourneySlots } from './auth-view';
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+function setup(
+ options: {
+ intent?: AuthIntent;
+ world?: Partial<FakeAuthWorld>;
+ initialEmail?: string;
+ autoStart?: boolean;
+ token?: string;
+ signupJourney?: (slots: SignupJourneySlots) => ReturnType<typeof Journey>;
+ } = {}
+) {
+ const verified = vi.fn();
+ const { fake } = renderWithFakeAuth(
+ () => (
+ <AuthView
+ intent={options.intent ?? 'login'}
+ showApple={false}
+ compact={false}
+ initialEmail={options.initialEmail}
+ autoStart={options.autoStart}
+ token={options.token}
+ onVerified={verified}
+ signupJourney={options.signupJourney}
+ signedIn={(user) => (
+ <p data-testid="signed-in">
+ {user.email} {user.tutorialComplete ? 'returning' : 'new'}
+ </p>
+ )}
+ />
+ ),
+ options.world
+ );
+ return { fake, verified };
+}
+
+const click = (name: string | RegExp) =>
+ fireEvent.click(screen.getByRole('button', { name }));
+// Stepper swaps steps on the next frame, so each step is awaited.
+const typeEmail = async (value: string) =>
+ fireEvent.input(await screen.findByPlaceholderText('[email protected]'), {
+ target: { value },
+ });
+const typeCode = async (value: string) =>
+ fireEvent.input(await screen.findByLabelText(/code/i), {
+ target: { value },
+ });
+
+describe('email sign-in', () => {
+ it('sends a code, verifies it, and hands off to the signed-in view', async () => {
+ const { fake, verified } = setup();
+ click('Continue with email');
+ await typeEmail('[email protected]');
+ click('Continue');
+ await screen.findByText('[email protected]');
+ await typeCode('424242');
+ await screen.findByTestId('signed-in');
+ expect(screen.getByTestId('signed-in').textContent).toBe(
+ '[email protected] returning'
+ );
+ expect(fake.calls()).toEqual(
+ expect.arrayContaining([
+ 'pageView:login',
+ 'sendCode:[email protected]',
+ 'verify:[email protected]:424242',
+ 'completeLogin',
+ 'identify:macro|[email protected]',
+ ])
+ );
+ expect(fake.events()).toContainEqual({
+ event: 'login',
+ data: { method: 'email' },
+ });
+ expect(verified).toHaveBeenCalledOnce();
+ });
+
+ it('keeps the verify step open on a wrong code', async () => {
+ setup();
+ click('Continue with email');
+ await typeEmail('[email protected]');
+ click('Continue');
+ await screen.findByText('[email protected]');
+ await typeCode('000000');
+ await screen.findByText('Invalid code.');
+ await typeCode('424242');
+ await screen.findByTestId('signed-in');
+ });
+
+ it('asks for a password only for password accounts', async () => {
+ setup({ world: { passwordAccounts: { '[email protected]': 'hunter2' } } });
+ click('Continue with email');
+ await typeEmail('[email protected]');
+ click('Continue');
+ const password = await screen.findByPlaceholderText('Password');
+ fireEvent.input(password, { target: { value: 'wrong' } });
+ click('Continue');
+ await screen.findByText(/Check your email and password/);
+ fireEvent.input(password, { target: { value: 'hunter2' } });
+ click('Continue');
+ await screen.findByTestId('signed-in');
+ });
+
+ it('lets the user resend after the countdown', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ const { fake } = setup();
+ click('Continue with email');
+ await typeEmail('[email protected]');
+ click('Continue');
+ await screen.findByText('[email protected]');
+ expect(
+ screen.getByRole('button', { name: /Resend \(45\)/ })
+ ).toHaveProperty('disabled', true);
+ await vi.advanceTimersByTimeAsync(45_000);
+ click('Resend');
+ await waitFor(() =>
+ expect(
+ fake.calls().filter((c) => c === 'sendCode:[email protected]')
+ ).toHaveLength(2)
+ );
+ });
+
+ it('goes back from verify to the email step, and from there to the picker', async () => {
+ setup();
+ click('Continue with email');
+ await typeEmail('[email protected]');
+ click('Continue');
+ await screen.findByText('[email protected]');
+ click('Change email');
+ await screen.findByPlaceholderText('[email protected]');
+ click('Back to sign in');
+ await screen.findByRole('button', { name: 'Continue with Google' });
+ });
+
+ it('signs straight in from a dev persona link when the backend returns the code', async () => {
+ setup({
+ initialEmail: '[email protected]',
+ autoStart: true,
+ world: { autoCode: true },
+ });
+ await screen.findByTestId('signed-in');
+ });
+
+ it('shows the server’s reason when sending fails', async () => {
+ setup({ world: { failures: { sendCode: 'Email is not allowed.' } } });
+ click('Continue with email');
+ await typeEmail('[email protected]');
+ click('Continue');
+ await screen.findByText('Email is not allowed.');
+ });
+});
+
+describe('single sign-on', () => {
+ it('starts Google with the page’s intent', async () => {
+ const { fake } = setup({ intent: 'login' });
+ click('Continue with Google');
+ await screen.findByTestId('signed-in');
+ expect(fake.calls()).toContain('sso:google:login');
+ });
+
+ it('records the email choice as a sign-up click on /signup', () => {
+ const { fake } = setup({ intent: 'signup' });
+ click('Continue with email');
+ expect(fake.events()).toContainEqual({
+ event: 'sign_up_click',
+ data: { method: 'email' },
+ });
+ });
+
+ it('redeems the session code an SSO return put on the URL', async () => {
+ setup({
+ token: 'tok-1',
+ world: { sessionTokens: { 'tok-1': '[email protected]' } },
+ });
+ await screen.findByText('[email protected] new');
+ });
+
+ it('reports a session code that cannot be redeemed', async () => {
+ const { fake } = setup({ token: 'expired' });
+ await waitFor(() =>
+ expect(fake.notifications()).toEqual([
+ 'Sign-in failed. Please try again.',
+ ])
+ );
+ expect(
+ screen.getByRole('button', { name: 'Continue with Google' })
+ ).toBeTruthy();
+ });
+});
+
+function Journey(props: SignupJourneySlots) {
+ return (
+ <section>
+ <button type="button" onClick={() => void props.onGoogle()}>
+ Connect work email
+ </button>
+ <p data-testid="showing-email">{String(props.showingEmail)}</p>
+ {props.emailForm}
+ </section>
+ );
+}
+
+describe('desktop sign-up', () => {
+ it('hands onboarding’s slides a Google sign-up and no email form until chosen', async () => {
+ const { fake } = setup({
+ intent: 'signup',
+ signupJourney: (slots) => <Journey {...slots} />,
+ });
+ expect(screen.getByTestId('showing-email').textContent).toBe('false');
+ expect(screen.queryByPlaceholderText('[email protected]')).toBeNull();
+ click('Connect work email');
+ await screen.findByText('[email protected] new');
+ expect(fake.calls()).toContain('sso:google:signup');
+ });
+
+ it('shows the email form inside the slides for an emailed sign-up link', () => {
+ setup({
+ intent: 'signup',
+ initialEmail: '[email protected]',
+ signupJourney: (slots) => <Journey {...slots} />,
+ });
+ expect(screen.getByTestId('showing-email').textContent).toBe('true');
+ expect(screen.getByDisplayValue('[email protected]')).toBeTruthy();
+ });
+});
diff --git a/apps/web/src/features/auth/views/auth-view.tsx b/apps/web/src/features/auth/views/auth-view.tsx
new file mode 100644
index 0000000000..39c2948871
--- /dev/null
+++ b/apps/web/src/features/auth/views/auth-view.tsx
@@ -0,0 +1,151 @@
+import { Stepper } from '@ui/components/Stepper';
+import { type JSX, Match, onMount, Show, Switch } from 'solid-js';
+import { EmailForm } from '../components/email-form';
+import { LoginCard } from '../components/login-card';
+import { LoginPicker } from '../components/login-picker';
+import { VerifyForm } from '../components/verify-form';
+import {
+ type AuthIntent,
+ type AuthUser,
+ useAuthContext,
+} from '../context/auth-context';
+import { createEmailLogin, type EmailLogin } from '../primitives/email-login';
+import {
+ createSessionIdentity,
+ redeemSessionToken,
+} from '../primitives/session';
+
+/** What desktop sign-up hands onboarding's opening slides. */
+export type SignupJourneySlots = {
+ onGoogle: () => Promise<void>;
+ onBackFromEmail: () => void;
+ emailForm: JSX.Element;
+ showingEmail: boolean;
+};
+
+/** Sign-in and sign-up: SSO or an emailed code, then whatever comes next. */
+export function AuthView(props: {
+ intent: AuthIntent;
+ showApple: boolean;
+ /** The header yields to the on-screen keyboard on phones. */
+ compact: boolean;
+ initialEmail?: string;
+ autoStart?: boolean;
+ /** The session code an SSO return put on the URL. */
+ token?: string;
+ onVerified?: () => void;
+ /** Desktop sign-up: onboarding's slides host Google and the email form. */
+ signupJourney?: (slots: SignupJourneySlots) => JSX.Element;
+ /** What a signed-in visitor sees instead. */
+ signedIn: (user: AuthUser) => JSX.Element;
+}) {
+ const context = useAuthContext();
+ const login = createEmailLogin(context, {
+ intent: props.intent,
+ initialEmail: props.initialEmail,
+ autoStart: props.autoStart,
+ onVerified: props.onVerified,
+ });
+ createSessionIdentity(context);
+ redeemSessionToken(context, props.token);
+ onMount(() => context.pageView(props.intent));
+
+ const user = () => {
+ const session = context.session();
+ return session.t === 'signed-in' ? session.user : undefined;
+ };
+
+ const signedOut = () => (
+ <Switch>
+ <Match when={props.signupJourney}>
+ {(journey) =>
+ journey()({
+ onGoogle: () => context.startSso('google', 'signup'),
+ onBackFromEmail: login.back,
+ showingEmail: login.step() !== 'choose',
+ emailForm: (
+ <Show when={login.step() !== 'choose'}>
+ <Stepper
+ step={login.step() === 'verify' ? 1 : 0}
+ transition={Stepper.transitions.scale}
+ >
+ <Stepper.Step>
+ <EmailStep login={login} />
+ </Stepper.Step>
+ <Stepper.Step>
+ <VerifyStep login={login} />
+ </Stepper.Step>
+ </Stepper>
+ </Show>
+ ),
+ })
+ }
+ </Match>
+ <Match when={true}>
+ <LoginCard compact={props.compact}>
+ <Stepper
+ step={STEP_INDEX[login.step()]}
+ transition={Stepper.transitions.scale}
+ >
+ <Stepper.Step>
+ <LoginPicker
+ showApple={props.showApple}
+ onGoogle={() => void context.startSso('google', props.intent)}
+ onApple={() => void context.startSso('apple', props.intent)}
+ onEmail={login.chooseEmail}
+ />
+ </Stepper.Step>
+ <Stepper.Step>
+ <EmailStep login={login} />
+ </Stepper.Step>
+ <Stepper.Step>
+ <VerifyStep login={login} />
+ </Stepper.Step>
+ </Stepper>
+ </LoginCard>
+ </Match>
+ </Switch>
+ );
+
+ return (
+ <Show when={user()} keyed fallback={signedOut()}>
+ {(signedIn) => props.signedIn(signedIn)}
+ </Show>
+ );
+}
+
+const STEP_INDEX = { choose: 0, email: 1, verify: 2 } as const;
+
+function EmailStep(props: { login: EmailLogin }) {
+ return (
+ <EmailForm
+ email={props.login.email()}
+ password={props.login.password()}
+ passwordRequired={props.login.passwordRequired()}
+ sending={props.login.sending()}
+ error={props.login.sendError()}
+ onEmailInput={props.login.setEmail}
+ onPasswordInput={props.login.setPassword}
+ onSubmit={props.login.submitEmail}
+ onBack={props.login.back}
+ />
+ );
+}
+
+function VerifyStep(props: { login: EmailLogin }) {
+ return (
+ <VerifyForm
+ email={props.login.email()}
+ code={props.login.code()}
+ verifying={props.login.verifying()}
+ canVerify={props.login.canVerify()}
+ resendIn={props.login.resendIn()}
+ resending={props.login.sending()}
+ error={props.login.verifyError() ?? props.login.sendError()}
+ onCodeInput={props.login.setCode}
+ onVerify={props.login.verify}
+ onResend={() => void props.login.resend()}
+ onBack={props.login.back}
+ />
+ );
+}
diff --git a/apps/web/src/features/auth/views/mobile-web-signup-view.test.tsx b/apps/web/src/features/auth/views/mobile-web-signup-view.test.tsx
new file mode 100644
index 0000000000..8f1c857881
--- /dev/null
+++ b/apps/web/src/features/auth/views/mobile-web-signup-view.test.tsx
@@ -0,0 +1,59 @@
+import { cleanup, fireEvent, screen, waitFor } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { FakeAuthWorld } from '../tests/fake-auth-context';
+import { renderWithFakeAuth } from '../tests/render';
+import { MobileWebSignupView } from './mobile-web-signup-view';
+
+afterEach(cleanup);
+
+function setup(world: Partial<FakeAuthWorld> = {}) {
+ const login = vi.fn();
+ const { fake } = renderWithFakeAuth(
+ () => <MobileWebSignupView onLogin={login} onBackHome={() => {}} />,
+ world
+ );
+ return { fake, login };
+}
+
+const submit = (email: string) => {
+ fireEvent.input(screen.getByLabelText('Email address'), {
+ target: { value: email },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Sign Up' }));
+};
+
+describe('mobile-web sign-up', () => {
+ it('emails a desktop link and records the lead', async () => {
+ const { fake } = setup();
+ submit(' [email protected] ');
+ await screen.findByText('Macro is better on desktop.');
+ expect(fake.calls()).toEqual(
+ expect.arrayContaining([
+ 'identify:[email protected]',
+ 'mobileWelcome:[email protected]',
+ ])
+ );
+ });
+
+ it('stays on the capture step for an empty or rejected address', async () => {
+ const { fake } = setup({ mobileWelcome: 'invalid-email' });
+ submit(' ');
+ expect(fake.calls()).not.toContain('mobileWelcome:');
+ submit('[email protected]');
+ await waitFor(() =>
+ expect(fake.notifications()).toEqual(['Invalid email address.'])
+ );
+ expect(screen.getByRole('button', { name: 'Sign Up' })).toBeTruthy();
+ });
+
+ it('sends existing users to sign in', () => {
+ const { fake, login } = setup();
+ fireEvent.click(screen.getByRole('link', { name: 'Login' }));
+ expect(login).toHaveBeenCalledOnce();
+ expect(fake.events()).toContainEqual({
+ event: 'login_from_onboarding',
+ data: undefined,
+ });
+ });
+});
diff --git a/apps/web/src/features/auth/views/mobile-web-signup-view.tsx b/apps/web/src/features/auth/views/mobile-web-signup-view.tsx
new file mode 100644
index 0000000000..3f7d9d602a
--- /dev/null
+++ b/apps/web/src/features/auth/views/mobile-web-signup-view.tsx
@@ -0,0 +1,50 @@
+import { onMount, Show } from 'solid-js';
+import { MobileWebSignupSent } from '../components/mobile-web-signup-sent';
+import { MobileWebWelcome } from '../components/mobile-web-welcome';
+import { useAuthContext } from '../context/auth-context';
+import { createMobileSignup } from '../primitives/mobile-signup';
+
+/**
+ * Signing up on a phone is a poor experience, so mobile-web visitors leave
+ * their email and get a link to open on desktop instead.
+ */
+export function MobileWebSignupView(props: {
+ onLogin: () => void;
+ onBackHome: () => void;
+}) {
+ const context = useAuthContext();
+ const signup = createMobileSignup(context);
+ return (
+ <Show
+ when={signup.submitted()}
+ keyed
+ fallback={
+ <Welcome
+ pending={signup.pending()}
+ onSignUp={(email) => void signup.submit(email)}
+ onLogin={() => {
+ context.track('login_from_onboarding');
+ props.onLogin();
+ }}
+ />
+ }
+ >
+ {(email) => <Sent email={email} onBackHome={props.onBackHome} />}
+ </Show>
+ );
+}
+
+function Welcome(props: Parameters<typeof MobileWebWelcome>[0]) {
+ const context = useAuthContext();
+ onMount(() => context.track('mobile_web_welcome_viewed'));
+ return <MobileWebWelcome {...props} />;
+}
+
+function Sent(props: { email: string; onBackHome: () => void }) {
+ const context = useAuthContext();
+ onMount(() => {
+ context.track('mobile_web_signup_sent_viewed');
+ context.trackMobileSignupLead(props.email);
+ });
+ return <MobileWebSignupSent onBackHome={props.onBackHome} />;
+}
diff --git a/apps/web/src/features/getting-started/getting-started.tsx b/apps/web/src/features/getting-started/getting-started.tsx
index 8d2e779bde..fdc6f493b6 100644
--- a/apps/web/src/features/getting-started/getting-started.tsx
+++ b/apps/web/src/features/getting-started/getting-started.tsx
@@ -1,6 +1,6 @@
import { DOCS_BASE } from '@app/constants/docs-links';
import { HomeBackfillProgress } from '@app/features/home/home-backfill-progress';
-import { InteractiveOnboardingModal } from '@app/features/onboarding/InteractiveOnboardingModal';
+import { InteractiveOnboardingModal } from '@app/features/tutorial/InteractiveOnboardingModal';
import { useSplitLayout } from '@components/app/split-layout/layout';
import type { SplitContent } from '@components/app/split-layout/layoutManager';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
diff --git a/apps/web/src/features/gtm-invite/InviteOfferPanel.tsx b/apps/web/src/features/gtm-invite/InviteOfferPanel.tsx
index 150b29b37e..a9771b4adc 100644
--- a/apps/web/src/features/gtm-invite/InviteOfferPanel.tsx
+++ b/apps/web/src/features/gtm-invite/InviteOfferPanel.tsx
@@ -1,5 +1,4 @@
import { PLANS, planFeatures } from '@app/features/paywall/plans';
-import { SkipButton } from '@app/features/setup/flow/shared';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { enableAiUsageBilling } from '@core/constant/featureFlags';
@@ -92,11 +91,15 @@ export function InviteOfferPanel(props: {
{props.finishing ? 'Heading to checkout…' : 'Claim your free month'}
<ArrowRight class="size-5" />
</Button>
- <SkipButton
- label="Continue with Free instead"
+ <Button
+ variant="ghost"
+ size="sm"
+ class="self-center text-ink-muted"
disabled={props.finishing}
onClick={() => props.onContinueFree()}
- />
+ >
+ Continue as Guest instead
+ </Button>
</div>
</div>
);
diff --git a/apps/web/src/features/gtm-invite/InviteWelcome.tsx b/apps/web/src/features/gtm-invite/InviteWelcome.tsx
index 0f1b23fef9..16c216c04c 100644
--- a/apps/web/src/features/gtm-invite/InviteWelcome.tsx
+++ b/apps/web/src/features/gtm-invite/InviteWelcome.tsx
@@ -1,5 +1,5 @@
-import { NoiseBackground } from '@app/features/setup/flow/shared';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { NoiseBackground } from '@core/component/NoiseBackground';
import { useIsAuthenticated } from '@core/context/user';
import LogoIcon from '@icon/macro-logo.svg';
import ArrowRight from '@phosphor/arrow-right.svg';
diff --git a/apps/web/src/features/auth/mobile-onboarding/MobileAuthWelcome.tsx b/apps/web/src/features/mobile-onboarding/MobileAuthWelcome.tsx
similarity index 100%
rename from apps/web/src/features/auth/mobile-onboarding/MobileAuthWelcome.tsx
rename to apps/web/src/features/mobile-onboarding/MobileAuthWelcome.tsx
diff --git a/apps/web/src/features/auth/mobile-onboarding/MobileOnboarding.tsx b/apps/web/src/features/mobile-onboarding/MobileOnboarding.tsx
similarity index 100%
rename from apps/web/src/features/auth/mobile-onboarding/MobileOnboarding.tsx
rename to apps/web/src/features/mobile-onboarding/MobileOnboarding.tsx
diff --git a/apps/web/src/features/auth/mobile-onboarding/OnboardingConnectAccounts.tsx b/apps/web/src/features/mobile-onboarding/OnboardingConnectAccounts.tsx
similarity index 100%
rename from apps/web/src/features/auth/mobile-onboarding/OnboardingConnectAccounts.tsx
rename to apps/web/src/features/mobile-onboarding/OnboardingConnectAccounts.tsx
diff --git a/apps/web/src/features/auth/mobile-onboarding/OnboardingCreateAccount.tsx b/apps/web/src/features/mobile-onboarding/OnboardingCreateAccount.tsx
similarity index 96%
rename from apps/web/src/features/auth/mobile-onboarding/OnboardingCreateAccount.tsx
rename to apps/web/src/features/mobile-onboarding/OnboardingCreateAccount.tsx
index 6ed13b6ba2..efdbcf33a6 100644
--- a/apps/web/src/features/auth/mobile-onboarding/OnboardingCreateAccount.tsx
+++ b/apps/web/src/features/mobile-onboarding/OnboardingCreateAccount.tsx
@@ -1,8 +1,8 @@
+import { useSsoLogin } from '@app/features/auth/useSsoLogin';
import { GOOGLE_GMAIL_IDP } from '@core/auth/email';
import IconGoogle from '@icon/macro-google.svg';
import { useNavigate } from '@solidjs/router';
import { Button } from '@ui';
-import { useSsoLogin } from '../useSsoLogin';
/**
* Onboarding step 0 — create the account by connecting the primary Gmail via
diff --git a/apps/web/src/features/auth/mobile-onboarding/OnboardingInbox.tsx b/apps/web/src/features/mobile-onboarding/OnboardingInbox.tsx
similarity index 100%
rename from apps/web/src/features/auth/mobile-onboarding/OnboardingInbox.tsx
rename to apps/web/src/features/mobile-onboarding/OnboardingInbox.tsx
diff --git a/apps/web/src/features/onboarding/MobileWebSignup.tsx b/apps/web/src/features/onboarding/MobileWebSignup.tsx
deleted file mode 100644
index ea475da76a..0000000000
--- a/apps/web/src/features/onboarding/MobileWebSignup.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { toast } from '@core/component/Toast/Toast';
-import { useSendMobileWelcomeEmail } from '@queries/auth';
-import { createSignal, Match, Switch } from 'solid-js';
-import { match } from 'ts-pattern';
-import MobileWebSignupSent from './MobileWebSignupSent';
-import MobileWebWelcome from './MobileWebWelcome';
-
-/**
- * Mobile-web entry flow for unauthenticated visitors on a phone/tablet browser.
- *
- * Signing up on mobile web is a poor experience, so instead of pushing visitors
- * through Google SSO + onboarding we capture their email and send them a link
- * to open on desktop (POST /mobile-welcome-email on the auth service). The two
- * screens are:
- * 1. {@link MobileWebWelcome} — captures the email.
- * 2. {@link MobileWebSignupSent} — confirms "we emailed you a desktop link".
- *
- * Identifying the email also hands it to the analytics providers so downstream
- * marketing automation can pick it up.
- */
-export default function MobileWebSignup() {
- const analytics = useAnalytics();
- const sendWelcomeEmail = useSendMobileWelcomeEmail();
- const [submittedEmail, setSubmittedEmail] = createSignal<string | null>(null);
-
- const handleSignUp = async (email: string) => {
- const trimmed = email.trim();
- // Don't advance on an empty submit — keep the visitor on the capture step.
- if (!trimmed || sendWelcomeEmail.isPending) return;
- analytics.identify(trimmed, { email: trimmed });
-
- const result = await sendWelcomeEmail.mutateAsync(trimmed);
- if (result.isErr()) {
- match(result.error[0]?.code)
- .with('INVALID_EMAIL', () => toast.failure('Invalid email address.'))
- .with('RATE_LIMITED', () =>
- toast.failure('Too many attempts. Please try again later.')
- )
- .otherwise(() =>
- toast.failure('Something went wrong. Please try again.')
- );
- return;
- }
-
- // `sent: false` means we already emailed this address — the confirmation
- // screen is still accurate, so advance either way.
- setSubmittedEmail(trimmed);
- };
-
- return (
- <Switch fallback={<MobileWebWelcome onSignUp={handleSignUp} />}>
- <Match when={submittedEmail() !== null}>
- <MobileWebSignupSent email={submittedEmail() ?? undefined} />
- </Match>
- </Switch>
- );
-}
diff --git a/apps/web/src/features/onboarding/MobileWebSignupSent.tsx b/apps/web/src/features/onboarding/MobileWebSignupSent.tsx
deleted file mode 100644
index 1aacd4ecba..0000000000
--- a/apps/web/src/features/onboarding/MobileWebSignupSent.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { MOBILE_WEB_SIGNUP_LEAD_VALUE } from '@app/lib/analytics/leadValues';
-import { getWebOrigin } from '@core/util/webOrigin';
-import LogoIcon from '@icon/macro-logo.svg';
-import { onMount } from 'solid-js';
-
-type Props = {
- /** Email submitted on the prior step — used as the Google conversion `transaction_id` for dedup. */
- email?: string;
-};
-
-export default function MobileWebSignupSent(props: Props) {
- const analytics = useAnalytics();
-
- onMount(() => {
- analytics.track('mobile_web_signup_sent_viewed');
- // Fire as both Lead and CompleteRegistration: Meta's Maximize Value
- // campaigns don't support Lead, so we duplicate to CompleteRegistration.
- // The existing Lead event is used in a custom conversion we use in an ad campaign, so can't remove it
- const leadPayload = {
- content_name: 'mobile_web_signup',
- value: MOBILE_WEB_SIGNUP_LEAD_VALUE,
- currency: 'USD',
- };
- analytics.trackMeta('Lead', leadPayload);
- analytics.trackMeta('CompleteRegistration', leadPayload);
- analytics.trackGoogleConversion('mobile_web_lead', {
- value: MOBILE_WEB_SIGNUP_LEAD_VALUE,
- currency: 'USD',
- transaction_id: props.email,
- });
- });
-
- return (
- <div class="flex flex-col size-full p-6 overflow-hidden relative">
- <div class="flex flex-col items-start gap-4 w-full max-w-md mx-auto mt-6">
- <LogoIcon class="size-16 text-accent self-center" />
- <h2 class="text-3xl font-semibold text-ink mt-3">
- Macro is better on desktop.
- </h2>
- <p class="text-base text-ink/60 mt-4">
- We sent a link to your inbox - open it on your computer for the full
- Macro experience.
- </p>
-
- <button
- type="button"
- onClick={() => {
- window.location.href = getWebOrigin();
- }}
- class="w-full px-3 py-2.5 text-lg font-bold rounded-xs bg-accent text-surface border-none mt-16"
- >
- Back to Home
- </button>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/features/onboarding/apply-workspace-accent.test.ts b/apps/web/src/features/onboarding/apply-workspace-accent.test.ts
new file mode 100644
index 0000000000..3c53ebf691
--- /dev/null
+++ b/apps/web/src/features/onboarding/apply-workspace-accent.test.ts
@@ -0,0 +1,75 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ mode: 'system',
+ system: 'dark',
+ id: 'new-theme',
+ themes: [] as { id: string }[],
+ apply: vi.fn(),
+ save: vi.fn(),
+ update: vi.fn(),
+ token: vi.fn(),
+ light: vi.fn(),
+ dark: vi.fn(),
+}));
+vi.mock('@theme/constants', () => ({
+ DEFAULT_DARK_THEME: 'Macro Dark',
+ DEFAULT_LIGHT_THEME: 'Macro Light',
+}));
+vi.mock('@theme/signals/themeSignals', () => ({
+ currentThemeId: () => mocks.id,
+ themeMode: () => mocks.mode,
+ systemMode: () => mocks.system,
+ userThemes: () => mocks.themes,
+ setDarkModeTheme: mocks.dark,
+ setLightModeTheme: mocks.light,
+}));
+vi.mock('@theme/utils/themeUtils', () => ({
+ applyTheme: mocks.apply,
+ saveTheme: mocks.save,
+ updateTheme: mocks.update,
+ updateLiveThemeColorToken: mocks.token,
+}));
+
+import { applyWorkspaceAccent } from './apply-workspace-accent';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ sessionStorage.clear();
+ mocks.mode = 'system';
+ mocks.system = 'dark';
+ mocks.themes = [];
+});
+describe('workspace palette', () => {
+ it.each(['light', 'dark'])(
+ 'forks the default %s theme and pins the chosen accent',
+ (mode) => {
+ mocks.system = mode;
+ applyWorkspaceAccent('#65d8ac', 'person');
+ expect(mocks.apply).toHaveBeenNthCalledWith(
+ 1,
+ `Macro ${mode === 'dark' ? 'Dark' : 'Light'}`
+ );
+ expect(mocks.token).toHaveBeenCalledWith('accent', '#65d8ac');
+ expect(mocks.save).toHaveBeenCalledOnce();
+ expect(mode === 'dark' ? mocks.dark : mocks.light).toHaveBeenCalledWith(
+ 'new-theme'
+ );
+ expect(mocks.apply).toHaveBeenLastCalledWith('new-theme');
+ }
+ );
+ it('updates the same fork on back/forward instead of accumulating themes', () => {
+ mocks.themes = [{ id: 'new-theme' }];
+ sessionStorage.setItem('onboarding-theme:person:dark', 'new-theme');
+ applyWorkspaceAccent('#f77d67', 'person');
+ expect(mocks.update).toHaveBeenCalledWith('new-theme', 'My workspace dark');
+ expect(mocks.save).not.toHaveBeenCalled();
+ });
+ it('does not reuse a different user’s fork', () => {
+ mocks.themes = [{ id: 'old-theme' }];
+ sessionStorage.setItem('onboarding-theme:other:dark', 'old-theme');
+ applyWorkspaceAccent('#f77d67', 'person');
+ expect(mocks.save).toHaveBeenCalledOnce();
+ expect(mocks.update).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/onboarding/apply-workspace-accent.ts b/apps/web/src/features/onboarding/apply-workspace-accent.ts
new file mode 100644
index 0000000000..5e0bac74b6
--- /dev/null
+++ b/apps/web/src/features/onboarding/apply-workspace-accent.ts
@@ -0,0 +1,35 @@
+import { DEFAULT_DARK_THEME, DEFAULT_LIGHT_THEME } from '@theme/constants';
+import {
+ currentThemeId,
+ setDarkModeTheme,
+ setLightModeTheme,
+ systemMode,
+ themeMode,
+ userThemes,
+} from '@theme/signals/themeSignals';
+import {
+ applyTheme,
+ saveTheme,
+ updateLiveThemeColorToken,
+ updateTheme,
+} from '@theme/utils/themeUtils';
+
+/** Fork the built-in palette, never the user's unrelated custom theme. */
+export function applyWorkspaceAccent(color: string, userId: string) {
+ const mode = themeMode() === 'system' ? systemMode() : themeMode();
+ const storageKey = `onboarding-theme:${userId}:${mode}`;
+ const existingId = sessionStorage.getItem(storageKey);
+ applyTheme(mode === 'dark' ? DEFAULT_DARK_THEME : DEFAULT_LIGHT_THEME);
+ updateLiveThemeColorToken('accent', color);
+ const name = `My workspace ${mode}`;
+ if (existingId && userThemes().some((theme) => theme.id === existingId)) {
+ updateTheme(existingId, name);
+ } else {
+ saveTheme(name);
+ }
+ const id = currentThemeId();
+ sessionStorage.setItem(storageKey, id);
+ if (mode === 'dark') setDarkModeTheme(id);
+ else setLightModeTheme(id);
+ applyTheme(id);
+}
diff --git a/apps/web/src/features/onboarding/assets/a16z.svg b/apps/web/src/features/onboarding/assets/a16z.svg
new file mode 100644
index 0000000000..7a438780dc
--- /dev/null
+++ b/apps/web/src/features/onboarding/assets/a16z.svg
@@ -0,0 +1,22 @@
+<svg width="169" height="40" viewBox="0 0 169 40" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M78.7445 21.4403C74.986 21.4403 71.9492 24.4374 71.9492 28.3541C71.9492 32.2449 74.986 35.2681 78.7445 35.2681C82.5285 35.2681 85.5399 32.2449 85.5399 28.3541C85.5399 24.4374 82.5285 21.4403 78.7445 21.4403ZM78.7445 24.2006C81.0102 24.2006 82.7606 25.9622 82.7606 28.3541C82.7606 30.7467 81.0102 32.5077 78.7445 32.5077C76.4795 32.5077 74.7295 30.7467 74.7295 28.3541C74.7295 25.9622 76.4795 24.2006 78.7445 24.2006Z" fill="currentColor"/>
+<path d="M135.098 30.8204V24.5128H138.288V21.7802H135.098V18.1002L132.318 18.9412V21.7802H129.951V24.5128H132.318V30.8204C132.318 34.2374 134.017 35.4464 138.288 34.9209V32.3717C136.179 32.4767 135.098 32.5024 135.098 30.8204Z" fill="currentColor"/>
+<path d="M149.483 32.2741H143.115L149.463 24.4655H149.469V21.8215H139.669V24.4655H145.999L139.672 32.2741H139.669V34.918H149.483V32.2741Z" fill="currentColor"/>
+<path d="M37.715 12.1547C37.715 12.1492 37.7142 12.144 37.7134 12.1388L37.7128 12.1349L37.7124 12.1321C37.7123 12.1308 37.7121 12.1296 37.712 12.1283C37.7119 12.1271 37.7119 12.126 37.7118 12.1248V12.1843L37.7119 12.1823C37.712 12.181 37.7121 12.1796 37.7123 12.1783C37.7126 12.1757 37.713 12.1731 37.7134 12.1704C37.7142 12.1652 37.715 12.16 37.715 12.1547Z" fill="currentColor"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M38.619 1.22502L41.4487 0.374451V18.8001H38.619V17.79C37.3256 18.7448 35.6972 19.2545 33.9412 19.0745C30.7876 18.7512 28.2081 16.1464 27.8682 12.928C27.8403 12.6674 27.8274 12.4096 27.8274 12.1547H27.8271C27.8271 12.1544 27.8271 12.1541 27.8272 12.1538L27.8273 12.1535C27.8274 12.1533 27.8274 12.1532 27.8274 12.1529C27.8274 12.1451 27.8279 12.1374 27.8284 12.1296C27.829 12.1219 27.8295 12.1141 27.8295 12.1063C27.8312 11.8738 27.8427 11.6438 27.8665 11.4174C27.8712 11.3693 27.879 11.3221 27.8868 11.2748L27.8869 11.2745L27.8869 11.2742C27.8923 11.2419 27.8976 11.2094 27.902 11.1767L27.9076 11.1365C27.928 10.9911 27.9483 10.846 27.9777 10.7042C27.9904 10.6431 28.0064 10.5834 28.0223 10.5237C28.0307 10.4922 28.0391 10.4607 28.047 10.429L28.0599 10.3778C28.0903 10.2568 28.1206 10.136 28.1579 10.0178C28.1806 9.94596 28.2067 9.87615 28.2329 9.8061L28.233 9.80578C28.2417 9.7825 28.2504 9.7592 28.259 9.73578L28.2707 9.70381C28.3127 9.5884 28.3548 9.47296 28.4033 9.36052C28.4359 9.28517 28.4716 9.2119 28.5073 9.13848C28.516 9.12067 28.5247 9.1028 28.5334 9.08494C28.5898 8.9678 28.647 8.85067 28.7098 8.73709C28.7553 8.65488 28.8043 8.57504 28.8533 8.49513L28.8673 8.4722C28.9339 8.36361 29.0019 8.25644 29.0737 8.15176C29.1326 8.06667 29.1943 7.98443 29.2564 7.90218C29.3331 7.80142 29.4108 7.70315 29.4921 7.60702C29.559 7.52834 29.6277 7.45179 29.6978 7.37595C29.7828 7.2841 29.8703 7.19473 29.9603 7.10786C30.0342 7.0363 30.1088 6.96651 30.1862 6.89815C30.2803 6.81484 30.3772 6.73544 30.4755 6.65747C30.5561 6.59374 30.6366 6.53108 30.7196 6.4709C30.8224 6.3972 30.9277 6.32813 31.034 6.26013L31.0729 6.23541C31.1455 6.1891 31.2183 6.14276 31.2934 6.09956C31.4042 6.03549 31.5189 5.97746 31.6336 5.91944C31.6515 5.91039 31.6695 5.90124 31.6874 5.89213L31.6876 5.892C31.7591 5.85568 31.8306 5.81928 31.9038 5.7866C32.0178 5.73544 32.1349 5.691 32.2519 5.6466L32.2525 5.64638L32.2723 5.63884C32.3007 5.62816 32.3288 5.6172 32.357 5.60626L32.3574 5.60611C32.42 5.58175 32.4826 5.55739 32.5467 5.5363C32.6661 5.49715 32.7883 5.46525 32.9108 5.43327L32.9111 5.43318L32.9511 5.42272C32.9809 5.4149 33.0106 5.40664 33.0402 5.39838C33.0996 5.38185 33.159 5.36528 33.2199 5.35223C33.3631 5.32111 33.5096 5.30005 33.6561 5.27901L33.6842 5.27497C33.7161 5.27046 33.7477 5.26501 33.7794 5.25956C33.8253 5.25164 33.8713 5.24371 33.9182 5.23866C34.1549 5.21338 34.3944 5.19878 34.6377 5.19878C36.1263 5.19878 37.4985 5.69225 38.619 6.51933V1.22502ZM33.777 16.1315C36.3442 16.6802 38.6012 14.7042 38.619 12.1843V12.1248C38.6033 9.89172 36.8285 8.08554 34.6377 8.08554C34.491 8.08554 34.3459 8.0948 34.203 8.11082C34.173 8.11425 34.1436 8.11929 34.1141 8.12435L34.1032 8.12621C34.0904 8.1284 34.0775 8.13055 34.0646 8.13254C33.9694 8.14642 33.8742 8.16138 33.7812 8.18203C33.7458 8.1901 33.7108 8.19975 33.6758 8.2094L33.649 8.21676C33.6404 8.2191 33.6318 8.22142 33.6232 8.22369C33.5399 8.24612 33.4566 8.26961 33.3754 8.29738C33.3213 8.3159 33.2683 8.33655 33.2153 8.3572C33.1383 8.38746 33.062 8.41951 32.9877 8.45404C32.9351 8.47861 32.8835 8.50389 32.8326 8.53059C32.7597 8.56869 32.6882 8.60928 32.6178 8.65164C32.5697 8.68048 32.5216 8.70932 32.4749 8.7403C32.4034 8.78765 32.3347 8.83856 32.2664 8.89019C32.2531 8.90037 32.2397 8.91036 32.2263 8.92035C32.198 8.94146 32.1697 8.96253 32.1423 8.98525C32.068 9.04578 31.998 9.11129 31.9282 9.17716L31.9195 9.18549C31.9149 9.18975 31.9103 9.19398 31.9057 9.19818L31.8967 9.20637L31.8874 9.21483C31.8703 9.23025 31.8531 9.24573 31.8369 9.2619C31.74 9.35981 31.6476 9.46234 31.5608 9.56987C31.5553 9.57655 31.5504 9.58372 31.5454 9.59092C31.5408 9.59751 31.5362 9.60416 31.5312 9.61045C31.4562 9.70587 31.3844 9.80414 31.3181 9.90597C31.301 9.93243 31.2853 9.95983 31.2696 9.98712C31.2617 10.001 31.2537 10.0148 31.2456 10.0284C31.1982 10.1071 31.1515 10.1862 31.1093 10.2684C31.0893 10.3072 31.0712 10.3472 31.053 10.3871L31.0399 10.4158C31.0033 10.4941 30.9685 10.5728 30.9371 10.654C30.9172 10.7036 30.8998 10.7547 30.8825 10.8053L30.8789 10.816C30.8513 10.8965 30.8259 10.9776 30.8036 11.0602C30.7882 11.1172 30.7736 11.1742 30.7604 11.2322C30.7412 11.3166 30.7255 11.402 30.7115 11.4882C30.7021 11.5459 30.6927 11.6039 30.6858 11.6623C30.6749 11.7538 30.669 11.8467 30.6645 11.94C30.6636 11.9583 30.6624 11.9766 30.6612 11.9949C30.6589 12.0317 30.6566 12.0686 30.6561 12.1059C30.6526 12.4082 30.6791 12.718 30.744 13.0331C31.0581 14.5686 32.2734 15.8103 33.777 16.1315Z" fill="currentColor"/>
+<path d="M10.3396 12.1547C10.3396 12.1493 10.3389 12.1442 10.3381 12.1391C10.3374 12.1344 10.3366 12.1297 10.3365 12.1248V12.1843C10.3366 12.1795 10.3374 12.1748 10.3381 12.1701C10.3389 12.165 10.3396 12.1599 10.3396 12.1547Z" fill="currentColor"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M11.1105 5.62078V6.51942C9.98969 5.69234 8.61769 5.19887 7.12935 5.19887C3.11832 5.19887 -0.0829978 8.74004 0.359577 12.9281C0.699483 16.1468 3.27886 18.7513 6.43267 19.0745C8.18829 19.2546 9.81715 18.7449 11.1105 17.7901V18.8002H13.94V5.62078H11.1105ZM11.1105 12.1844C11.0926 14.7043 8.83544 16.6803 6.26829 16.1316C4.76458 15.8102 3.54946 14.5687 3.23501 13.0332C2.69642 10.4024 4.64776 8.08564 7.12935 8.08564C9.31971 8.08564 11.0945 9.89182 11.1105 12.1249V12.1844Z" fill="currentColor"/>
+<path d="M93.3654 21.5459V24.6214C91.5375 24.4901 89.4012 25.3577 89.4012 28.3018V34.9262H86.6209V21.782H89.4012V23.9905C90.1734 22.2028 91.7432 21.5459 93.3654 21.5459Z" fill="currentColor"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M100.083 21.4403C96.3249 21.4403 93.2877 24.4374 93.2877 28.3541C93.2877 32.2449 96.3249 35.2681 100.083 35.2681C103.867 35.2681 106.879 32.2449 106.879 28.3541C106.879 24.4374 103.867 21.4403 100.083 21.4403ZM100.083 24.2006C102.349 24.2006 104.099 25.9622 104.099 28.3541C104.099 30.7467 102.349 32.5077 100.083 32.5077C97.8184 32.5077 96.0679 30.7467 96.0679 28.3541C96.0679 25.9622 97.8184 24.2006 100.083 24.2006Z" fill="currentColor"/>
+<path d="M125.173 21.782L121.131 34.9262H118.403L115.725 26.0672L113.022 34.9262H110.294L106.254 21.782H109.188L111.685 30.8518L114.387 21.782H117.039L119.715 30.8518L122.238 21.782H125.173Z" fill="currentColor"/>
+<path d="M128.879 21.782H126.099V34.9262H128.879V21.782Z" fill="currentColor"/>
+<path d="M49.2962 5.41177V8.48759C47.4684 8.35586 45.332 9.22353 45.332 12.1676V18.7923H42.5518V5.64818H45.332V7.85633C46.1042 6.06902 47.6744 5.41177 49.2962 5.41177Z" fill="currentColor"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M62.015 16.2612L62.0271 16.2686C62.0261 16.2701 62.025 16.2715 62.024 16.2729L62.021 16.2767C62.0189 16.2794 62.0169 16.282 62.015 16.2848V23.4623C62.8649 22.095 64.2542 21.4385 66.0042 21.4385C68.8866 21.4385 70.9456 23.4356 70.9456 26.8524V34.921H68.166V27.1415C68.166 25.1441 67.0341 24.092 65.284 24.092C63.4565 24.092 62.015 25.1961 62.015 27.8767V34.921H59.2361V18.5815C58.3966 18.934 57.4498 19.134 56.3907 19.134C52.1427 19.134 49.3889 16.1636 49.3889 12.2199C49.3889 8.32987 52.1427 5.30638 56.1843 5.30638C60.0195 5.30638 62.6453 8.46089 62.6453 12.2466C62.6453 12.6408 62.5937 13.0616 62.5421 13.4298H52.2978C52.7347 15.4796 54.3568 16.5313 56.4158 16.5313C57.6133 16.5313 58.5744 16.1024 59.2361 15.4817C59.4275 15.302 59.598 15.1083 59.7364 14.9015L62.015 16.2612ZM56.1588 7.88304C57.8319 7.88304 59.454 8.85538 59.8399 11.1162H52.272C52.6576 9.14448 54.0737 7.88304 56.1588 7.88304Z" fill="currentColor"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M73.5846 14.9014C72.9672 15.8217 71.8087 16.5314 70.2639 16.5314C68.2046 16.5314 66.5832 15.4799 66.145 13.4297H76.3903C76.4415 13.0615 76.4931 12.6411 76.4931 12.2466C76.4931 8.46081 73.8677 5.3063 70.0325 5.3063C65.9912 5.3063 63.2364 8.32978 63.2364 12.2202C63.2364 16.1635 65.9912 19.1339 70.2382 19.1339C72.7608 19.1339 74.6914 18.0562 75.8757 16.2685L73.5846 14.9014ZM70.0063 7.88295C71.6797 7.88295 73.3011 8.85494 73.6874 11.1161H66.1199C66.5058 9.1444 67.9219 7.88295 70.0063 7.88295Z" fill="currentColor"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M105.399 16.5314C106.944 16.5314 108.102 15.8217 108.72 14.9014L111.011 16.2685C109.826 18.0562 107.896 19.1339 105.373 19.1339C101.127 19.1339 98.3716 16.1635 98.3716 12.2202C98.3716 8.32978 101.127 5.3063 105.168 5.3063C109.003 5.3063 111.628 8.46081 111.628 12.2466C111.628 12.6411 111.577 13.0615 111.525 13.4297H101.28C101.718 15.4799 103.34 16.5314 105.399 16.5314ZM108.823 11.1161C108.437 8.85494 106.815 7.88295 105.142 7.88295C103.057 7.88295 101.641 9.1444 101.255 11.1161H108.823Z" fill="currentColor"/>
+<path d="M126.099 18.8067H128.879V16.2433H126.099V18.8067Z" fill="currentColor"/>
+<path d="M21.8433 5.3024C20.0932 5.3024 18.7035 5.95965 17.8538 7.32684V5.81795L17.8492 5.81937V5.60575H15.071V6.69665H15.0747V18.7853H17.8538V11.741C17.8538 9.0604 19.2955 7.95667 21.1223 7.95667C22.8724 7.95667 24.0047 9.00841 24.0047 11.0058V18.7853H26.7843V10.7167C26.7843 7.29978 24.7257 5.3024 21.8433 5.3024Z" fill="currentColor"/>
+<path d="M115.805 18.7853H113.026L113.023 5.62747H115.803L115.805 7.32684C116.655 5.95965 118.045 5.3024 119.795 5.3024C122.677 5.3024 124.736 7.29978 124.736 10.7167V18.7853H121.956V11.0058C121.956 9.00841 120.824 7.95667 119.074 7.95667C117.247 7.95667 115.805 9.0604 115.805 11.741V18.7853Z" fill="currentColor"/>
+<path d="M80.1219 9.27613C80.1219 8.32978 80.997 7.88295 82.0017 7.88295C82.9935 7.88295 83.8445 8.307 84.3281 9.2092L86.736 7.99546C85.8278 6.28968 84.0927 5.3063 82.0017 5.3063C79.3759 5.3063 77.2908 6.85756 77.2908 9.32847C77.2908 12.0882 79.6722 12.7772 81.6419 13.3472C83.0309 13.7491 84.2151 14.0918 84.2151 15.0595C84.2151 16.1109 83.263 16.5314 82.0272 16.5314C80.7871 16.5314 79.8441 15.987 79.3518 15.0573L76.8913 16.2979C77.7635 18.0491 79.5641 19.1339 82.0272 19.1339C84.8071 19.1339 87.047 17.7144 87.047 15.0854C87.047 12.2271 84.6545 11.5482 82.682 10.9885C81.2987 10.596 80.1219 10.2621 80.1219 9.27613Z" fill="currentColor"/>
+<path d="M92.7347 7.88295C91.7303 7.88295 90.855 8.32978 90.855 9.27613C90.855 10.2621 92.0317 10.596 93.4151 10.9885C95.3875 11.5482 97.78 12.2271 97.78 15.0854C97.78 17.7144 95.5401 19.1339 92.7602 19.1339C90.2972 19.1339 88.4965 18.0491 87.6243 16.2979L90.0848 15.0573C90.5771 15.987 91.5201 16.5314 92.7602 16.5314C93.996 16.5314 94.9481 16.1109 94.9481 15.0595C94.9481 14.0918 93.7639 13.7491 92.3749 13.3472C90.4052 12.7772 88.0238 12.0882 88.0238 9.32847C88.0238 6.85756 90.1089 5.3063 92.7347 5.3063C94.8257 5.3063 96.5608 6.28968 97.469 7.99546L95.0611 9.2092C94.5775 8.307 93.7265 7.88295 92.7347 7.88295Z" fill="currentColor"/>
+</svg>
diff --git a/apps/web/src/features/onboarding/assets/design-casa.svg b/apps/web/src/features/onboarding/assets/design-casa.svg
new file mode 100644
index 0000000000..005804755c
--- /dev/null
+++ b/apps/web/src/features/onboarding/assets/design-casa.svg
@@ -0,0 +1,33 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 64 64"
+ fill="none"
+ display="block"
+>
+ <path
+ d="M32 4.5C24.2 10.8 15.9 13 8 13.4v15.1C8 45.2 18.4 55.4 32 60.5 45.6 55.4 56 45.2 56 28.5V13.4C48.1 13 39.8 10.8 32 4.5Z"
+ stroke="currentColor"
+ stroke-width="2.7"
+ stroke-linejoin="round"
+ />
+ <text
+ x="32"
+ y="32.5"
+ fill="currentColor"
+ font-family="Arial, Helvetica, sans-serif"
+ font-size="12.5"
+ font-weight="800"
+ letter-spacing="1"
+ text-anchor="middle"
+ >CASA</text>
+ <text
+ x="32"
+ y="45"
+ fill="currentColor"
+ font-family="Arial, Helvetica, sans-serif"
+ font-size="8.4"
+ font-weight="800"
+ letter-spacing="0.65"
+ text-anchor="middle"
+ >TIER 2</text>
+</svg>
diff --git a/apps/web/src/features/onboarding/assets/design-iso.svg b/apps/web/src/features/onboarding/assets/design-iso.svg
new file mode 100644
index 0000000000..0a09d042c4
--- /dev/null
+++ b/apps/web/src/features/onboarding/assets/design-iso.svg
@@ -0,0 +1,16 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 64 64"
+ fill="currentColor"
+ display="block"
+>
+ <path d="m17.709 44.335c0-1.7615 0.65588-2.7758 2.6532-3.8205 0.99397-0.52314 1.3524-0.8097 1.3524-1.4242 0-0.60434-0.39977-1.0346-1.1782-1.0346-0.83 0-1.3211 0.48098-1.4343 1.3625l-1.3727-0.08198c0.14367-1.5163 1.1478-2.4385 2.807-2.4385 1.6085 0 2.5509 0.88153 2.5509 2.1722 0 1.1166-0.52314 1.6389-1.9466 2.3971-1.2087 0.64495-1.7927 1.2594-1.8333 1.71h3.7791v1.1579z"/>
+ <path d="m25.659 44.253c0-2.2534 0.93228-4.3944 2.3971-6.1153h-3.9228v-1.1579h5.3056v1.0853c-1.6389 1.8443-2.4275 3.6472-2.4275 6.1879z"/>
+ <path d="m32.875 36.816c-1.8646 0-3.0333 1.4639-3.0333 3.8095 0 2.3362 1.1687 3.7912 3.0333 3.7912 1.8638 0 3.0211-1.455 3.0211-3.7912 0-2.3455-1.1573-3.8095-3.0211-3.8095zm0 1.156c1.065 0 1.6485 0.93262 1.6485 2.6535 0 1.7209-0.58352 2.6337-1.6485 2.6337-1.0658 0-1.6501-0.9128-1.6501-2.6337 0-1.7209 0.58426-2.6535 1.6501-2.6535z"/>
+ <path d="m40.012 36.816c-1.8646 0-3.0317 1.4639-3.0317 3.8095 0 2.3362 1.1672 3.7912 3.0317 3.7912 1.8646 0 3.0211-1.455 3.0211-3.7912 0-2.3455-1.1565-3.8095-3.0211-3.8095zm0 1.156c1.0658 0 1.6485 0.93262 1.6485 2.6535 0 1.7209-0.58274 2.6337-1.6485 2.6337-1.065 0-1.6501-0.9128-1.6501-2.6337 0-1.7209 0.58504-2.6535 1.6501-2.6535z"/>
+ <path d="m44.959 44.253v-4.9894h-1.5569v-1.0135h0.62465c0.87138 0 1.2095-0.30764 1.2095-1.2704h1.0549v7.2732z"/>
+ <path d="m18.905 32.998v2.0809h-8.9004v-2.0816c0.27562 0 0.54344 0.0055 0.80814-0.0016 0.18583 0 0.37166-0.01562 0.55672-0.04685a0.60122 0.60122 0 0 0 0.53876-0.53095 4.7083 4.7083 0 0 0 0.07886-0.65354c0.0055-2.8164 0.0055-5.6359 0-8.4522-0.0016-0.99709-0.23893-1.2243-1.236-1.2415-0.2358-0.0031-0.47317 0-0.74645 0v-2.0707h8.8387c0.11712 0.67228 0.12649 1.3602 0.02967 2.0363-0.12337 0.01249-0.25298 0.02733-0.38416 0.03592-0.13196 0.0086-0.27172 0-0.40836 0.0039-0.90808 0.03201-1.1236 0.22643-1.1236 1.1228-0.0078 2.8859-0.0078 5.7709 0 8.656 0.0039 0.92604 0.22019 1.1251 1.1509 1.1423 0.25298 0.0039 0.50362 0 0.7972 0z"/>
+ <path d="m31.964 25.107c-0.1015-0.27797-0.17802-0.50206-0.26001-0.72381-0.55594-1.4952-1.6764-2.2565-3.2232-2.4228a4.3147 4.3147 0 0 0-1.767 0.09604 2.1628 2.1628 0 0 0-0.98538 0.60591c-0.55125 0.60903-0.49191 1.2961 0.20848 1.7225a5.1158 5.1158 0 0 0 1.3063 0.54344c0.96274 0.26391 1.9481 0.45521 2.914 0.71522 1.1244 0.27094 2.1956 0.71834 3.1794 1.3266a3.8751 3.8751 0 0 1 1.8193 3.0233 4.5708 4.5708 0 0 1-0.97601 3.5253 5.1721 5.1721 0 0 1-2.2932 1.5507c-1.1915 0.40134-2.4533 0.56218-3.7081 0.47083a11.142 11.142 0 0 1-4.2546-1.0994c-0.05778-0.02733-0.12259-0.04451-0.22175-0.07808l-0.56687 0.79642h-2.0012v-5.5328a4.7543 4.7543 0 0 1 1.0447-0.04294c0.33809-0.0078 0.67618-0.0016 1.0572-0.0016 0.07027 0.18271 0.13118 0.35371 0.20145 0.5208 0.69648 1.6592 1.8661 2.7711 3.6706 3.1178a3.6932 3.6932 0 0 0 1.8154-0.03904 2.725 2.725 0 0 0 0.89402-0.45599 1.1533 1.1533 0 0 0-0.0016-1.8786 5.272 5.272 0 0 0-1.4304-0.74723c-0.99159-0.34508-2.0144-0.59806-3.0154-0.91741a20.336 20.336 0 0 1-2.0551-0.7402c-1.2758-0.56687-2.2097-1.489-2.4931-2.8905-0.45287-2.2386 0.48878-4.1851 2.5407-5.2673a6.8289 6.8289 0 0 1 2.832-0.73942 11.061 11.061 0 0 1 5.4485 0.98694c0.0609 0.02889 0.12649 0.04997 0.23736 0.09214l0.41461-0.69336h2.1066v5.165c-0.3904 0.0031-0.79018 0.01015-1.1884 0.01171-0.40914 0.0016-0.81594 0-1.2493 0z"/>
+ <path d="m45.102 19.505a11.591 11.591 0 0 0-4.1053 0.75793 6.8649 6.8649 0 0 0-4.2014 4.5445 9.7445 9.7445 0 0 0-0.26535 4.2319c0.45053 3.1037 2.2205 5.0957 5.1759 6.0436a11.464 11.464 0 0 0 4.2228 0.45598c1.2227-0.04451 2.4286-0.29442 3.5655-0.74573a6.8867 6.8867 0 0 0 3.6158-3.2788 8.7919 8.7919 0 0 0 0.88451-3.9406h-0.0016c-0.04685-0.53954-0.06906-1.0832-0.14793-1.6196a6.9414 6.9414 0 0 0-4.2471-5.6182c-0.98382-0.4232-2.0322-0.67695-3.1004-0.74878a11.591 11.591 0 0 0-1.3954-0.08235zm0.1281 2.2768a2.3245 2.3245 0 0 1 2.1579 1.278 6.1692 6.1692 0 0 1 0.64966 2.3363c0.08042 0.72225 0.10413 1.4524 0.15098 2.1777v0.0016c0 1.0869-0.11432 2.1688-0.34465 3.2315a5.3407 5.3407 0 0 1-0.36295 1.0553 2.5353 2.5353 0 0 1-4.6162-0.09913c-0.28499-0.67075-0.45924-1.3868-0.51545-2.1137a18.017 18.017 0 0 1 0.0854-4.7641 5.4133 5.4133 0 0 1 0.57798-1.8315 2.3674 2.3674 0 0 1 2.2174-1.2719z"/>
+ <path d="m32 0c-7.5289 0-14.442 2.6246-19.91 6.9844-0.6521 0.51988-1.2736 1.0723-1.8828 1.6406-6.2642 5.8434-10.207 14.143-10.207 23.375s3.9428 17.532 10.207 23.375c0.6092 0.56828 1.2307 1.1207 1.8828 1.6406 5.4685 4.3597 12.381 6.9844 19.91 6.9844-0.30965-0.001146-0.61544-0.021522-0.91797-0.056641 0.31298 0.036373 0.62862 0.056641 0.94922 0.056641 0.29994-2.9e-4 0.59071-0.03836 0.88867-0.04687 7.1693-0.2048 13.747-2.7576 18.99-6.9375 0.6521-0.51988 1.2736-1.0723 1.8828-1.6406 6.2642-5.8434 10.207-14.143 10.207-23.375s-3.9428-17.532-10.207-23.375c-0.6092-0.56828-1.2307-1.1207-1.8828-1.6406-5.243-4.1799-11.821-6.7327-18.99-6.9375-0.29797-0.0085116-0.58873-0.046585-0.88867-0.046875-0.010501 0-0.020757-3.8818e-5 -0.03125 0zm0.03125 2.5c0.0084 0 0.01696 0.00191 0.02539 0.00195 3.2894 0.01504 6.601 2.9601 9.1191 8.2891 0.32231 0.68208 0.62887 1.4017 0.91992 2.1523-3.1532 1.1485-6.5425 1.8066-10.096 1.8066-3.5321 0-6.9016-0.65166-10.039-1.7871 0.29323-0.75733 0.60082-1.4842 0.92578-2.1719 2.5221-5.3373 5.8403-8.2832 9.1348-8.2891 0.0033-5.8e-6 0.0065-0.00195 0.0098-0.00195zm-7.1484 0.89844c-1.6232 1.6484-3.0618 3.7933-4.2578 6.3242-0.34588 0.73196-0.67265 1.4978-0.98242 2.293-1.9997-0.92379-3.8748-2.0626-5.6016-3.3906 3.1679-2.4363 6.8402-4.2353 10.842-5.2266zm14.314 0.021484c3.9704 0.99545 7.6151 2.7852 10.762 5.2051-1.7115 1.3162-3.569 2.4458-5.5488 3.3652-0.30701-0.78648-0.63223-1.543-0.97461-2.2676-1.191-2.5203-2.624-4.6568-4.2383-6.3027zm-27.107 6.8457c2.0487 1.6333 4.304 3.011 6.7168 4.1074-0.37175 1.1574-0.70182 2.3726-0.99805 3.627h2.5859c0.22978-0.92247 0.47309-1.8261 0.74414-2.6855 3.3968 1.2298 7.0429 1.9355 10.861 1.9355 3.8395 0 7.5054-0.71231 10.918-1.9551 0.27332 0.86552 0.51863 1.7755 0.75 2.7051h2.584c-0.2983-1.2631-0.631-2.4856-1.0059-3.6504 2.393-1.0926 4.6303-2.4626 6.6641-4.084 5.8827 5.3909 9.5898 13.116 9.5898 21.734s-3.7072 16.344-9.5898 21.734c-2.0338-1.6214-4.2711-2.9914-6.6641-4.084 0.37486-1.1648 0.70756-2.3873 1.0059-3.6504h-2.584c-0.23137 0.92957-0.47668 1.8396-0.75 2.7051-3.4126-1.2428-7.0784-1.9551-10.918-1.9551-3.8184 0-7.4645 0.7058-10.861 1.9355-0.27105-0.85944-0.51436-1.7631-0.74414-2.6855h-2.5859c0.29623 1.2544 0.6263 2.4695 0.99805 3.627-2.4128 1.0964-4.6681 2.4741-6.7168 4.1074-5.8827-5.3909-9.5898-13.116-9.5898-21.734s3.7072-16.344 9.5898-21.734zm19.91 38.984c3.5532 0 6.9425 0.65818 10.096 1.8066-0.29105 0.75063-0.59761 1.4703-0.91992 2.1523-2.5182 5.3289-5.8297 8.274-9.1191 8.2891-0.0084 3.8e-5 -0.01696 2e-3 -0.02539 2e-3 -0.0033 0-0.0065-0.0019-0.0098-2e-3 -3.2945-0.0059-6.6127-2.9518-9.1348-8.2891-0.32489-0.68767-0.63252-1.4145-0.92575-2.1719 3.1375-1.1354 6.507-1.7871 10.039-1.7871zm-12.357 2.7344c0.30977 0.79514 0.63654 1.561 0.98242 2.293 1.196 2.5309 2.6347 4.6758 4.2578 6.3242-4.0016-0.99123-7.6739-2.7903-10.842-5.2266 1.7268-1.328 3.6019-2.4668 5.6016-3.3906zm24.768 0.02539c1.9798 0.91942 3.8374 2.049 5.5488 3.3652-3.1466 2.4199-6.7913 4.2096-10.762 5.2051 1.6143-1.6459 3.0473-3.7824 4.2383-6.3027 0.34238-0.72455 0.6676-1.4811 0.97461-2.2676z"/>
+</svg>
diff --git a/apps/web/src/features/onboarding/assets/design-soc2.svg b/apps/web/src/features/onboarding/assets/design-soc2.svg
new file mode 100644
index 0000000000..ad1607b07a
--- /dev/null
+++ b/apps/web/src/features/onboarding/assets/design-soc2.svg
@@ -0,0 +1,17 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 64 64"
+ fill="currentColor"
+ display="block"
+>
+ <path d="m20 43.129c0.13995 1.7271 1.3884 2.8817 3.4534 2.8817 1.8671 0 3.1036-0.94464 3.1036-2.4619 0-1.2373-0.74667-2.0531-2.9747-2.5318-1.4703-0.33792-1.8671-0.59478-1.8671-1.2715 0-0.64171 0.53675-1.0854 1.4234-1.0854 1.0385 0 1.6333 0.61867 1.7382 1.5172l1.5283-0.06997c-0.17493-1.5983-1.2715-2.7537-3.2427-2.7537-1.8671 0-2.9867 1.0035-2.9867 2.4499 0 1.3534 0.76885 1.9371 2.8228 2.4038 1.6913 0.3968 2.0181 0.78165 2.0181 1.4234 0 0.71168-0.57173 1.0735-1.5394 1.0735-1.1554 0-1.7852-0.59477-1.9371-1.6683z"/>
+ <path d="m31.846 37.353c-2.4619 0-3.9551 1.6689-3.9551 4.3398 0 2.6718 1.4932 4.3184 3.9551 4.3184 2.473 0 3.9551-1.6466 3.9551-4.3184 0-2.6718-1.4821-4.3398-3.9551-4.3398zm-2e-3 1.3184c1.4933 0 2.3809 1.1314 2.3809 3.0215s-0.88557 3-2.3789 3c-1.4933 0-2.3809-1.1099-2.3809-3s0.88557-3.0215 2.3789-3.0215z"/>
+ <path d="m36.497 41.694c0 2.7068 1.5872 4.3179 3.8383 4.3179 2.1001 0 3.3365-1.1904 3.6642-3.1394l-1.5872-0.08192c-0.18688 1.1904-0.83968 1.9029-2.0651 1.9029-1.3773 0-2.275-1.1324-2.275-2.9995 0-1.8432 0.87467-3.0217 2.2869-3.0217 1.1435 0 1.8082 0.6656 2.0062 1.7493l1.5872-0.08107c-0.34987-1.8782-1.4822-2.9867-3.5934-2.9867-2.3339 0-3.8622 1.6802-3.8622 4.3401z"/>
+ <path d="m17.804 17.988-2.9863 8.2832h1.5859l0.68945-1.959h3.2773l0.6875 1.959h1.5879l-2.9863-8.2832zm0.93359 1.5293 1.1895 3.5h-2.3926v-2e-3z"/>
+ <path d="m23.424 17.988v8.2833h1.5164v-8.2833z"/>
+ <path d="m30.131 26.646c-2.2519 0-3.8383-1.6102-3.8383-4.317 0-2.6598 1.5283-4.3401 3.8622-4.3401 2.1111 0 3.2427 1.1085 3.5925 2.9867l-1.5863 0.08192c-0.19797-1.0854-0.86272-1.7502-2.0062-1.7502-1.4123 0-2.2869 1.1776-2.2869 3.0217 0 1.8671 0.89771 2.9986 2.275 2.9986 1.2245 0 1.8782-0.71168 2.0651-1.9021l1.5872 0.08192c-0.32683 1.9482-1.5642 3.1386-3.6642 3.1386z"/>
+ <path d="m34.899 17.988v8.2832h1.5156v-2.9863h1.6934c1.9371 0 3.0918-1.0038 3.0918-2.6602 0-1.6452-1.1547-2.6367-3.0918-2.6367zm1.5176 1.3184h1.6211c1.0385 0 1.5977 0.45479 1.5977 1.3184 0 0.88661-0.5711 1.3418-1.5977 1.3418h-1.6211z"/>
+ <path d="m44.341 17.988-2.9863 8.2832h1.5859l0.68945-1.959h3.2793l0.6875 1.959h1.5859l-2.9863-8.2832zm0.93359 1.5293 1.1895 3.5h-2.3906v-2e-3z"/>
+ <path d="m32 0c-17.673 0-32 14.327-32 32s14.327 32 32 32 32-14.327 32-32-14.327-32-32-32zm0 2.5605c16.259 0 29.439 13.18 29.439 29.439s-13.18 29.439-29.439 29.439-29.439-13.18-29.439-29.439 13.18-29.439 29.439-29.439z"/>
+ <path d="m12 30.75v2.5h40v-2.5z"/>
+</svg>
diff --git a/apps/web/src/features/onboarding/assets/roboto-slab-variable.woff2 b/apps/web/src/features/onboarding/assets/roboto-slab-variable.woff2
new file mode 100644
index 0000000000..53cd54e61d
Binary files /dev/null and b/apps/web/src/features/onboarding/assets/roboto-slab-variable.woff2 differ
diff --git a/apps/web/src/features/onboarding/browser-test/.gitignore b/apps/web/src/features/onboarding/browser-test/.gitignore
new file mode 100644
index 0000000000..6419da1a8e
--- /dev/null
+++ b/apps/web/src/features/onboarding/browser-test/.gitignore
@@ -0,0 +1,3 @@
+.vite/
+.dist/
+test-results/
diff --git a/apps/web/src/features/onboarding/browser-test/README.md b/apps/web/src/features/onboarding/browser-test/README.md
new file mode 100644
index 0000000000..fe5aec15c5
--- /dev/null
+++ b/apps/web/src/features/onboarding/browser-test/README.md
@@ -0,0 +1,30 @@
+# Onboarding browser tests
+
+The fixture mounts the real onboarding views under `OnboardingProvider` with the
+fake backend from `tests/fake-onboarding-context.ts`. No module is aliased or
+mocked, and nothing touches the network: the only difference from production is
+the context the provider receives.
+
+The fake world is persisted in sessionStorage, so the full-page round-trips are
+real page loads. Google sign-up and the inbox OAuth reload into the flow, and
+checkout returns on Stripe's success or cancel leg. Leaving onboarding renders
+a `landed` marker showing where the app would have navigated.
+
+Run the suite from `apps/web` (the config starts or reuses the fixture server).
+Add `--ui` to watch and step through each test, or `--headed` to see the browser:
+
+```sh
+bunx playwright test --config src/features/onboarding/browser-test/playwright.config.ts
+```
+
+To click through by hand, start the fixture and open `http://127.0.0.1:3021/`:
+
+```sh
+bunx vite --config src/features/onboarding/browser-test/vite.config.ts
+```
+
+- `/?view=signup` shows the signed-out slides; Google sign-up continues into the flow.
+- `/?view=flow&next=/channel/x` shows the signed-in flow with a deep link.
+
+Tests seed the world through `openFixture` in `fixture-page.ts`. They read the
+world and the recorded analytics through `window.onboardingFixture`.
diff --git a/apps/web/src/features/onboarding/browser-test/fixture-keys.ts b/apps/web/src/features/onboarding/browser-test/fixture-keys.ts
new file mode 100644
index 0000000000..9fd99f3109
--- /dev/null
+++ b/apps/web/src/features/onboarding/browser-test/fixture-keys.ts
@@ -0,0 +1,15 @@
+/** sessionStorage keys shared by the fixture page and its Playwright tests. */
+export const FIXTURE_KEYS = {
+ /** Partial world merged over the defaults on the first load. */
+ seed: 'onboarding-fixture:seed',
+ /** The fake backend's current state, persisted across reloads. */
+ world: 'onboarding-fixture:world',
+ /** Where the flow handed the user off. */
+ landed: 'onboarding-fixture:landed',
+ /** Analytics recorded across page loads. */
+ events: 'onboarding-fixture:events',
+ /** `cancel` makes the fake Stripe return on the cancel leg. */
+ checkoutOutcome: 'onboarding-fixture:checkout-outcome',
+} as const;
+
+export type FixtureLanding = { t: 'app'; target: string } | { t: 'signed-out' };
diff --git a/apps/web/src/features/onboarding/browser-test/fixture-page.ts b/apps/web/src/features/onboarding/browser-test/fixture-page.ts
new file mode 100644
index 0000000000..a3c55f5bfe
--- /dev/null
+++ b/apps/web/src/features/onboarding/browser-test/fixture-page.ts
@@ -0,0 +1,43 @@
+import { expect, type Page } from '@playwright/test';
+import type { FakeOnboardingWorld } from '../tests/fake-onboarding-context';
+import { FIXTURE_KEYS } from './fixture-keys';
+
+/** Open the fixture with `seed` merged over the default fake world. */
+export async function openFixture(
+ page: Page,
+ path: string,
+ seed: Partial<FakeOnboardingWorld> & { checkoutOutcome?: 'cancel' } = {}
+) {
+ page.on('pageerror', (error) => {
+ throw error;
+ });
+ const { checkoutOutcome, ...world } = seed;
+ // Init scripts rerun on every load; only the first may seed, or reloads
+ // after OAuth/Stripe would reset the fake backend.
+ await page.addInitScript(
+ ([keys, world, outcome]) => {
+ if (sessionStorage.getItem(keys.seed) !== null) return;
+ sessionStorage.setItem(keys.seed, JSON.stringify(world));
+ if (outcome) sessionStorage.setItem(keys.checkoutOutcome, outcome);
+ },
+ [FIXTURE_KEYS, world, checkoutOutcome] as const
+ );
+ await page.goto(path);
+}
+
+export const fakeWorld = (page: Page) =>
+ page.evaluate(() => window.onboardingFixture.world());
+
+export const fakeEvents = (page: Page) =>
+ page.evaluate(() => window.onboardingFixture.events());
+
+export async function expectLanded(page: Page, text: string) {
+ await expect(page.getByTestId('landed')).toHaveText(text);
+}
+
+/** The visible swatch; its radio is visually hidden inside the label. */
+export const accentSwatch = (page: Page, name: string) =>
+ page.locator('label').filter({ has: page.getByRole('radio', { name }) });
+
+export const heading = (page: Page, name: string | RegExp) =>
+ page.getByRole('heading', { level: 1, name });
diff --git a/apps/web/src/features/onboarding/browser-test/fixture.tsx b/apps/web/src/features/onboarding/browser-test/fixture.tsx
new file mode 100644
index 0000000000..1274d7ddd9
--- /dev/null
+++ b/apps/web/src/features/onboarding/browser-test/fixture.tsx
@@ -0,0 +1,139 @@
+import '@fontsource-variable/inter';
+import '../../../index.css';
+import { createEffect, For, Match, Switch } from 'solid-js';
+import { unwrap } from 'solid-js/store';
+import { render } from 'solid-js/web';
+import { OnboardingProvider } from '../context/onboarding-context';
+import { parseCheckoutReturn } from '../core/checkout';
+import {
+ createFakeOnboarding,
+ defaultFakeWorld,
+ type FakeOnboardingWorld,
+} from '../tests/fake-onboarding-context';
+import { renderInviteOfferStub } from '../tests/invite-offer-stub';
+import { OnboardingFlowView } from '../views/onboarding-flow-view';
+import { SignupJourneyView } from '../views/signup-journey-view';
+import { FIXTURE_KEYS, type FixtureLanding } from './fixture-keys';
+
+/**
+ * The real onboarding views over a fake backend persisted in sessionStorage,
+ * so OAuth and Stripe round-trips are real page loads. Tests seed the world
+ * through `FIXTURE_KEYS.seed` before the first load.
+ */
+function loadWorld(): FakeOnboardingWorld {
+ const saved = sessionStorage.getItem(FIXTURE_KEYS.world);
+ if (saved) return JSON.parse(saved);
+ const seed = sessionStorage.getItem(FIXTURE_KEYS.seed);
+ return { ...defaultFakeWorld(), ...(seed ? JSON.parse(seed) : {}) };
+}
+const saveWorld = (world: FakeOnboardingWorld) =>
+ sessionStorage.setItem(FIXTURE_KEYS.world, JSON.stringify(world));
+const land = (landing: FixtureLanding) => {
+ sessionStorage.setItem(FIXTURE_KEYS.landed, JSON.stringify(landing));
+ location.assign(`${location.pathname}?view=landed`);
+};
+
+const params = Object.fromEntries(new URLSearchParams(location.search));
+const fake = createFakeOnboarding(loadWorld(), {
+ onChange: saveWorld,
+ // The inbox OAuth leaves the page and returns to bare /onboarding.
+ roundTrip: async (apply) => {
+ apply();
+ location.assign(`${location.pathname}?view=flow`);
+ await new Promise(() => {});
+ },
+ checkoutUrl: (tier) =>
+ sessionStorage.getItem(FIXTURE_KEYS.checkoutOutcome) === 'cancel'
+ ? `${location.pathname}?view=flow&subscriptionCancel=true`
+ : `${location.pathname}?view=flow&subscriptionSuccess=true&type=${tier}`,
+});
+saveWorld(structuredClone(unwrap(fake.world)));
+
+// Events outlive the page: the flow's last act is often a navigation.
+const earlierEvents = JSON.parse(
+ sessionStorage.getItem(FIXTURE_KEYS.events) ?? '[]'
+) as ReturnType<typeof fake.events>;
+const events = () => [...earlierEvents, ...fake.events()];
+createEffect(() =>
+ sessionStorage.setItem(FIXTURE_KEYS.events, JSON.stringify(events()))
+);
+
+/** Google sign-up creates the account and returns into onboarding. */
+const signUpWithGoogle = async () => {
+ fake.update((draft) => {
+ draft.viewer = defaultFakeWorld().viewer;
+ });
+ location.assign(`${location.pathname}?view=flow`);
+ await new Promise(() => {});
+};
+
+const landed = (): FixtureLanding | undefined => {
+ const raw = sessionStorage.getItem(FIXTURE_KEYS.landed);
+ return raw ? JSON.parse(raw) : undefined;
+};
+
+const landingText = (landing: FixtureLanding | undefined) =>
+ landing?.t === 'app' ? `Entered Macro at ${landing.target}` : 'Signed out';
+
+declare global {
+ interface Window {
+ onboardingFixture: {
+ world: () => FakeOnboardingWorld;
+ events: typeof events;
+ calls: typeof fake.calls;
+ notifications: typeof fake.notifications;
+ };
+ }
+}
+window.onboardingFixture = {
+ world: () => structuredClone(unwrap(fake.world)),
+ events,
+ calls: fake.calls,
+ notifications: fake.notifications,
+};
+
+function Fixture() {
+ return (
+ <OnboardingProvider value={fake.context}>
+ <Switch>
+ <Match when={params.view === 'landed'}>
+ <main data-testid="landed" class="p-8 text-ink">
+ {landingText(landed())}
+ </main>
+ </Match>
+ <Match when={params.view === 'signup'}>
+ <SignupJourneyView
+ onGoogle={signUpWithGoogle}
+ onBackFromEmail={() => {}}
+ showingEmail={false}
+ />
+ </Match>
+ <Match when={true}>
+ <OnboardingFlowView
+ next={params.next}
+ checkoutReturn={parseCheckoutReturn(params)}
+ onNavigate={(target) => land({ t: 'app', target })}
+ onRedirect={(url) => location.assign(url)}
+ onSignedOut={() => land({ t: 'signed-out' })}
+ renderInviteOffer={renderInviteOfferStub}
+ />
+ </Match>
+ </Switch>
+ <div
+ role="status"
+ aria-label="Notifications"
+ class="fixed top-4 left-1/2 z-[2000] -translate-x-1/2 text-sm text-ink"
+ >
+ <For each={fake.notifications()}>
+ {(message) => <p class="rounded bg-input px-3 py-2">{message}</p>}
+ </For>
+ </div>
+ <details class="fixed bottom-1 right-1 z-[2000] max-h-40 max-w-80 overflow-auto bg-surface text-xs text-ink">
+ <summary>Fake backend (no network)</summary>
+ <For each={events()}>{(item) => <p>{item.event}</p>}</For>
+ </details>
+ </OnboardingProvider>
+ );
+}
+
+render(() => <Fixture />, document.getElementById('root')!);
diff --git a/apps/web/src/features/onboarding/browser-test/index.html b/apps/web/src/features/onboarding/browser-test/index.html
new file mode 100644
index 0000000000..2f830f2df9
--- /dev/null
+++ b/apps/web/src/features/onboarding/browser-test/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en" data-modality="keyboard">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Onboarding fixture</title>
+ </head>
+ <body>
+ <div id="root" style="height: 100svh"></div>
+ <script type="module" src="/fixture.tsx"></script>
+ </body>
+</html>
diff --git a/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts b/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts
new file mode 100644
index 0000000000..e274922a24
--- /dev/null
+++ b/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts
@@ -0,0 +1,267 @@
+import { expect, test } from '@playwright/test';
+import {
+ accentSwatch,
+ expectLanded,
+ fakeEvents,
+ fakeWorld,
+ heading,
+ openFixture,
+} from './fixture-page';
+
+test('a new user signs up, connects everything, and starts the trial', async ({
+ page,
+}) => {
+ await openFixture(page, '/?view=signup', { viewer: null });
+
+ await expect(heading(page, 'Create your workspace')).toBeVisible();
+ await accentSwatch(page, 'Coral').click();
+ await expect(page.getByRole('radio', { name: 'Coral' })).toBeChecked();
+ await page.getByRole('button', { name: 'Get started' }).click();
+ await expect(
+ heading(page, 'Which features do you want to try first?')
+ ).toBeVisible();
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await expect(
+ heading(page, 'A workspace built to earn your trust.')
+ ).toBeVisible();
+ await page.getByRole('button', { name: 'Continue' }).click();
+
+ // Google sign-up leaves the page; the account exists when it returns.
+ await page.getByRole('button', { name: 'Connect work email' }).click();
+ await expect(heading(page, /Connect your work/)).toBeVisible();
+ expect((await fakeWorld(page)).accent).toBe('#f77d67');
+
+ // Inbox OAuth is a full-page round-trip back into the same step.
+ await page.getByRole('button', { name: 'Connect work email' }).click();
+ await expect(page.getByText('[email protected]')).toBeVisible();
+ await page.getByRole('button', { name: 'Continue' }).click();
+
+ await expect(heading(page, /Add your personal/)).toBeVisible();
+ await page.getByRole('button', { name: 'Skip for now' }).click();
+
+ await expect(heading(page, 'Connect your tools.')).toBeVisible();
+ await page.getByLabel('Search integrations and MCPs').fill('lin');
+ await expect(page.getByRole('button', { name: /Notion/ })).toHaveCount(0);
+ await page.getByRole('button', { name: 'Connect Linear' }).click();
+ await expect(
+ page.getByRole('button', { name: 'Connected to Linear' })
+ ).toBeVisible();
+ await page.getByRole('button', { name: 'Continue' }).click();
+
+ await expect(heading(page, 'Built for teams.')).toBeVisible();
+ await expect(page.locator('#team-name')).toHaveValue('Acme');
+ await expect(page.getByLabel('Teammate 1 email')).toHaveValue(
+ );
+ await page.getByRole('button', { name: 'Create team & invite 2' }).click();
+
+ await expect(heading(page, 'Free Claude & GPT for 30 days.')).toBeVisible();
+ await expect(page.getByRole('textbox')).toHaveCount(0);
+ await page.getByRole('button', { name: 'Start 30 day trial' }).click();
+
+ // Stripe returns on the success leg; the flow waits for the webhook's license.
+ await expectLanded(page, 'Entered Macro at /getting-started');
+ const world = await fakeWorld(page);
+ expect(world.viewer).toMatchObject({
+ tutorialComplete: true,
+ licensed: true,
+ });
+ expect(world.teams).toEqual([{ name: 'Acme' }]);
+ expect(world.connectedTools).toEqual(['linear']);
+});
+
+test('a deep link survives the inbox OAuth round-trip', async ({ page }) => {
+ await openFixture(page, '/?view=flow&next=/channel/launch');
+ await page.getByRole('button', { name: 'Get started' }).click();
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await page.getByRole('button', { name: 'Continue' }).click();
+
+ await page.getByRole('button', { name: 'Connect work email' }).click();
+ await expect(page.getByText('[email protected]')).toBeVisible();
+ expect(new URL(page.url()).searchParams.get('next')).toBeNull();
+
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await page.getByRole('button', { name: 'Skip for now' }).click();
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await page.getByRole('button', { name: 'Skip for now' }).click();
+ await page.getByRole('button', { name: 'Continue as Guest' }).last().click();
+
+ await expectLanded(page, 'Entered Macro at /channel/launch');
+});
+
+test('Guest continuation lives in the comparison below the trial offer', async ({
+ page,
+}) => {
+ await openFixture(page, '/?view=flow&next=/md/notes');
+ await page.evaluate(() => {
+ sessionStorage.setItem(
+ 'onboarding-flow-step',
+ JSON.stringify({ user: 'macro|[email protected]', step: 'plan' })
+ );
+ });
+ await page.reload();
+
+ await page.getByRole('button', { name: 'Continue as Guest' }).first().click();
+ await expect(
+ page.getByRole('heading', { name: 'Choose what works for you.' })
+ ).toBeInViewport();
+ await expect(page.getByRole('table')).toContainText('Haiku');
+ await page.getByRole('button', { name: 'Continue as Guest' }).last().click();
+
+ await expectLanded(page, 'Entered Macro at /md/notes');
+ expect(await fakeEvents(page)).toContainEqual({
+ event: 'onboarding_v4_completed',
+ data: expect.objectContaining({ plan: 'free' }),
+ });
+});
+
+test('cancelling checkout returns to a retryable trial offer', async ({
+ page,
+}) => {
+ await openFixture(page, '/?view=flow', { checkoutOutcome: 'cancel' });
+ await page.evaluate(() => {
+ sessionStorage.setItem(
+ 'onboarding-flow-step',
+ JSON.stringify({ user: 'macro|[email protected]', step: 'plan' })
+ );
+ });
+ await page.reload();
+ await page.getByRole('button', { name: 'Start 30 day trial' }).click();
+
+ await expect(page).toHaveURL(/subscriptionCancel=true/);
+ await expect(
+ page.getByRole('button', { name: 'Start 30 day trial' })
+ ).toBeEnabled();
+ expect((await fakeWorld(page)).viewer?.tutorialComplete).toBe(false);
+});
+
+test('an ineligible trial explains itself instead of charging', async ({
+ page,
+}) => {
+ const message =
+ 'The 30-day trial is only available for your first Premium subscription';
+ await openFixture(page, '/?view=flow', { failures: { checkout: message } });
+ await page.evaluate(() => {
+ sessionStorage.setItem(
+ 'onboarding-flow-step',
+ JSON.stringify({ user: 'macro|[email protected]', step: 'plan' })
+ );
+ });
+ await page.reload();
+ await page.getByRole('button', { name: 'Start 30 day trial' }).click();
+
+ await expect(page.getByRole('status', { name: 'Notifications' })).toHaveText(
+ message
+ );
+ await expect(
+ page.getByRole('button', { name: 'Start 30 day trial' })
+ ).toBeEnabled();
+ await expect(page).not.toHaveURL(/subscription/);
+});
+
+test('an invite’s free months replace the trial and keep its promotion', async ({
+ page,
+}) => {
+ await openFixture(page, '/?view=flow', {
+ inviteOffer: {
+ firstName: 'Ada',
+ freeMonths: 3,
+ linkId: 'link-1',
+ promoCode: 'ADA3',
+ redeemedAt: '2026-10-01T00:00:00Z',
+ },
+ });
+ await page.evaluate(() => {
+ sessionStorage.setItem(
+ 'onboarding-flow-step',
+ JSON.stringify({ user: 'macro|[email protected]', step: 'plan' })
+ );
+ });
+ await page.reload();
+ await expect(
+ page.getByRole('button', { name: 'Start 30 day trial' })
+ ).toHaveCount(0);
+ await page.getByRole('button', { name: 'Claim your free months' }).click();
+ await expectLanded(page, 'Entered Macro at /getting-started');
+ expect((await fakeWorld(page)).viewer?.licensed).toBe(true);
+});
+
+test('an existing team member just confirms and moves on', async ({ page }) => {
+ await openFixture(page, '/?view=flow', { teams: [{ name: 'Acme' }] });
+ await page.evaluate(() => {
+ sessionStorage.setItem(
+ 'onboarding-flow-step',
+ JSON.stringify({ user: 'macro|[email protected]', step: 'team' })
+ );
+ });
+ await page.reload();
+ await expect(page.getByText("You're on Acme")).toBeVisible();
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await expect(heading(page, 'Free Claude & GPT for 30 days.')).toBeVisible();
+});
+
+test('staff can bypass onboarding from any step', async ({ page }) => {
+ await openFixture(page, '/?view=flow', {
+ viewer: {
+ id: 'macro|[email protected]',
+ email: '[email protected]',
+ tutorialComplete: false,
+ licensed: false,
+ },
+ });
+ await expect(heading(page, 'Create your workspace')).toBeVisible();
+ await page.getByRole('button', { name: 'Bypass' }).click();
+ await expectLanded(page, 'Entered Macro at /home');
+ expect((await fakeWorld(page)).record.status).toBe('completed');
+});
+
+test('a finished user is sent straight into the app', async ({ page }) => {
+ await openFixture(page, '/?view=flow&next=/md/doc', {
+ viewer: {
+ id: 'macro|[email protected]',
+ email: '[email protected]',
+ tutorialComplete: true,
+ licensed: false,
+ },
+ });
+ await expectLanded(page, 'Entered Macro at /md/doc');
+});
+
+test.describe('with motion', () => {
+ test.use({ contextOptions: { reducedMotion: 'no-preference' } });
+
+ test('the story handoffs finish and leave the next step interactive', async ({
+ page,
+ }) => {
+ await openFixture(page, '/?view=flow');
+ await page.getByRole('button', { name: 'Get started' }).click();
+ await expect(
+ heading(page, 'Which features do you want to try first?')
+ ).toBeVisible();
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await expect(
+ heading(page, 'A workspace built to earn your trust.')
+ ).toBeVisible();
+ await page.getByRole('button', { name: 'Continue' }).click();
+ await expect(
+ page.getByRole('button', { name: 'Connect work email' })
+ ).toBeEnabled();
+ await expect(page.locator('[inert]')).toHaveCount(0);
+ });
+});
+
+test.describe('on a phone-sized screen', () => {
+ test.use({ viewport: { width: 390, height: 780 }, hasTouch: true });
+
+ test('the steps fit without horizontal scrolling', async ({ page }) => {
+ await openFixture(page, '/?view=flow');
+ for (const next of ['Get started', 'Continue', 'Continue']) {
+ const overflow = await page.evaluate(
+ () => document.documentElement.scrollWidth - window.innerWidth
+ );
+ expect(overflow).toBeLessThanOrEqual(0);
+ await page.getByRole('button', { name: next }).click();
+ }
+ await expect(heading(page, /Connect your work/)).toBeVisible();
+ });
+});
diff --git a/apps/web/src/features/onboarding/browser-test/playwright.config.ts b/apps/web/src/features/onboarding/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..6f9afe88f3
--- /dev/null
+++ b/apps/web/src/features/onboarding/browser-test/playwright.config.ts
@@ -0,0 +1,42 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const port = Number(process.env.ONBOARDING_BROWSER_PORT ?? 3021);
+
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: `${directory}/test-results`,
+ timeout: 60_000,
+ fullyParallel: true,
+ forbidOnly: !!process.env.CI,
+ reporter: process.env.CI ? [['list'], ['github']] : 'line',
+ use: {
+ baseURL: `http://127.0.0.1:${port}`,
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ // The handoff motion is covered by one explicit full-motion test.
+ contextOptions: { reducedMotion: 'reduce' },
+ },
+ webServer: {
+ command: `bunx vite --config src/features/onboarding/browser-test/vite.config.ts --port ${port}`,
+ cwd: webDirectory,
+ url: `http://127.0.0.1:${port}`,
+ reuseExistingServer: !process.env.CI,
+ timeout: 120_000,
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: {
+ ...devices['Desktop Chrome'],
+ viewport: { width: 1280, height: 900 },
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ },
+ ],
+});
diff --git a/apps/web/src/features/onboarding/browser-test/vite.config.ts b/apps/web/src/features/onboarding/browser-test/vite.config.ts
new file mode 100644
index 0000000000..8b3dfd8d60
--- /dev/null
+++ b/apps/web/src/features/onboarding/browser-test/vite.config.ts
@@ -0,0 +1,31 @@
+import { fileURLToPath } from 'node:url';
+import tailwind from '@tailwindcss/vite';
+import { defineConfig } from 'vite';
+import solidPlugin from 'vite-plugin-solid';
+import solidSvg from 'vite-plugin-solid-svg';
+import tsconfigPaths from 'vite-tsconfig-paths';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const workspaceDirectory = fileURLToPath(
+ new URL('../../../../../../', import.meta.url)
+);
+
+/** The real onboarding views over the fake backend; no module is replaced. */
+export default defineConfig({
+ root: directory,
+ cacheDir: `${directory}/.vite`,
+ plugins: [
+ solidPlugin(),
+ solidSvg({ defaultAsComponent: true }),
+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),
+ tailwind(),
+ ],
+ resolve: { dedupe: ['solid-js'] },
+ server: {
+ host: '127.0.0.1',
+ port: 3021,
+ strictPort: true,
+ fs: { allow: [workspaceDirectory] },
+ },
+});
diff --git a/apps/web/src/features/onboarding/components/bypass-button.tsx b/apps/web/src/features/onboarding/components/bypass-button.tsx
new file mode 100644
index 0000000000..dfe1fc3bc2
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/bypass-button.tsx
@@ -0,0 +1,21 @@
+import { Button } from '@ui';
+
+/** Staff-only escape hatch, pinned to the corner over every step. */
+export function BypassButton(props: {
+ disabled: boolean;
+ onBypass: () => void;
+}) {
+ return (
+ <div class="absolute top-4 right-4 z-30">
+ <Button
+ variant="ghost"
+ size="sm"
+ class="text-ink-muted"
+ disabled={props.disabled}
+ onClick={() => props.onBypass()}
+ >
+ Bypass
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/controls.tsx b/apps/web/src/features/onboarding/components/controls.tsx
new file mode 100644
index 0000000000..f03ca2d80f
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/controls.tsx
@@ -0,0 +1,97 @@
+import ArrowRightIcon from '@phosphor/arrow-right.svg';
+import { onCleanup, onMount } from 'solid-js';
+
+export function FormInput(props: {
+ id: string;
+ type?: string;
+ placeholder?: string;
+ value: string;
+ autoFocus?: boolean;
+ label?: string;
+ invalid?: 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}
+ aria-label={props.label}
+ aria-invalid={props.invalid || undefined}
+ 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-2xl border border-edge bg-input text-sm text-ink placeholder:text-ink-placeholder focus:border-ink/40 focus:outline-none transition-colors"
+ />
+ );
+}
+
+/** A quiet inset frame, free of gradients. */
+export function NoiseBackground() {
+ return (
+ <div
+ aria-hidden="true"
+ class="pointer-events-none absolute inset-4 rounded-[32px] border border-ink/[0.04] sm:inset-6"
+ />
+ );
+}
+
+export function SkipButton(props: {
+ label?: string;
+ disabled?: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ class="self-center rounded-full border border-edge-muted bg-surface px-4 py-2 text-xs text-ink-muted focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ink disabled:opacity-40"
+ disabled={props.disabled}
+ onClick={props.onClick}
+ >
+ {props.label ?? 'Skip for now'}
+ </button>
+ );
+}
+
+export function ContinueButton(props: {
+ label?: string;
+ disabled?: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <div class="mt-6 flex shrink-0 justify-center pb-3">
+ <div class="flex justify-center">
+ <button
+ type="button"
+ aria-label={props.label ?? 'Continue'}
+ title={props.label ?? 'Continue'}
+ disabled={props.disabled}
+ onClick={props.onClick}
+ class="flex min-h-14 min-w-44 max-w-full items-center justify-center gap-4 rounded-full bg-ink px-7 py-3.5 text-base font-medium text-surface transition-opacity hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-8 focus-visible:outline-ink disabled:opacity-40"
+ >
+ <span>{props.label ?? 'Continue'}</span>
+ <ArrowRightIcon class="size-5 shrink-0" aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/feature-overview.css b/apps/web/src/features/onboarding/components/feature-overview.css
new file mode 100644
index 0000000000..9eaad54ef2
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/feature-overview.css
@@ -0,0 +1,155 @@
+.feature-overview {
+ width: min(780px, calc(100vw - 40px));
+ margin-left: calc((100% - min(780px, 100vw - 40px)) / 2);
+}
+.feature-flow {
+ position: relative;
+ width: 100%;
+ height: clamp(280px, 36vw, 370px);
+ isolation: isolate;
+}
+.feature-flow-core {
+ position: absolute;
+ left: 48%;
+ top: 46%;
+ transform: translate(-50%, -50%);
+ display: grid;
+ place-items: center;
+ width: 104px;
+ height: 104px;
+ border-radius: 50%;
+ color: var(--color-ink);
+
+}
+.feature-flow-core svg { width: 43px; height: 43px; }
+.feature-flow-node { position: absolute; transform: translate(-50%, -50%); display: flex; flex-direction: column; align-items: center; }
+.feature-flow-node > span { position: absolute; top: calc(100% + 12px); font-size: 13px; color: var(--color-ink-muted); white-space: nowrap; }
+.feature-flow-icon {
+ position: relative;
+ display: grid;
+ place-items: center;
+ width: 76px;
+ height: 76px;
+ border-radius: 50%;
+ color: var(--color-ink);
+}
+/* Share the homepage's translucent material in onboarding and during travel.
+ The halo is already soft, so no live backdrop filters are needed. */
+.feature-flow-icon,
+.feature-flow-core {
+ background: linear-gradient(145deg,
+ color-mix(in srgb, var(--color-ink) 10%, transparent),
+ color-mix(in srgb, var(--color-ink) 6%, transparent));
+ backdrop-filter: none;
+}
+.feature-flow-core {
+ background: color-mix(in srgb, var(--color-ink) 12%, transparent);
+}
+.feature-flow-icon svg { width: 27px; height: 27px; }
+@media (max-width: 639px) {
+ .feature-flow { height: 280px; }
+ .feature-flow-core { width: 66px; height: 66px; }
+ .feature-flow-core svg { width: 33px; height: 33px; }
+ .feature-flow-icon { width: 54px; height: 54px; }
+ .feature-flow-icon svg { width: 21px; height: 21px; }
+ .feature-flow-node > span { font-size: 11px; top: calc(100% + 9px); }
+}
+
+/* Halo centers share the exact node coordinates, independently of icon surfaces. */
+.feature-flow-light {
+ position: absolute;
+ inset: 0;
+ z-index: -1;
+ pointer-events: none;
+}
+.feature-flow-halo {
+ position: absolute;
+ width: clamp(200px, 48vw, 420px);
+ aspect-ratio: 1;
+ transform: translate(-50%, -50%);
+ border-radius: 50%;
+ background: radial-gradient(circle,
+ color-mix(in srgb, var(--halo-color) 11%, transparent) 0%,
+ color-mix(in srgb, var(--halo-color) 7%, transparent) 22%,
+ color-mix(in srgb, var(--halo-color) 3%, transparent) 45%,
+ transparent 72%);
+}
+.feature-flow-halo::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ border-radius: inherit;
+ opacity: 0.045;
+ mix-blend-mode: soft-light;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Cpath fill='%23888' filter='url(%23n)' d='M0 0h160v160H0z'/%3E%3C/svg%3E");
+ mask-image: radial-gradient(circle, black 5%, transparent 70%);
+}
+
+.feature-flow-texture {
+ position: absolute;
+ opacity: .5;
+ left: 50%;
+ top: 50%;
+ width: 150%;
+ height: 190%;
+ max-width: calc(100vw - 48px);
+ transform: translate(-50%, -50%);
+ z-index: -1;
+ pointer-events: none;
+}
+
+/* Onboarding uses the chosen workspace accent and keeps every bubble interactive. */
+.feature-overview .feature-flow-expanded { height: 380px; margin-top: 22px; }
+.feature-overview .feature-flow-core { left: 50%; top: 49%; width: 88px; height: 88px; }
+.feature-overview .feature-flow-icon { width: 54px; height: 54px; transition: background 180ms ease, box-shadow 180ms ease; }
+.feature-overview .feature-flow-node > span { top: calc(100% + 9px); font-size: 12px; }
+.feature-overview button.feature-flow-node { border: 0; padding: 0; background: transparent; border-radius: 50%; outline: none; }
+.feature-overview button.feature-flow-node:hover .feature-flow-icon,
+.feature-overview button.feature-flow-node[aria-pressed=true] .feature-flow-icon {
+ background: linear-gradient(145deg,
+ color-mix(in srgb, var(--feature-accent) 22%, transparent),
+ color-mix(in srgb, var(--feature-accent) 10%, transparent));
+ box-shadow: var(--glass-shadow), inset 0 0 0 1px color-mix(in srgb, var(--feature-accent) 60%, transparent);
+}
+.feature-overview button.feature-flow-node:focus-visible .feature-flow-icon { outline: 2px solid var(--feature-accent); outline-offset: 4px; }
+.feature-overview button.feature-flow-node[aria-pressed=true] > span { color: var(--feature-accent); }
+.feature-overview .feature-flow-check {
+ position: absolute;
+ right: -3px;
+ bottom: -3px;
+ display: grid;
+ place-items: center;
+ width: 20px;
+ height: 20px;
+ border: 2px solid var(--color-surface);
+ border-radius: 50%;
+ background: var(--feature-accent);
+ color: var(--color-surface);
+}
+.feature-overview .feature-flow-check svg { width: 12px; height: 12px; }
+.feature-overview-description { min-height: 24px; }
+.feature-overview .feature-flow-light { opacity: .28; }
+@media (min-width: 640px) and (max-height: 800px) {
+ [data-onboarding-hero]:has(.feature-overview) { padding-top: 76px; padding-bottom: 24px; }
+ .feature-overview .feature-flow-expanded { height: 320px; margin-top: 12px; margin-bottom: -32px; }
+ .feature-overview .feature-flow-icon { width: 48px; height: 48px; }
+ .feature-overview .feature-flow-node > span { font-size: 11px; line-height: 14px; top: calc(100% + 7px); }
+ .feature-overview header { margin-top: 8px; }
+ .feature-overview h1 { font-size: 30px; }
+ .feature-overview-description { margin-top: 16px; }
+}
+@media (max-width: 639px) {
+ .feature-overview { width: 100%; margin-left: 0; overflow-x: clip; overflow-clip-margin: 24px; }
+ .feature-overview .feature-flow-expanded { height: auto; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 18px 8px; margin-top: 0; }
+ .feature-overview .feature-flow-core { display: none; }
+ .feature-overview button.feature-flow-node { position: relative; left: auto !important; top: auto !important; transform: none; gap: 7px; border-radius: 8px; }
+ .feature-overview .feature-flow-icon { width: 44px; height: 44px; }
+ .feature-overview .feature-flow-node > span { position: static; font-size: 10px; line-height: 14px; white-space: normal; }
+ .feature-overview .feature-overview-description { min-height: 48px; }
+}
+@media (max-width: 359px) {
+ .feature-overview h1 { font-size: 26px; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .feature-overview .feature-flow-icon { transition: none; }
+}
diff --git a/apps/web/src/features/onboarding/components/feature-overview.tsx b/apps/web/src/features/onboarding/components/feature-overview.tsx
new file mode 100644
index 0000000000..96ca70ba27
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/feature-overview.tsx
@@ -0,0 +1,313 @@
+import Logo from '@icon/macro-logo.svg';
+import Sheet from '@icon/wide-spreadsheet.svg';
+import CRM from '@phosphor/buildings.svg';
+import Calendar from '@phosphor/calendar-blank.svg';
+import Chat from '@phosphor/chats-circle.svg';
+import Check from '@phosphor/check.svg';
+import Database from '@phosphor/database.svg';
+import Mail from '@phosphor/envelope.svg';
+import Doc from '@phosphor/file.svg';
+import Folder from '@phosphor/folder.svg';
+import Booking from '@phosphor/link.svg';
+import Task from '@phosphor/list-checks.svg';
+import Call from '@phosphor/phone-call.svg';
+import Recording from '@phosphor/record.svg';
+import Sparkle from '@phosphor/sparkle.svg';
+import Coding from '@phosphor/terminal-window.svg';
+import Diagram from '@phosphor/tree-structure.svg';
+import { makePersisted } from '@solid-primitives/storage';
+import { createSignal, createUniqueId, For, Show } from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+import { ContinueButton } from './controls';
+import { WorkspaceTexture } from './workspace-texture';
+import './feature-overview.css';
+
+// Matching connector names let StoryStage carry the actual welcome icons here.
+const features = [
+ {
+ label: 'Email',
+ color: 'var(--color-write)',
+ source: 'Google',
+ icon: Mail,
+ x: 11,
+ y: 45,
+ },
+ {
+ label: 'Chat',
+ color: 'var(--color-chat)',
+ source: 'Slack',
+ icon: Chat,
+ x: 26,
+ y: 19,
+ },
+ {
+ label: 'Sheets',
+ color: 'var(--color-success)',
+ source: 'Sheets',
+ icon: Sheet,
+ x: 48,
+ y: 6,
+ },
+ {
+ label: 'Docs',
+ color: 'var(--color-note)',
+ source: 'Notion',
+ icon: Doc,
+ x: 70,
+ y: 19,
+ },
+ {
+ label: 'Tasks',
+ color: 'var(--color-task)',
+ source: 'Linear',
+ icon: Task,
+ x: 85,
+ y: 46,
+ },
+ {
+ label: 'CRM',
+ color: 'var(--color-contact)',
+ source: 'HubSpot',
+ icon: CRM,
+ x: 75,
+ y: 78,
+ },
+ {
+ label: 'Agents',
+ color: 'var(--color-snippet)',
+ source: 'GitHub',
+ icon: Sparkle,
+ x: 48,
+ y: 88,
+ },
+ {
+ label: 'Calls',
+ color: 'var(--color-note)',
+ source: 'Zoom',
+ icon: Call,
+ x: 22,
+ y: 78,
+ },
+];
+
+// The public overview has room for the full workspace; onboarding stays compact.
+const expandedPositions = [
+ [12, 27],
+ [37, 27],
+ [63, 27],
+ [88, 27],
+ [92, 49],
+ [63, 71],
+ [88, 71],
+ [8, 49],
+];
+const expandedFeatures = [
+ ...features.map((feature, index) => ({
+ ...feature,
+ x: expandedPositions[index][0],
+ y: expandedPositions[index][1],
+ })),
+ {
+ label: 'Calendar',
+ source: 'Calendar',
+ icon: Calendar,
+ color: 'var(--color-note)',
+ x: 26,
+ y: 5,
+ },
+ {
+ label: 'Booking links',
+ source: 'Booking',
+ icon: Booking,
+ color: 'var(--color-chat)',
+ x: 50,
+ y: 5,
+ },
+ {
+ label: 'Recordings',
+ source: 'Recordings',
+ icon: Recording,
+ color: 'var(--color-write)',
+ x: 74,
+ y: 5,
+ },
+ {
+ label: 'File storage',
+ source: 'Storage',
+ icon: Folder,
+ color: 'var(--color-note)',
+ x: 12,
+ y: 71,
+ },
+ {
+ label: 'Databases',
+ source: 'Databases',
+ icon: Database,
+ color: 'var(--color-success)',
+ x: 37,
+ y: 71,
+ },
+ {
+ label: 'Diagrams',
+ source: 'Diagrams',
+ icon: Diagram,
+ color: 'var(--color-contact)',
+ x: 29,
+ y: 49,
+ },
+ {
+ label: 'Coding agents',
+ source: 'Coding',
+ icon: Coding,
+ color: 'var(--color-task)',
+ x: 71,
+ y: 49,
+ },
+];
+
+/** The workspace constellation shared by onboarding and the public homepage. */
+function FeatureConstellation(
+ props: {
+ expanded?: boolean;
+ textured?: boolean;
+ accent?: string;
+ selected?: readonly string[];
+ onSelect?: (label: string) => void;
+ } = {}
+) {
+ const noiseId = createUniqueId();
+ const items = () => (props.expanded ? expandedFeatures : features);
+ return (
+ <div
+ class="feature-flow"
+ classList={{ 'feature-flow-expanded': props.expanded }}
+ role={props.onSelect ? 'group' : 'img'}
+ aria-label={
+ props.onSelect
+ ? 'Features to try first'
+ : `${items()
+ .map((feature) => feature.label)
+ .join(', ')}, connected in Macro`
+ }
+ >
+ <div class="feature-flow-light" aria-hidden="true">
+ <For each={items()}>
+ {(feature) => (
+ <div
+ class="feature-flow-halo"
+ style={{
+ left: `${feature.x}%`,
+ top: `${feature.y}%`,
+ '--halo-color': props.accent ?? feature.color,
+ }}
+ />
+ )}
+ </For>
+ </div>
+ <Show when={props.textured}>
+ <div class="feature-flow-texture" aria-hidden="true">
+ <WorkspaceTexture
+ accent={props.accent ?? 'var(--color-ink)'}
+ filterId={noiseId}
+ />
+ </div>
+ </Show>
+ <div class="feature-flow-core glass" aria-hidden="true">
+ <Logo />
+ </div>
+ <For each={items()}>
+ {(feature) => (
+ <Dynamic
+ component={props.onSelect ? 'button' : 'div'}
+ type={props.onSelect ? 'button' : undefined}
+ aria-label={props.onSelect ? feature.label : undefined}
+ aria-pressed={
+ props.onSelect
+ ? (props.selected?.includes(feature.label) ?? false)
+ : undefined
+ }
+ onClick={() => props.onSelect?.(feature.label)}
+ class="feature-flow-node"
+ data-tool-tile={feature.source}
+ style={{
+ left: `${feature.x}%`,
+ top: `${feature.y}%`,
+ }}
+ aria-hidden={props.onSelect ? undefined : true}
+ >
+ <div class="feature-flow-icon glass" data-tool-surface>
+ <Dynamic component={feature.icon} />
+ <Show
+ when={props.onSelect && props.selected?.includes(feature.label)}
+ >
+ <span class="feature-flow-check" aria-hidden="true">
+ <Check />
+ </span>
+ </Show>
+ </div>
+ <span>{feature.label}</span>
+ </Dynamic>
+ )}
+ </For>
+ </div>
+ );
+}
+
+export function FeatureOverview(props: {
+ /** The workspace accent picked on the first slide. */
+ accent: string;
+ onContinue: (features: string[]) => void;
+}) {
+ // Keep the user's starting interests through Back and Google redirects.
+ const [selected, setSelected] = makePersisted(createSignal<string[]>([]), {
+ name: 'macro:onboarding-features',
+ storage: sessionStorage,
+ deserialize: (value) => {
+ try {
+ const saved: unknown = JSON.parse(value);
+ return Array.isArray(saved)
+ ? expandedFeatures
+ .filter((feature) => saved.includes(feature.label))
+ .map((feature) => feature.label)
+ : [];
+ } catch {
+ return [];
+ }
+ },
+ });
+ return (
+ <section
+ class="feature-overview"
+ style={{ '--feature-accent': props.accent }}
+ >
+ <FeatureConstellation
+ textured
+ expanded
+ accent={props.accent}
+ selected={selected()}
+ onSelect={(label) =>
+ setSelected((current) =>
+ current.includes(label)
+ ? current.filter((item) => item !== label)
+ : [...current, label]
+ )
+ }
+ />
+ <header class="relative mx-auto mt-4 pb-6 text-center sm:mt-6">
+ <h1
+ tabindex="-1"
+ class="font-[Roboto_Slab_Variable] text-[30px] font-[315] leading-[1.2] tracking-[-.025em] outline-none [text-wrap:balance] sm:text-[36px]"
+ >
+ Which features do you want to try first?
+ </h1>
+ <div class="feature-overview-description mx-auto mt-5 max-w-lg text-sm leading-6 text-ink-muted sm:text-[15px]">
+ <p>Choose as many as you like. You can try the rest anytime.</p>
+ </div>
+ </header>
+ <ContinueButton
+ label="Continue"
+ onClick={() => props.onContinue([...selected()])}
+ />
+ </section>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/google-accounts-step.tsx b/apps/web/src/features/onboarding/components/google-accounts-step.tsx
new file mode 100644
index 0000000000..688af27107
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/google-accounts-step.tsx
@@ -0,0 +1,187 @@
+import GoogleIcon from '@icon/macro-google.svg';
+import CheckIcon from '@phosphor/check.svg';
+import HandIcon from '@phosphor/hand-palm.svg';
+import LockIcon from '@phosphor/lock-key.svg';
+import ShieldIcon from '@phosphor/shield-check.svg';
+import SpinnerIcon from '@phosphor/spinner-gap.svg';
+import { onCleanup, onMount, Show } from 'solid-js';
+import { ContinueButton } from './controls';
+import { animateOnboardingStep } from './motion/step-transition';
+
+export interface GoogleAccountsStepProps {
+ mode?: 'work' | 'personal';
+ accountEmail?: string;
+ workConnected?: boolean;
+ workNeedsReconnect?: boolean;
+ personalEmail?: string;
+ connecting?: 'work' | 'personal';
+ loading?: boolean;
+ disabled?: boolean;
+ error?: string;
+ onRetry?: () => void;
+ onConnectWork: () => void;
+ onConnectPersonal: () => void;
+ onContinue?: () => void;
+ onSkip?: () => void;
+}
+
+/** One decision per screen, with the reason for access explained before consent. */
+export function GoogleAccountsStep(props: GoogleAccountsStepProps) {
+ let root!: HTMLDivElement;
+ onMount(() => {
+ if (root.closest('[data-security-handoff]')) return;
+ const animation = animateOnboardingStep(root, 'in');
+ onCleanup(() => animation?.cancel());
+ });
+ const personal = () => props.mode === 'personal';
+ const connected = () =>
+ personal() ? !!props.personalEmail : !!props.workConnected;
+ const blocked = () =>
+ !!props.disabled || !!props.loading || !!props.connecting;
+ return (
+ <div
+ ref={root}
+ class="mx-auto flex w-full max-w-lg flex-col items-center py-2 text-center sm:py-4"
+ >
+ <header class="flex w-full flex-col items-center">
+ <h1
+ tabindex="-1"
+ class="font-[Roboto_Slab_Variable] text-[clamp(22px,6.6vw,30px)] font-[315] leading-[1.2] tracking-[-.025em] [text-wrap:balance] sm:text-[36px]"
+ >
+ {personal() ? 'Add your personal' : 'Connect your work'} <br />
+ Google email and calendar.
+ </h1>
+ <p class="mt-7 max-w-[440px] font-[Inter_Variable] text-sm font-normal leading-6 text-ink-muted sm:text-[15px] [text-wrap:balance]">
+ {personal()
+ ? 'Add a personal account for email and calendar in Macro. This is optional; your Macro sign-in stays the same. Agents ask for approval before sending email, and you can disconnect anytime.'
+ : 'Connect through Google to read, send, and organize email and manage your calendars in Macro. Agents ask for your approval before sending email. Your password stays with Google, and you can disconnect anytime.'}
+ </p>
+ </header>
+
+ <Show when={props.error}>
+ <p role="alert" class="mt-5 max-w-md text-sm leading-6 text-ink-muted">
+ {props.error}{' '}
+ <Show when={props.onRetry}>
+ <button
+ type="button"
+ onClick={props.onRetry}
+ class="rounded-sm text-ink underline underline-offset-4"
+ >
+ Try again
+ </button>
+ </Show>
+ </p>
+ </Show>
+
+ <div class="mt-7 flex w-full max-w-xs flex-col items-center gap-3">
+ <Show
+ when={connected()}
+ fallback={
+ <button
+ type="button"
+ disabled={blocked()}
+ onClick={() =>
+ personal() ? props.onConnectPersonal() : props.onConnectWork()
+ }
+ class="flex min-h-14 w-full items-center justify-center gap-3 rounded-full bg-ink px-6 py-4 text-base font-medium text-surface transition-opacity hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ink disabled:opacity-40"
+ >
+ <Show
+ when={!!props.connecting || props.loading}
+ fallback={
+ <GoogleIcon
+ viewBox="0 0 24 24"
+ class="size-5 shrink-0"
+ fill="currentColor"
+ stroke="none"
+ aria-hidden="true"
+ />
+ }
+ >
+ <SpinnerIcon class="size-5 animate-spin" />
+ </Show>
+ {props.loading
+ ? 'Checking connection…'
+ : props.connecting
+ ? 'Opening Google…'
+ : personal()
+ ? 'Connect personal email'
+ : props.workNeedsReconnect
+ ? 'Reconnect work email'
+ : 'Connect work email'}
+ </button>
+ }
+ >
+ <p
+ role="status"
+ class="flex max-w-full items-center gap-2 text-sm leading-6 text-ink-muted [overflow-wrap:anywhere]"
+ >
+ <CheckIcon class="size-4 shrink-0 text-ink" />
+ {personal() ? props.personalEmail : 'Work email connected'}
+ </p>
+ <Show when={props.onContinue}>
+ <ContinueButton
+ label={personal() ? 'Choose integrations' : 'Continue'}
+ disabled={blocked()}
+ onClick={() => props.onContinue?.()}
+ />
+ </Show>
+ </Show>
+ <Show when={!connected() && props.onSkip}>
+ <button
+ type="button"
+ disabled={!!props.connecting}
+ onClick={props.onSkip}
+ class="rounded-lg px-4 py-2 text-sm text-ink-muted hover:text-ink focus-visible:outline-2 focus-visible:outline-ink disabled:opacity-40"
+ >
+ Skip for now
+ </button>
+ </Show>
+ </div>
+
+ <Show when={!personal() && props.accountEmail}>
+ <p class="mt-3 max-w-sm text-xs leading-5 text-ink-extra-muted [overflow-wrap:anywhere]">
+ {props.accountEmail}
+ </p>
+ </Show>
+
+ <section
+ aria-label="Privacy assurances"
+ class="mt-9 grid w-full grid-cols-1 gap-6 border-t border-edge-muted pt-6 min-[360px]:grid-cols-3 min-[360px]:gap-3 sm:gap-6"
+ >
+ <div data-privacy-item class="flex min-w-0 flex-col items-center">
+ <LockIcon class="size-5 text-ink-muted" aria-hidden="true" />
+ <h2 class="mt-3 text-xs font-medium leading-5 text-ink">
+ Zero retention
+ </h2>
+ <p class="mt-1 text-[11px] leading-[1.6] text-ink-extra-muted sm:text-xs">
+ Agreements with
+ <br />
+ OpenAI &amp; Anthropic
+ </p>
+ </div>
+ <div data-privacy-item class="flex min-w-0 flex-col items-center">
+ <ShieldIcon class="size-5 text-ink-muted" aria-hidden="true" />
+ <h2 class="mt-3 text-xs font-medium leading-5 text-ink">
+ Audited security
+ </h2>
+ <p class="mt-1 text-[11px] leading-[1.6] text-ink-extra-muted sm:text-xs">
+ SOC 2 · ISO 27001
+ <br />
+ CASA Tier 2
+ </p>
+ </div>
+ <div data-privacy-item class="flex min-w-0 flex-col items-center">
+ <HandIcon class="size-5 text-ink-muted" aria-hidden="true" />
+ <h2 class="mt-3 text-xs font-medium leading-5 text-ink">
+ Never sold
+ </h2>
+ <p class="mt-1 text-[11px] leading-[1.6] text-ink-extra-muted sm:text-xs">
+ No generalized
+ <br />
+ AI model training.
+ </p>
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/macro-mark-icon.tsx b/apps/web/src/features/onboarding/components/macro-mark-icon.tsx
new file mode 100644
index 0000000000..7d04a14953
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/macro-mark-icon.tsx
@@ -0,0 +1,58 @@
+import type { JSX } from 'solid-js';
+
+const MACRO_MARK_PATHS = [
+ 'M0.121368 44.5707V94.6784L0.123097 94.8165C0.140592 95.5053 0.289921 96.1847 0.563153 96.8184C0.854625 97.4943 1.28114 98.1038 1.8166 98.6094L22.5065 118.144L37.6081 112.239V59.7876L15.2084 38.6654L0.121368 44.5707Z',
+ 'M30.89 6.04832V48.797L41.1458 58.4696V68.173L94.2982 118.349L109.4 112.444L109.392 59.9907L45.9767 0.140625L30.89 6.04832Z',
+ 'M102.685 6.04936V48.7977L112.948 58.4841L112.848 68.0867L166.111 118.35L181.197 112.445V62.3371C181.198 61.6013 181.047 60.8733 180.756 60.1975C180.465 59.5216 180.038 58.9121 179.503 58.4065L117.789 0.140625L102.685 6.04936Z',
+] as const;
+
+// The three strokes of the Macro mark — left, center, and right — split apart
+// horizontally when the header logo link is hovered.
+export function MacroMarkIcon(props: {
+ style?: JSX.CSSProperties;
+ class?: string;
+}) {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 182 119"
+ fill="currentColor"
+ aria-hidden="true"
+ class={props.class}
+ style={props.style}
+ >
+ <style>{`
+ .macro-mark-part {
+ transform-box: fill-box;
+ transition: transform 520ms cubic-bezier(0.22, 1, 0.36, 1);
+ }
+ .macro-mark-left { transform-origin: 85% 50%; }
+ .macro-mark-mid { transform-origin: center; }
+ .macro-mark-right { transform-origin: 15% 50%; }
+ @media (hover) {
+ .base-header-logo:hover .macro-mark-left {
+ transform: translateX(-11px) scale(1.06);
+ }
+ .base-header-logo:hover .macro-mark-mid {
+ transform: scale(1.1);
+ }
+ .base-header-logo:hover .macro-mark-right {
+ transform: translateX(11px) scale(1.06);
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .macro-mark-part { transition: none; }
+ }
+ `}</style>
+ <g class="macro-mark-part macro-mark-left">
+ <path d={MACRO_MARK_PATHS[0]} />
+ </g>
+ <g class="macro-mark-part macro-mark-mid">
+ <path d={MACRO_MARK_PATHS[1]} />
+ </g>
+ <g class="macro-mark-part macro-mark-right">
+ <path d={MACRO_MARK_PATHS[2]} />
+ </g>
+ </svg>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/motion/security-handoff.ts b/apps/web/src/features/onboarding/components/motion/security-handoff.ts
new file mode 100644
index 0000000000..0ea01473a6
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/motion/security-handoff.ts
@@ -0,0 +1,243 @@
+/** Fade the slide and carry its visual anchors downward into the next proof row. */
+export function animateSecurityHandoff(
+ content: HTMLElement,
+ commit: () => void,
+ from: 'intro' | 'features' | 'security' = 'security'
+) {
+ const sourceSelector =
+ from === 'intro'
+ ? '.workspace-intro-icon'
+ : from === 'features'
+ ? '[data-tool-surface]'
+ : '[data-security-item]';
+ const sources = Array.from(
+ content.querySelectorAll<HTMLElement>(sourceSelector)
+ );
+ const shell =
+ content.closest<HTMLElement>('.onboarding-flow') ??
+ (from === 'intro' ? document.body : null);
+ if (
+ !shell ||
+ (from === 'features'
+ ? sources.length === 0
+ : sources.length !== (from === 'intro' ? 1 : 3)) ||
+ typeof content.animate !== 'function' ||
+ typeof window.matchMedia !== 'function' ||
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ ) {
+ commit();
+ return () => {};
+ }
+
+ const bounds = content.getBoundingClientRect();
+ const sourceBounds = sources.map((source) => source.getBoundingClientRect());
+ const overlay = document.createElement('div');
+ overlay.className =
+ 'pointer-events-none fixed inset-0 z-[1000] font-sans text-ink';
+ overlay.dataset.securityTransition = '';
+ overlay.setAttribute('aria-hidden', 'true');
+ overlay.inert = true;
+
+ let cloneIndex = 0;
+ const cloneAt = (
+ source: HTMLElement,
+ rect: DOMRect,
+ freezeAppearance = false
+ ) => {
+ const clone = source.cloneNode(true) as HTMLElement;
+ if (freezeAppearance) {
+ // Moving a bubble outside .feature-overview loses its scoped dimensions,
+ // selected treatment, and checkmark styles. Freeze the small moving subtree
+ // before detaching it; the full-slide snapshot retains its CSS ancestry.
+ const originals = [source, ...source.querySelectorAll('*')];
+ const copies = [clone, ...clone.querySelectorAll('*')];
+ originals.forEach((element, index) => {
+ const copy = copies[index];
+ if (!(copy instanceof HTMLElement || copy instanceof SVGElement))
+ return;
+ const appearance = getComputedStyle(element);
+ for (const property of Array.from(appearance)) {
+ if (!property.startsWith('--'))
+ copy.style.setProperty(
+ property,
+ appearance.getPropertyValue(property)
+ );
+ }
+ copy.style.animation = 'none';
+ copy.style.transition = 'none';
+ });
+ }
+ clone.removeAttribute('id');
+ const ids = new Map<string, string>();
+ clone.querySelectorAll('[id]').forEach((node) => {
+ const id = node.id;
+ const replacement = `handoff-${cloneIndex++}-${id}`;
+ ids.set(id, replacement);
+ node.id = replacement;
+ });
+ // Keep cloned SVG texture filters local to the outgoing snapshot.
+ clone.querySelectorAll('*').forEach((node) => {
+ for (const attribute of Array.from(node.attributes)) {
+ let value = attribute.value;
+ for (const [id, replacement] of ids) {
+ value = value.replaceAll(`url(#${id})`, `url(#${replacement})`);
+ if (value === `#${id}`) value = `#${replacement}`;
+ }
+ if (value !== attribute.value) node.setAttribute(attribute.name, value);
+ }
+ });
+ const accent = getComputedStyle(source).getPropertyValue('--intro-accent');
+ if (accent) clone.style.setProperty('--intro-accent', accent);
+ Object.assign(clone.style, {
+ position: 'absolute',
+ left: `${rect.left}px`,
+ top: `${rect.top}px`,
+ width: `${rect.width}px`,
+ height: `${rect.height}px`,
+ boxSizing: 'border-box',
+ margin: '0',
+ animation: 'none',
+ });
+ overlay.append(clone);
+ return clone;
+ };
+ const snapshot = cloneAt(content, bounds);
+ snapshot.querySelectorAll<HTMLElement>(sourceSelector).forEach((item) => {
+ item.style.visibility = 'hidden';
+ });
+ const ghosts = sources.map((source, index) =>
+ cloneAt(source, sourceBounds[index], true)
+ );
+ shell.append(overlay);
+
+ const originalOpacity = content.style.opacity;
+ const originalInert = content.inert;
+ const originalBusy = content.getAttribute('aria-busy');
+ const scroller = content.closest('[data-onboarding-scroll]');
+ const animations: Animation[] = [];
+ let finished = false;
+ const finish = (focus: boolean) => {
+ if (finished) return;
+ finished = true;
+ animations.forEach((animation) => animation.cancel());
+ overlay.remove();
+ content.style.opacity = originalOpacity;
+ content.inert = originalInert;
+ if (originalBusy === null) content.removeAttribute('aria-busy');
+ else content.setAttribute('aria-busy', originalBusy);
+ delete content.dataset.securityHandoff;
+ window.removeEventListener('resize', settle);
+ scroller?.removeEventListener('scroll', settleScroll);
+ if (focus && content.isConnected)
+ content.querySelector<HTMLElement>('h1')?.focus({ preventScroll: true });
+ };
+ const settle = () => finish(true);
+ const settleScroll = () => finish(false);
+ content.dataset.securityHandoff = '';
+ content.style.opacity = '0';
+ content.inert = true;
+ content.setAttribute('aria-busy', 'true');
+ commit();
+
+ // The new view and its scroll reset must settle before measuring destinations.
+ queueMicrotask(() => {
+ if (finished) return;
+ const targets = Array.from(
+ content.querySelectorAll<HTMLElement>(
+ from === 'intro' && content.querySelector('.feature-flow-core')
+ ? '.feature-flow-node, .feature-flow-core'
+ : from !== 'security'
+ ? '[data-security-item]'
+ : '[data-privacy-item]'
+ )
+ );
+ if (
+ !content.isConnected ||
+ (from === 'intro' ? targets.length === 0 : targets.length !== 3)
+ ) {
+ finish(true);
+ return;
+ }
+ const targetBounds = targets.map((target) =>
+ target.getBoundingClientRect()
+ );
+ const animate = (
+ element: HTMLElement,
+ frames: Keyframe[],
+ duration: number,
+ delay = 0
+ ) => {
+ const animation = element.animate(frames, {
+ duration: duration * 1.5,
+ delay: delay * 1.5,
+ easing: 'cubic-bezier(.22,1,.36,1)',
+ fill: 'both',
+ });
+ animations.push(animation);
+ };
+
+ animate(snapshot, [{ opacity: 1 }, { opacity: 0 }], 200);
+ animate(content, [{ opacity: 0 }, { opacity: 1 }], 300, 180);
+ ghosts.forEach((ghost, index) => {
+ const source = sourceBounds[index];
+ const to = targetBounds[index % targetBounds.length];
+ const dx =
+ from === 'intro'
+ ? 0
+ : to.left + to.width / 2 - source.left - source.width / 2;
+ // The intro icon leaves downward; the proof row enters from above,
+ // preserving the same direction even though its final layout is higher.
+ const dy = from === 'intro' ? 96 : to.top - source.top;
+ animate(
+ ghost,
+ [
+ { transform: 'translate(0, 0)' },
+ { transform: `translate(${dx}px, ${dy}px)` },
+ ],
+ 680,
+ index * 25
+ );
+ animate(
+ ghost,
+ [
+ { opacity: 1, offset: 0 },
+ { opacity: 0.2, offset: 0.45 },
+ { opacity: 0, offset: 0.7 },
+ { opacity: 0, offset: 1 },
+ ],
+ 680,
+ index * 25
+ );
+ });
+ targets.forEach((target, index) => {
+ // Individual translate composes with each bubble's centering transform.
+ // Overriding transform makes it snap back by half its size on cleanup.
+ animate(
+ target,
+ [
+ { opacity: 0, translate: '0 -28px' },
+ { opacity: 1, translate: '0 0' },
+ ],
+ 380,
+ 280 + Math.min(index, 5) * 25
+ );
+ });
+ content.style.opacity = originalOpacity;
+ window.addEventListener('resize', settle, { once: true });
+ scroller?.addEventListener('scroll', settleScroll, {
+ once: true,
+ passive: true,
+ });
+ const complete = async () => {
+ try {
+ await Promise.all(animations.map((animation) => animation.finished));
+ settle();
+ } catch {
+ finish(false);
+ }
+ };
+ void complete();
+ });
+
+ return () => finish(false);
+}
diff --git a/apps/web/src/features/onboarding/components/motion/step-change.ts b/apps/web/src/features/onboarding/components/motion/step-change.ts
new file mode 100644
index 0000000000..382302ac97
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/motion/step-change.ts
@@ -0,0 +1,33 @@
+import { animateSecurityHandoff } from './security-handoff';
+import { transitionOnboardingStep } from './step-transition';
+
+/**
+ * Swap one step's content for the next, choosing the handoff that carries the
+ * story's visual anchors forward. Returns a cancel for an interrupted change.
+ */
+export function animateStepChange(
+ content: HTMLElement,
+ from: string,
+ to: string,
+ commit: () => void
+): () => void {
+ if (from === 'welcome' && to === 'vision')
+ return animateSecurityHandoff(content, commit, 'intro');
+ if (from === 'vision' && to === 'security')
+ return animateSecurityHandoff(content, commit, 'features');
+ if (from === 'security' && to === 'work')
+ return animateSecurityHandoff(content, commit);
+ return transitionOnboardingStep(content, commit);
+}
+
+/** After a swap: back to the top, focus on the new step's heading. */
+export function focusStepHeading(content: HTMLElement, smooth = false) {
+ content.closest('[data-onboarding-scroll]')?.scrollTo({
+ top: 0,
+ behavior:
+ smooth && !window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ ? 'smooth'
+ : 'instant',
+ });
+ content.querySelector('h1')?.focus({ preventScroll: true });
+}
diff --git a/apps/web/src/features/onboarding/components/motion/step-transition.ts b/apps/web/src/features/onboarding/components/motion/step-transition.ts
new file mode 100644
index 0000000000..10f0a7296f
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/motion/step-transition.ts
@@ -0,0 +1,53 @@
+/** Small compositor-only handoff, with no motion for reduced-motion users. */
+export function animateOnboardingStep(
+ element: HTMLElement,
+ direction: 'in' | 'out'
+) {
+ if (
+ typeof element.animate !== 'function' ||
+ typeof window.matchMedia !== 'function' ||
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ )
+ return;
+
+ return element.animate(
+ direction === 'in'
+ ? [
+ { opacity: 0, transform: 'translateY(6px)' },
+ { opacity: 1, transform: 'translateY(0)' },
+ ]
+ : [
+ { opacity: 1, transform: 'translateY(0)' },
+ { opacity: 0, transform: 'translateY(-6px)' },
+ ],
+ {
+ duration: direction === 'in' ? 260 : 160,
+ easing: 'cubic-bezier(.22,1,.36,1)',
+ fill: direction === 'in' ? 'none' : 'forwards',
+ }
+ );
+}
+
+/** Fade between account decisions without accepting duplicate actions mid-handoff. */
+export function transitionOnboardingStep(
+ element: HTMLElement,
+ commit: () => void
+) {
+ let cancelled = false;
+ let animation = animateOnboardingStep(element, 'out');
+ const finish = () => {
+ if (cancelled) return;
+ animation?.cancel();
+ commit();
+ animation = animateOnboardingStep(element, 'in');
+ element.inert = false;
+ };
+ element.inert = true;
+ if (animation) animation.onfinish = finish;
+ else finish();
+ return () => {
+ cancelled = true;
+ animation?.cancel();
+ element.inert = false;
+ };
+}
diff --git a/apps/web/src/features/onboarding/components/onboarding-shell.tsx b/apps/web/src/features/onboarding/components/onboarding-shell.tsx
new file mode 100644
index 0000000000..4d660ac9be
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/onboarding-shell.tsx
@@ -0,0 +1,141 @@
+import ArrowDownIcon from '@phosphor/arrow-down.svg';
+import ArrowLeftIcon from '@phosphor/arrow-left.svg';
+import { cn } from '@ui/utils/classname';
+import { children, createMemo, createUniqueId, type JSX, Show } from 'solid-js';
+import { NoiseBackground } from './controls';
+import './onboarding.css';
+
+export function OnboardingShell(props: {
+ wide?: boolean;
+ onBack?: () => void;
+ children: JSX.Element;
+ overlay?: JSX.Element;
+ heroFooter?: JSX.Element;
+ below?: JSX.Element;
+ explainer?: JSX.Element;
+ explainerLabel?: string;
+}) {
+ const detailsId = createUniqueId();
+ const explainer = createMemo(() => props.explainer);
+ const heroFooter = children(() => props.heroFooter);
+ let details!: HTMLDivElement;
+ return (
+ <div
+ class="onboarding-flow relative size-full overflow-hidden bg-surface font-sans text-ink"
+ style={{
+ '--color-surface': '#000',
+ '--color-ink': '#fff',
+ '--color-ink-muted': '#a8a8a8',
+ '--color-ink-extra-muted': '#737373',
+ '--color-edge': '#292929',
+ '--color-edge-muted': '#1c1c1c',
+ '--color-accent': 'var(--color-ink)',
+ '--color-accent-contrast': '#000',
+ '--color-accent-contrast-muted': '#292929',
+ '--color-input': '#171717',
+ '--color-ink-placeholder': '#737373',
+ '--glass-tint': '#fff',
+ '--glass-shade-color': '#000',
+ '--glass-highlight-base': '6%',
+ '--glass-rim-strong-base': '13.5%',
+ '--glass-rim-soft-base': '9%',
+ '--glass-rim-shade-base': '0%',
+ }}
+ >
+ <style>{
+ /*css*/ `
+ @keyframes obf-card-in {
+ from { opacity: 0; }
+ to { opacity: 1; }
+ }
+ .onboarding-flow:not([data-landing]) .obf-card { animation: obf-card-in 520ms cubic-bezier(0.22, 1, 0.36, 1) both; }
+
+ @keyframes ob-orbit-in { from { opacity: 0; transform: translate(-50%, -40%) scale(.8); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } }
+ .ob-orbit-tile { animation: ob-orbit-in 900ms cubic-bezier(.22,1,.36,1) both; }
+ @media (prefers-reduced-motion: reduce) {
+ .onboarding-flow *, .onboarding-flow *::before, .onboarding-flow *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
+ }
+ /* 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 />
+ <header class="absolute left-6 top-5 z-50 sm:left-10">
+ <Show when={props.onBack}>
+ <button
+ type="button"
+ aria-label="Back to previous step"
+ onClick={() => props.onBack?.()}
+ class="grid size-[68px] -ml-2.5 place-items-center rounded-full text-ink hover:bg-ink/5 focus-visible:outline-2 focus-visible:outline-ink"
+ >
+ <ArrowLeftIcon class="size-7" aria-hidden="true" />
+ </button>
+ </Show>
+ </header>
+
+ {/* Keep long connector catalogs and summaries inside the fixed frame. */}
+ <div
+ data-onboarding-scroll
+ role="main"
+ class="relative z-10 size-full overflow-x-hidden overflow-y-auto overscroll-contain"
+ >
+ <div
+ data-onboarding-hero
+ class={cn(
+ 'relative z-[3] flex min-h-full items-center justify-center px-6 pt-24',
+ explainer() ? 'pb-32' : heroFooter() ? 'pb-24' : 'pb-10'
+ )}
+ >
+ <div
+ class={cn(
+ 'w-full obf-card transition-[max-width] duration-300 md:[&:has(.ob-welcome)]:max-w-[720px]',
+ props.wide ? 'sm:max-w-xl' : 'sm:max-w-lg'
+ )}
+ >
+ {props.children}
+ </div>
+ {heroFooter()}
+ <Show when={explainer()}>
+ <button
+ type="button"
+ aria-controls={detailsId}
+ class="absolute bottom-[30px] left-1/2 flex -translate-x-1/2 flex-col items-center gap-2 rounded-lg px-4 py-1 text-xs leading-5 text-ink-extra-muted transition-colors hover:text-ink-muted focus-visible:outline-1 focus-visible:outline-offset-4 focus-visible:outline-ink-muted"
+ onClick={() => {
+ details
+ .querySelector<HTMLElement>('h2')
+ ?.focus({ preventScroll: true });
+ details.scrollIntoView({
+ block: 'start',
+ behavior: window.matchMedia(
+ '(prefers-reduced-motion: reduce)'
+ ).matches
+ ? 'instant'
+ : 'smooth',
+ });
+ }}
+ >
+ {props.explainerLabel ?? 'Read more'}
+ <ArrowDownIcon class="size-5" aria-hidden="true" />
+ </button>
+ </Show>
+ </div>
+ <Show when={explainer()}>
+ <div ref={details} id={detailsId} data-onboarding-details>
+ {explainer()}
+ </div>
+ </Show>
+ {props.below}
+ </div>
+ {props.overlay}
+ </div>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/onboarding.css b/apps/web/src/features/onboarding/components/onboarding.css
new file mode 100644
index 0000000000..0bb8f276a5
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/onboarding.css
@@ -0,0 +1,7 @@
+@font-face {
+ font-family: 'Roboto Slab Variable';
+ font-style: normal;
+ font-weight: 100 900;
+ font-display: swap;
+ src: url('../assets/roboto-slab-variable.woff2') format('woff2');
+}
diff --git a/apps/web/src/features/onboarding/components/plan-comparison.tsx b/apps/web/src/features/onboarding/components/plan-comparison.tsx
new file mode 100644
index 0000000000..954bb0dcd4
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/plan-comparison.tsx
@@ -0,0 +1,111 @@
+import { For } from 'solid-js';
+import { PLAN_COMPARISON } from '../core/plan-comparison';
+
+export function PlanComparison(props: {
+ disabled?: boolean;
+ onContinueGuest: () => void;
+ onBackToPro: () => void;
+}) {
+ return (
+ <section class="mx-auto w-full max-w-[608px] px-6 pb-20 pt-20 font-[Inter_Variable] text-sm leading-7 text-ink-muted sm:pb-28 sm:pt-24 sm:text-[15px]">
+ <div class="mb-10 h-px w-12 bg-edge" aria-hidden="true" />
+ <p class="mb-4 text-xs text-ink-extra-muted">Guest & Pro</p>
+ <h2
+ tabindex="-1"
+ class="mb-7 text-2xl font-medium leading-8 tracking-tight text-ink outline-none sm:text-[28px] sm:leading-9"
+ >
+ Choose what works for you.
+ </h2>
+ <p>
+ Join your workspace as a Guest for free, with no credit card needed.
+ Connect up to two email accounts, use Haiku, and keep up to 5 GB of
+ files. Emails you send include a “Sent with Macro” footer.
+ </p>
+ <p class="mt-5">
+ Pro removes the email watermark and account limit, unlocks every AI
+ model, and gives you more storage and team features.
+ </p>
+
+ <div class="mt-10">
+ <table class="w-full table-fixed border-collapse text-left text-xs leading-5 sm:text-sm sm:leading-6">
+ <caption class="sr-only">
+ Compare Guest access and Pro features
+ </caption>
+ <thead>
+ <tr class="border-b border-edge">
+ <th
+ scope="col"
+ class="w-[38%] pb-5 pr-3 align-top font-medium text-ink sm:pr-6"
+ >
+ What’s included
+ </th>
+ <th
+ scope="col"
+ class="w-[31%] pb-5 pr-3 align-top font-medium text-ink sm:pr-6"
+ >
+ Guest
+ <span class="mt-1.5 block text-xs font-normal leading-5 text-ink-muted">
+ Free
+ </span>
+ </th>
+ <th
+ scope="col"
+ class="w-[31%] pb-5 align-top font-medium text-ink"
+ >
+ Pro
+ <span class="mt-1.5 block text-xs font-normal leading-5 text-ink-muted [overflow-wrap:anywhere]">
+ 30 days free, then $40/user/month
+ </span>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <For each={PLAN_COMPARISON}>
+ {(row) => (
+ <tr class="border-b border-edge-muted last:border-b-0">
+ <th
+ scope="row"
+ class="py-4 pr-3 align-top font-normal text-ink-muted sm:py-5 sm:pr-6"
+ >
+ {row.feature}
+ </th>
+ <td class="py-4 pr-3 align-top text-ink-muted sm:py-5 sm:pr-6">
+ {row.guest}
+ </td>
+ <td class="py-4 align-top text-ink-muted sm:py-5">
+ {row.pro}
+ </td>
+ </tr>
+ )}
+ </For>
+ </tbody>
+ <tfoot>
+ <tr>
+ <td />
+ <td class="pt-6 pr-3 align-top sm:pr-6">
+ <button
+ type="button"
+ disabled={props.disabled}
+ onClick={props.onContinueGuest}
+ class="flex min-h-10 w-full max-w-40 items-center justify-center gap-2 rounded-full border border-edge px-2 py-2 text-center text-[11px] font-medium leading-4 text-ink-muted hover:border-ink-muted hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ink sm:px-3"
+ >
+ <span>Continue as Guest</span>
+ </button>
+ </td>
+ <td class="pt-6 align-top">
+ <button
+ type="button"
+ disabled={props.disabled}
+ onClick={props.onBackToPro}
+ class="flex min-h-10 w-full max-w-40 items-center justify-center gap-2 rounded-full bg-ink px-2 py-2 text-center text-[11px] font-medium leading-4 text-surface hover:bg-ink/90 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ink sm:px-3"
+ >
+ <span>Continue with Pro</span>
+ </button>
+ </td>
+ </tr>
+ </tfoot>
+ </table>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/story-stage.tsx b/apps/web/src/features/onboarding/components/story-stage.tsx
new file mode 100644
index 0000000000..7d34023fdf
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/story-stage.tsx
@@ -0,0 +1,289 @@
+import {
+ createEffect,
+ createSignal,
+ type JSX,
+ Match,
+ onCleanup,
+ Switch,
+ untrack,
+} from 'solid-js';
+import type { StoryStep } from '../core/steps';
+import type { WorkspaceAccent } from '../core/workspace-accent';
+import { animateSecurityHandoff } from './motion/security-handoff';
+import { SecurityStep, VisionStep } from './story-steps';
+import { WorkspaceIntro } from './workspace-intro';
+
+/** Owns the measured handoffs between the four opening story slides. */
+export function StoryStage(props: {
+ step: StoryStep;
+ accent: WorkspaceAccent;
+ githubStars: number | undefined;
+ onSelectAccent: (name: string) => void;
+ onNext: (features?: string[]) => void;
+ onWorkspaceContinue: (color: string) => void;
+ children: JSX.Element;
+ durationMs?: number;
+ welcomeAction?: JSX.Element;
+}) {
+ const [shown, setShown] = createSignal(untrack(() => props.step));
+ const [moving, setMoving] = createSignal(false);
+ let stage!: HTMLDivElement;
+ let disposeMotion: (() => void) | undefined;
+ onCleanup(() => disposeMotion?.());
+
+ const advance = (features?: string[]) => {
+ if (!moving() && !stage.closest('[inert], [data-security-handoff]'))
+ props.onNext(features);
+ };
+
+ const transitionTo = (next: StoryStep) => {
+ disposeMotion?.();
+ // The outer handoff snapshots the full slide before shell layout changes.
+ if (stage?.parentElement?.closest('[data-security-handoff]')) {
+ setShown(next);
+ return;
+ }
+ if (
+ !stage ||
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ ) {
+ setShown(next);
+ queueMicrotask(() => {
+ if (stage?.isConnected && shown() === next)
+ stage.querySelector('h1')?.focus({ preventScroll: true });
+ });
+ return;
+ }
+ if (shown() === 'welcome') {
+ disposeMotion = animateSecurityHandoff(
+ stage,
+ () => setShown(next),
+ 'intro'
+ );
+ return;
+ }
+ const bounds = stage.getBoundingClientRect();
+ const overlay = document.createElement('div');
+ overlay.className =
+ 'onboarding-flow pointer-events-none fixed inset-0 z-[1000] font-sans text-ink';
+ overlay.setAttribute('data-story-transition', '');
+ overlay.setAttribute('aria-hidden', 'true');
+ overlay.inert = true;
+ const snapshot = stage.cloneNode(true) as HTMLDivElement;
+ snapshot.querySelectorAll('[id]').forEach((el) => el.removeAttribute('id'));
+ Object.assign(snapshot.style, {
+ position: 'absolute',
+ left: `${bounds.left}px`,
+ top: `${bounds.top}px`,
+ width: `${bounds.width}px`,
+ height: `${bounds.height}px`,
+ });
+ overlay.append(snapshot);
+ // Keep the marketing palette when the app's saved theme is light.
+ (stage.closest('.onboarding-flow') ?? document.body).append(overlay);
+ const sources = Array.from(
+ stage.querySelectorAll<HTMLElement>(
+ '[data-constellation-tool], [data-tool-surface]'
+ )
+ );
+ const ghosts = sources.map((source) => {
+ const rect = source.getBoundingClientRect();
+ const appearance = getComputedStyle(source);
+ const ghost = source.cloneNode(true) as HTMLElement;
+ Object.assign(ghost.style, {
+ position: 'absolute',
+ left: `${rect.left}px`,
+ top: `${rect.top}px`,
+ width: `${rect.width}px`,
+ height: `${rect.height}px`,
+ animation: 'none',
+ transform: 'none',
+ margin: '0',
+ color: appearance.color,
+ background: appearance.background,
+ borderColor: appearance.borderColor,
+ boxShadow: appearance.boxShadow,
+ });
+ overlay.append(ghost);
+ return {
+ ghost,
+ rect,
+ name:
+ source.dataset.constellationTool ??
+ source.closest<HTMLElement>('[data-tool-tile]')?.dataset.toolTile,
+ };
+ });
+ snapshot
+ .querySelectorAll<HTMLElement>(
+ '[data-constellation-tool], [data-tool-surface]'
+ )
+ .forEach((node) => {
+ node.style.visibility = 'hidden';
+ });
+ const animations: Animation[] = [];
+ let cancelled = false;
+ const cleanup = () => {
+ cancelled = true;
+ animations.forEach((animation) => animation.cancel());
+ overlay.remove();
+ stage.style.removeProperty('opacity');
+ setMoving(false);
+ window.removeEventListener('resize', finish);
+ };
+ const finish = () => {
+ cleanup();
+ stage.querySelector('h1')?.focus({ preventScroll: true });
+ };
+ disposeMotion = cleanup;
+ setMoving(true);
+ setShown(next);
+ queueMicrotask(() => {
+ if (cancelled || !stage.isConnected) {
+ cleanup();
+ return;
+ }
+ const duration = props.durationMs ?? 1400;
+ const animate = (
+ element: Element,
+ frames: Keyframe[],
+ start = 0,
+ end = 1,
+ easing = 'cubic-bezier(.22,1,.36,1)'
+ ) => {
+ const animation = element.animate(frames, {
+ duration: duration * (end - start),
+ delay: duration * start,
+ easing,
+ fill: 'both',
+ });
+ animations.push(animation);
+ return animation;
+ };
+ const heading = stage.querySelector<HTMLElement>('h1');
+ heading?.setAttribute('tabindex', '-1');
+ if (heading) heading.style.outline = 'none';
+ animate(snapshot, [{ opacity: 1 }, { opacity: 0 }], 0, 0.34);
+ animate(stage, [{ opacity: 0 }, { opacity: 1 }], 0.28, 0.92);
+ if (heading)
+ animate(
+ heading,
+ [{ transform: 'translateY(18px)' }, { transform: 'translateY(0)' }],
+ 0.3,
+ 1
+ );
+ const targets = Array.from(
+ stage.querySelectorAll<HTMLElement>(
+ '[data-constellation-tool], [data-tool-surface]'
+ )
+ );
+ const security = stage
+ .querySelector('[data-security-scene]')
+ ?.getBoundingClientRect();
+ targets.forEach((target) => {
+ if (target.dataset.constellationTool) {
+ target.style.animation = 'none';
+ target.style.transform = 'translate(-50%, -50%)';
+ }
+ });
+ ghosts.forEach(({ ghost, rect, name }, index) => {
+ const target = targets.find(
+ (el) =>
+ (el.dataset.constellationTool ??
+ el.closest<HTMLElement>('[data-tool-tile]')?.dataset.toolTile) ===
+ name
+ );
+ if (target) {
+ const end = target.getBoundingClientRect();
+ animate(
+ ghost,
+ [
+ {
+ transform: 'translate(0,0)',
+ width: `${rect.width}px`,
+ height: `${rect.height}px`,
+ borderRadius: getComputedStyle(ghost).borderRadius,
+ },
+ {
+ transform: `translate(${end.left - rect.left}px,${end.top - rect.top}px)`,
+ width: `${end.width}px`,
+ height: `${end.height}px`,
+ borderRadius: getComputedStyle(target).borderRadius,
+ },
+ ],
+ (index % 3) * 0.025,
+ 0.9
+ );
+ animate(ghost, [{ opacity: 1 }, { opacity: 0 }], 0.76, 0.92);
+ animate(target, [{ opacity: 0 }, { opacity: 1 }], 0.76, 0.94);
+ } else if (security) {
+ animate(
+ ghost,
+ [
+ { transform: 'translate(0,0) scale(1)', opacity: 1 },
+ {
+ transform: `translate(${security.left + security.width / 2 - rect.left - rect.width / 2}px,${security.top + security.height / 2 - rect.top - rect.height / 2}px) scale(.25)`,
+ opacity: 0,
+ },
+ ],
+ 0,
+ 0.58
+ );
+ } else {
+ animate(ghost, [{ opacity: 1 }, { opacity: 0 }], 0, 0.34);
+ }
+ });
+ const clock = animate(overlay, [{ opacity: 1 }, { opacity: 1 }]);
+ const settle = async () => {
+ try {
+ await clock.finished;
+ if (!cancelled) finish();
+ } catch {
+ /* Navigation or unmount cancelled the handoff. */
+ }
+ };
+ void settle();
+ window.addEventListener('resize', finish, { once: true });
+ });
+ };
+
+ // A prop change drives an imperative DOM snapshot/animation, not derived state.
+ createEffect(() => {
+ const next = props.step;
+ if (next !== untrack(shown)) untrack(() => transitionTo(next));
+ });
+
+ return (
+ <div ref={stage} data-story-stage aria-busy={moving()} inert={moving()}>
+ <Switch>
+ <Match when={shown() === 'welcome'}>
+ <WorkspaceIntro
+ accent={props.accent}
+ onSelectAccent={props.onSelectAccent}
+ onContinue={props.onWorkspaceContinue}
+ action={props.welcomeAction}
+ />
+ </Match>
+ <Match when={shown() === 'vision'}>
+ <VisionStep accent={props.accent.color} onContinue={advance} />
+ </Match>
+ <Match when={shown() === 'tools'}>
+ <div class="flex flex-col gap-8">
+ <h1
+ tabindex="-1"
+ class="mx-auto max-w-lg text-center font-[Roboto_Slab_Variable] text-4xl font-[315] leading-[1.12] tracking-tight outline-none sm:text-5xl"
+ >
+ Connect your tools.
+ </h1>
+ <div>{props.children}</div>
+ </div>
+ </Match>
+ <Match when={shown() === 'security'}>
+ <SecurityStep
+ githubStars={props.githubStars}
+ onContinue={() => advance()}
+ />
+ </Match>
+ </Switch>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/story-steps.tsx b/apps/web/src/features/onboarding/components/story-steps.tsx
new file mode 100644
index 0000000000..ace5defcf1
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/story-steps.tsx
@@ -0,0 +1,101 @@
+import IconGithub from '@icon/mcp-github.svg';
+import { Show } from 'solid-js';
+import LogoA16z from '../assets/a16z.svg';
+import IconCasa from '../assets/design-casa.svg';
+import IconIso from '../assets/design-iso.svg';
+import IconSoc2 from '../assets/design-soc2.svg';
+import { ContinueButton } from './controls';
+import { FeatureOverview } from './feature-overview';
+
+export function VisionStep(props: {
+ accent: string;
+ onContinue: (features: string[]) => void;
+}) {
+ return (
+ <FeatureOverview accent={props.accent} onContinue={props.onContinue} />
+ );
+}
+
+export function SecurityStep(props: {
+ githubStars: number | undefined;
+ onContinue: () => void;
+}) {
+ const starCount = () => props.githubStars;
+ const formatStars = new Intl.NumberFormat('en-US', {
+ notation: 'compact',
+ maximumFractionDigits: 1,
+ });
+ return (
+ <div class="mx-auto flex w-full max-w-lg flex-col items-center py-2 text-center sm:py-4">
+ <section
+ data-security-scene
+ data-security-proof
+ aria-label="Built on trust"
+ class="grid w-full grid-cols-1 gap-6 border-b border-edge-muted pb-8 min-[360px]:grid-cols-3 min-[360px]:gap-3 sm:gap-6"
+ >
+ <a
+ data-security-item
+ href="https://github.com/macro-inc/macro"
+ target="_blank"
+ rel="noreferrer"
+ class="group flex min-w-0 flex-col items-center rounded-sm focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ink"
+ >
+ <span class="flex h-10 items-center justify-center gap-2 whitespace-nowrap text-ink-muted transition-colors group-hover:text-ink">
+ <IconGithub class="size-6 shrink-0" aria-hidden="true" />
+ <Show when={starCount() !== undefined}>
+ <svg
+ viewBox="0 0 256 256"
+ fill="currentColor"
+ aria-hidden="true"
+ class="size-4 shrink-0 text-orange"
+ >
+ <path d="M239.2,97.29a16,16,0,0,0-13.81-11L166,81.17,142.72,25.81h0a15.95,15.95,0,0,0-29.44,0L90.07,81.17,30.61,86.32a16,16,0,0,0-9.11,28.06L66.61,153.8,53.09,212.34a16,16,0,0,0,23.84,17.34l51-31,51.11,31a16,16,0,0,0,23.84-17.34l-13.51-58.6,45.1-39.36A16,16,0,0,0,239.2,97.29Z" />
+ </svg>
+ <span class="text-lg font-semibold leading-none tabular-nums">
+ {formatStars.format(starCount() ?? 0).toLowerCase()}
+ <span class="sr-only"> GitHub stars</span>
+ </span>
+ </Show>
+ </span>
+ <span class="mt-3 text-sm font-normal leading-6 text-ink-extra-muted">
+ Open source
+ </span>
+ </a>
+ <div data-security-item class="flex min-w-0 flex-col items-center">
+ <span class="flex h-10 w-full items-center justify-center text-ink-muted">
+ <LogoA16z
+ viewBox="0 0 169 40"
+ class="h-auto w-24 max-w-full sm:w-28"
+ aria-label="Andreessen Horowitz"
+ />
+ </span>
+ <span class="mt-3 text-sm font-normal leading-6 text-ink-extra-muted">
+ $30M+ raised
+ </span>
+ </div>
+ <div data-security-item class="flex min-w-0 flex-col items-center">
+ <div
+ class="flex h-10 items-center justify-center gap-1.5 text-ink-muted"
+ aria-label="Security certifications"
+ >
+ <IconIso class="size-6 sm:size-7" aria-label="ISO 27001" />
+ <IconSoc2 class="size-6 sm:size-7" aria-label="SOC 2" />
+ <IconCasa class="size-6 sm:size-7" aria-label="CASA Tier 2" />
+ </div>
+ <span class="mt-3 text-sm font-normal leading-6 text-ink-extra-muted">
+ Audited security
+ </span>
+ </div>
+ </section>
+ <h1 tabindex="-1" class="sr-only">
+ A workspace built to earn your trust.
+ </h1>
+ <p class="mb-6 mt-9 max-w-[440px] font-[Inter_Variable] text-sm font-normal leading-6 text-ink-muted sm:text-[15px] [text-wrap:balance]">
+ We don’t sell your data or train AI on it. Our agreements with OpenAI
+ and Anthropic ensure zero data retention. Review permissions and
+ disconnect anytime.
+ </p>
+ <ContinueButton label="Continue" onClick={props.onContinue} />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/team-panels.tsx b/apps/web/src/features/onboarding/components/team-panels.tsx
new file mode 100644
index 0000000000..4e514bc53b
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/team-panels.tsx
@@ -0,0 +1,77 @@
+import CheckIcon from '@phosphor/check.svg';
+import { Button } from '@ui';
+import { For } from 'solid-js';
+import type { TeamInvite } from '../context/onboarding-context';
+import { ContinueButton, SkipButton } from './controls';
+
+/** Already on a team — auto-joined by domain, or just created/joined here. */
+export 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-bg text-success">
+ <CheckIcon class="size-5" />
+ </span>
+ <p class="text-sm font-medium text-ink">You're on {props.name}</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. */
+export function InvitesPanel(props: {
+ invites: readonly TeamInvite[];
+ joining: boolean;
+ onJoin: (inviteId: string) => void;
+ onSkip: () => void;
+}) {
+ 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">
+ {invite.invitedBy} invited you to their team
+ </span>
+ <Button
+ variant="cta"
+ size="sm"
+ class="ml-auto shrink-0"
+ disabled={props.joining}
+ onClick={() => props.onJoin(invite.id)}
+ >
+ Join
+ </Button>
+ </div>
+ )}
+ </For>
+ <SkipButton onClick={props.onSkip} />
+ </div>
+ );
+}
+
+export function TeamStatus(props: { message: string }) {
+ return (
+ <p role="status" class="text-center text-sm text-ink-muted">
+ {props.message}
+ </p>
+ );
+}
+
+export function TeamLoadError(props: { onRetry: () => void }) {
+ return (
+ <p role="alert" class="text-center text-sm text-ink-muted">
+ Couldn't load your team.{' '}
+ <button type="button" class="underline" onClick={props.onRetry}>
+ Try again
+ </button>
+ </p>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/team-setup.tsx b/apps/web/src/features/onboarding/components/team-setup.tsx
new file mode 100644
index 0000000000..347cb1c6d6
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/team-setup.tsx
@@ -0,0 +1,114 @@
+import PlusIcon from '@phosphor/plus.svg';
+import XIcon from '@phosphor/x.svg';
+import { Index, type JSX, Show } from 'solid-js';
+import { isPlausibleEmail, PREFILL_CAP } from '../core/team';
+import { FormInput } from './controls';
+
+/** Shared presentation for the public preview and authenticated team setup. */
+export function TeamSetup(props: { children: JSX.Element }) {
+ return (
+ <section class="mx-auto flex w-full max-w-lg flex-col items-center py-2 sm:py-4">
+ <header class="flex w-full flex-col items-center text-center">
+ <h1
+ tabindex="-1"
+ class="whitespace-nowrap font-[Roboto_Slab_Variable] text-[clamp(1.75rem,8vw,3rem)] font-[315] leading-[1.12] tracking-tight outline-none"
+ >
+ Built for teams.
+ </h1>
+ <h2 class="mt-6 max-w-[440px] text-sm font-normal leading-6 text-ink-muted text-balance sm:text-[15px]">
+ Bring your team into one workspace. Choose Guest access or upgrade for
+ more AI and storage.
+ </h2>
+ </header>
+ <div class="mt-9 w-full">{props.children}</div>
+ </section>
+ );
+}
+
+export function TeamSetupFields(props: {
+ id: string;
+ name: string;
+ emails: string[];
+ disabled?: boolean;
+ suggested?: boolean;
+ onNameChange: (value: string) => void;
+ onEmailChange: (index: number, value: string) => void;
+ onRemoveEmail: (index: number) => void;
+ onAddEmail: () => void;
+ children?: JSX.Element;
+}) {
+ let inviteList!: HTMLDivElement;
+ return (
+ <fieldset
+ disabled={props.disabled}
+ class="flex min-w-0 flex-col gap-6 text-left"
+ >
+ <label class="flex flex-col gap-2.5 text-sm text-ink-muted">
+ Workspace name
+ <FormInput
+ id={`${props.id}-name`}
+ placeholder="Acme Inc."
+ value={props.name}
+ onInput={props.onNameChange}
+ />
+ </label>
+ <div class="flex flex-col gap-6 border-t border-edge-muted pt-6">
+ <Show when={props.suggested}>
+ <p class="-mt-2 text-sm leading-6 text-ink-muted">
+ We found a few people at your company. Review the addresses and
+ remove anyone you don’t want to invite.
+ </p>
+ </Show>
+ <div ref={inviteList} class="flex flex-col gap-3">
+ <Index each={props.emails}>
+ {(email, index) => (
+ <div class="relative [&_.obf-input]:pr-12">
+ <FormInput
+ id={`${props.id}-teammate-${index}`}
+ label={`Teammate ${index + 1} email`}
+ type="email"
+ placeholder="[email protected]"
+ value={email()}
+ invalid={!!email().trim() && !isPlausibleEmail(email())}
+ onInput={(value) => props.onEmailChange(index, value)}
+ />
+ <Show when={email().trim()}>
+ <button
+ type="button"
+ aria-label={`Don't invite ${email().trim()}`}
+ class="absolute top-1/2 right-2 flex size-8 -translate-y-1/2 items-center justify-center rounded-full text-ink-extra-muted hover:bg-ink/5 hover:text-ink focus-visible:outline-2 focus-visible:outline-ink"
+ onClick={() => props.onRemoveEmail(index)}
+ >
+ <XIcon class="size-4" aria-hidden="true" />
+ </button>
+ </Show>
+ </div>
+ )}
+ </Index>
+ </div>
+ <button
+ type="button"
+ class="-mt-3 flex self-center items-center gap-2 rounded-full px-3 py-2 text-sm text-ink-muted hover:text-ink focus-visible:outline-2 focus-visible:outline-ink disabled:opacity-40"
+ disabled={props.emails.length >= PREFILL_CAP + 1}
+ onClick={() => {
+ props.onAddEmail();
+ inviteList.lastElementChild
+ ?.querySelector('input')
+ ?.focus({ preventScroll: true });
+ inviteList.lastElementChild?.scrollIntoView({
+ block: 'nearest',
+ behavior: window.matchMedia('(prefers-reduced-motion: reduce)')
+ .matches
+ ? 'instant'
+ : 'smooth',
+ });
+ }}
+ >
+ <PlusIcon class="size-4" aria-hidden="true" />
+ Add another teammate
+ </button>
+ </div>
+ {props.children}
+ </fieldset>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/tool-tile.tsx b/apps/web/src/features/onboarding/components/tool-tile.tsx
new file mode 100644
index 0000000000..646efe0aa1
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/tool-tile.tsx
@@ -0,0 +1,67 @@
+import { PipedreamConnectorIcon } from '@core/pipedream/ConnectorIcon';
+import CheckIcon from '@phosphor/check.svg';
+import PlusIcon from '@phosphor/plus.svg';
+import SpinnerIcon from '@phosphor/spinner-gap.svg';
+import { Show } from 'solid-js';
+import type { Tool } from '../context/onboarding-context';
+
+export function ToolTile(props: {
+ tool: Tool;
+ connected: boolean;
+ busy: boolean;
+ disabled: boolean;
+ onConnect: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ aria-label={`${props.connected ? 'Connected to' : props.busy ? 'Connecting' : 'Connect'} ${props.tool.name}`}
+ aria-busy={props.busy}
+ disabled={props.disabled || props.busy || props.connected}
+ onClick={() => props.onConnect()}
+ class="group flex min-w-0 flex-col items-center gap-3 rounded-2xl p-2 text-center outline-none focus-visible:ring-2 focus-visible:ring-ink/50"
+ >
+ <span
+ class="relative flex size-20 items-center justify-center rounded-[22px] bg-ink/5 transition-colors group-hover:bg-ink/10"
+ classList={{
+ glass: !props.connected,
+ 'border-2 border-success': props.connected,
+ }}
+ >
+ <PipedreamConnectorIcon
+ appSlug={props.tool.slug}
+ iconUrl={props.tool.iconUrl}
+ class="size-7"
+ />
+ <span
+ class="absolute -right-1 -bottom-1 flex size-7 items-center justify-center rounded-full border shadow-sm"
+ classList={{
+ 'border-success bg-success text-ink ring-2 ring-surface':
+ props.connected,
+ 'border-edge bg-surface text-ink-muted': !props.connected,
+ }}
+ >
+ <Show
+ when={!props.busy}
+ fallback={<SpinnerIcon class="size-3.5 animate-spin" />}
+ >
+ <Show
+ when={props.connected}
+ fallback={<PlusIcon class="size-3.5" />}
+ >
+ <CheckIcon class="size-3.5" />
+ </Show>
+ </Show>
+ </span>
+ </span>
+ <span class="flex w-full flex-col gap-1">
+ <span class="w-full break-words text-xs font-medium">
+ {props.tool.name}
+ </span>
+ <span class="text-[11px] font-normal text-ink-extra-muted">
+ {props.connected ? 'Connected' : 'Integration'}
+ </span>
+ </span>
+ </button>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/trust-details.tsx b/apps/web/src/features/onboarding/components/trust-details.tsx
new file mode 100644
index 0000000000..bcc7a39a44
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/trust-details.tsx
@@ -0,0 +1,236 @@
+import ArrowUpIcon from '@phosphor/arrow-up.svg';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import { For, type JSX, Show } from 'solid-js';
+
+function EvidenceLink(props: { href: string; children: JSX.Element }) {
+ return (
+ <a
+ href={props.href}
+ target="_blank"
+ rel="noreferrer"
+ class="rounded-sm text-ink-muted underline decoration-ink-extra-muted underline-offset-4 hover:text-ink focus-visible:outline-1 focus-visible:outline-offset-4 focus-visible:outline-ink"
+ >
+ {props.children}
+ </a>
+ );
+}
+
+/** Optional reading, grounded in Macro's privacy policy, DPA, and security material. */
+export function OnboardingTrustDetails(props: {
+ topic: 'security' | 'google';
+}) {
+ const google = () => props.topic === 'google';
+ const questions = () =>
+ google()
+ ? [
+ {
+ title: 'Why does Google ask for these permissions?',
+ answer: (
+ <>
+ Gmail access lets Macro read, send, organize, and move messages
+ to trash. Contacts help suggest recipients; mail settings
+ support your signature and filters. When you connect Calendar,
+ its permissions let Macro show your calendars and create or
+ update events. Google shows the exact permissions before you
+ approve.
+ </>
+ ),
+ },
+ {
+ title: 'Does Macro get my Google password?',
+ answer: (
+ <>
+ No. You sign in and approve access on Google. Google gives Macro
+ authorization for the permissions you approve; your Google
+ password stays with Google.
+ </>
+ ),
+ },
+ {
+ title: 'Is my email used to train AI?',
+ answer: (
+ <>
+ Data received through Google Workspace APIs is not used to
+ develop or train generalized AI models. Macro also maintains
+ zero data retention agreements with OpenAI and Anthropic for
+ model processing.
+ </>
+ ),
+ },
+ {
+ title: 'How do I revoke access?',
+ answer: (
+ <>
+ You can disconnect in Macro’s Settings or revoke access from
+ your Google account. Revoking access and deleting data already
+ stored in Macro are separate actions. You can request account
+ and data deletion as described in our{' '}
+ <EvidenceLink href="https://macro.com/privacy/">
+ Privacy Policy
+ </EvidenceLink>
+ .
+ </>
+ ),
+ },
+ ]
+ : [
+ {
+ title: 'What does zero data retention mean?',
+ answer: (
+ <>
+ When you use an agent, information needed for your request is
+ processed by its model provider. Our agreements with OpenAI and
+ Anthropic provide zero data retention and no training on that
+ data. This concerns model processing: Macro still stores the
+ workspace content needed to provide the service.
+ </>
+ ),
+ },
+ {
+ title: 'Who can access production data?',
+ answer: (
+ <>
+ Production access is restricted to authorized engineering staff,
+ and development runs in a separate environment. Personnel who
+ process customer data are bound by confidentiality obligations.
+ </>
+ ),
+ },
+ {
+ title: 'Can my team review the security evidence?',
+ answer: (
+ <>
+ Yes. Our security program includes SOC 2, ISO 27001, and Google
+ CASA Tier 2, with external audits and penetration testing. Visit
+ our{' '}
+ <EvidenceLink href="https://security.macro.com">
+ Trust Center
+ </EvidenceLink>{' '}
+ for security information. Our{' '}
+ <EvidenceLink href="https://macro.com/dpa">
+ Data Processing Agreement
+ </EvidenceLink>{' '}
+ describes confidentiality, safeguards, subprocessors, and data
+ return or deletion.
+ </>
+ ),
+ },
+ {
+ title: 'Is Macro open source?',
+ answer: (
+ <>
+ Macro is open source: you can inspect our{' '}
+ <EvidenceLink href="https://github.com/macro-inc/macro">
+ code on GitHub
+ </EvidenceLink>
+ .
+ </>
+ ),
+ },
+ ];
+
+ return (
+ <section class="mx-auto w-full max-w-[608px] px-6 pb-20 pt-20 font-[Inter_Variable] text-sm leading-7 text-ink-muted sm:pb-28 sm:pt-24 sm:text-[15px]">
+ <div class="mb-10 h-px w-12 bg-edge" aria-hidden="true" />
+ <p class="mb-4 text-xs text-ink-extra-muted">
+ {google() ? 'Google account connection' : 'Security & privacy'}
+ </p>
+ <h2
+ tabindex="-1"
+ class="mb-7 text-2xl font-medium leading-8 tracking-tight text-ink outline-none sm:text-[28px] sm:leading-9"
+ >
+ {google() ? 'Email and calendar permissions' : 'Data protection'}
+ </h2>
+ <div class="space-y-5">
+ <Show
+ when={google()}
+ fallback={
+ <>
+ <p>
+ Macro stores your workspace content to provide the service. We
+ do not sell your data.
+ </p>
+ <p>
+ Your data is encrypted in transit and at rest. Production access
+ is restricted to authorized engineering staff. Development runs
+ in a separate environment.
+ </p>
+ <p>
+ Macro is open source. Our security program includes independent
+ audits and penetration testing. The FAQs below link to our code,
+ security information, and data policies.
+ </p>
+ </>
+ }
+ >
+ <p>
+ Macro requests Google account access to read, send, and organize
+ email and manage connected calendars. Google lists the permissions
+ before you approve the connection.
+ </p>
+ <p>
+ Macro’s email agents show you the draft and ask for your approval
+ before sending.
+ </p>
+ <p>
+ You sign in through Google. Macro does not receive your Google
+ password. Your Macro sign-in stays the same; adding a personal
+ account is optional. You can disconnect in Macro’s Settings or
+ revoke access from your Google account.
+ </p>
+ </Show>
+ </div>
+ <h3 class="mb-3 mt-12 text-base font-medium text-ink">
+ Frequently asked questions
+ </h3>
+ <div class="border-t border-edge-muted">
+ <For each={questions()}>
+ {(question) => (
+ <details class="group border-b border-edge-muted">
+ <summary class="flex list-none items-start justify-between gap-5 rounded-sm py-5 text-sm font-medium leading-6 text-ink-muted hover:text-ink focus-visible:outline-1 focus-visible:outline-offset-4 focus-visible:outline-ink [&::-webkit-details-marker]:hidden">
+ {question.title}
+ <CaretDownIcon
+ class="mt-1 size-4 shrink-0 text-ink-extra-muted transition-transform group-open:rotate-180 motion-reduce:transition-none"
+ aria-hidden="true"
+ />
+ </summary>
+ <p class="pb-6 pr-6 font-normal">{question.answer}</p>
+ </details>
+ )}
+ </For>
+ </div>
+ <p class="mt-8 text-xs leading-6 text-ink-extra-muted">
+ More detail in our{' '}
+ <EvidenceLink href="https://macro.com/privacy/">
+ Privacy Policy
+ </EvidenceLink>{' '}
+ and{' '}
+ <EvidenceLink href="https://security.macro.com">
+ Trust Center
+ </EvidenceLink>
+ .
+ </p>
+ <button
+ type="button"
+ class="mt-10 inline-flex items-center gap-2 rounded-sm py-2 text-sm text-ink-muted hover:text-ink focus-visible:outline-1 focus-visible:outline-offset-4 focus-visible:outline-ink"
+ onClick={(event) => {
+ const scroller = event.currentTarget.closest(
+ '[data-onboarding-scroll]'
+ );
+ scroller
+ ?.querySelector<HTMLElement>('h1')
+ ?.focus({ preventScroll: true });
+ scroller?.scrollTo({
+ top: 0,
+ behavior: window.matchMedia('(prefers-reduced-motion: reduce)')
+ .matches
+ ? 'instant'
+ : 'smooth',
+ });
+ }}
+ >
+ Back to setup <ArrowUpIcon class="size-4" aria-hidden="true" />
+ </button>
+ </section>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/workspace-intro.css b/apps/web/src/features/onboarding/components/workspace-intro.css
new file mode 100644
index 0000000000..33c790f8ae
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/workspace-intro.css
@@ -0,0 +1,18 @@
+.workspace-intro-icon:focus-visible .macro-mark-left { transform: translateX(-11px) scale(1.06); }
+.workspace-intro-icon:focus-visible .macro-mark-mid { transform: scale(1.1); }
+.workspace-intro-icon:focus-visible .macro-mark-right { transform: translateX(11px) scale(1.06); }
+@media (prefers-reduced-motion: reduce) {
+ .workspace-intro-icon .macro-mark-part { transform: none !important; }
+}
+
+@property --intro-accent {
+ syntax: '<color>';
+ inherits: true;
+ initial-value: #65d8ac;
+}
+[data-workspace-intro] {
+ transition: --intro-accent 220ms ease-out;
+}
+@media (prefers-reduced-motion: reduce) {
+ [data-workspace-intro] { transition: none; }
+}
diff --git a/apps/web/src/features/onboarding/components/workspace-intro.tsx b/apps/web/src/features/onboarding/components/workspace-intro.tsx
new file mode 100644
index 0000000000..0ca3c77a5f
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/workspace-intro.tsx
@@ -0,0 +1,165 @@
+import CheckIcon from '@phosphor/check.svg';
+import { createUniqueId, For, type JSX, onCleanup } from 'solid-js';
+import {
+ WORKSPACE_ACCENTS,
+ type WorkspaceAccent,
+} from '../core/workspace-accent';
+import { ContinueButton } from './controls';
+import { MacroMarkIcon } from './macro-mark-icon';
+import { WorkspaceTexture } from './workspace-texture';
+import './workspace-intro.css';
+
+/** An onboarding-only introduction; the public homepage keeps its own hero. */
+export function WorkspaceIntro(props: {
+ accent: WorkspaceAccent;
+ onSelectAccent: (name: string) => void;
+ onContinue: (color: string) => void;
+ action?: JSX.Element;
+}) {
+ const accent = () => props.accent;
+ const noiseId = createUniqueId();
+ let burst!: HTMLDivElement;
+ let burstAnimation: Animation | undefined;
+ const celebrateAccent = () => {
+ burstAnimation?.cancel();
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
+ burstAnimation = burst.animate(
+ [
+ { transform: 'scale(.12)', opacity: 0 },
+ { transform: 'scale(.5)', opacity: 0.24, offset: 0.2 },
+ { transform: 'scale(1)', opacity: 0.1, offset: 0.6 },
+ { transform: 'scale(1.2)', opacity: 0 },
+ ],
+ { duration: 1100, easing: 'cubic-bezier(.16,1,.3,1)' }
+ );
+ };
+ onCleanup(() => burstAnimation?.cancel());
+ const changeAccent = (color: string) => {
+ if (color === accent().name) return;
+ props.onSelectAccent(color);
+ celebrateAccent();
+ };
+ return (
+ <div
+ data-workspace-intro
+ class="isolate mx-auto flex w-full max-w-lg flex-col items-center py-2 text-center sm:py-4"
+ style={{ '--intro-accent': accent().color }}
+ >
+ <h1
+ tabindex="-1"
+ class="font-[Roboto_Slab_Variable] text-[30px] font-[315] leading-[1.2] tracking-[-.025em] outline-none [text-wrap:balance] sm:text-[36px]"
+ >
+ Create your workspace
+ </h1>
+ <p class="mt-6 max-w-[460px] font-[Inter_Variable] text-sm leading-6 text-ink-muted sm:text-[15px] [text-wrap:balance]">
+ Choose your workspace color. You’ll connect accounts and invite
+ teammates next.
+ </p>
+ <div
+ class="relative mt-8 flex h-40 w-full max-w-[400px] items-center justify-center sm:h-44"
+ aria-label={`${accent().name} workspace preview`}
+ >
+ <div
+ aria-hidden="true"
+ class="pointer-events-none absolute left-1/2 top-1/2 -z-10 h-[450%] w-[300%] max-w-[calc(100vw-48px)] -translate-x-1/2 -translate-y-1/2"
+ >
+ <div
+ aria-hidden="true"
+ class="absolute inset-0"
+ style={{
+ background:
+ 'radial-gradient(ellipse 50% 50% at center, color-mix(in srgb, var(--intro-accent) 20%, transparent) 0%, color-mix(in srgb, var(--intro-accent) 8%, transparent) 18%, color-mix(in srgb, var(--intro-accent) 2%, transparent) 32%, color-mix(in srgb, var(--intro-accent) .5%, transparent) 48%, transparent 78%)',
+ filter: 'blur(12px)',
+ }}
+ />
+ <WorkspaceTexture accent="var(--intro-accent)" filterId={noiseId} />
+ </div>
+ <div
+ class="pointer-events-none absolute -z-10 flex size-[min(560px,80vw)] items-center justify-center"
+ aria-hidden="true"
+ >
+ <div
+ ref={burst}
+ data-accent-burst
+ class="size-full opacity-0"
+ style={{
+ background:
+ 'radial-gradient(circle, var(--intro-accent) 0%, color-mix(in srgb, var(--intro-accent) 60%, transparent) 20%, transparent 65%)',
+ 'mask-image':
+ 'radial-gradient(circle, black 10%, transparent 70%)',
+ }}
+ >
+ <svg class="size-full" aria-hidden="true">
+ <rect
+ width="100%"
+ height="100%"
+ filter={`url(#${noiseId})`}
+ opacity=".45"
+ />
+ </svg>
+ </div>
+ </div>
+ <button
+ type="button"
+ aria-label="Play accent burst"
+ onClick={celebrateAccent}
+ class="workspace-intro-icon base-header-logo relative flex size-20 items-center justify-center rounded-[22px] focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ink"
+ style={{
+ color: 'var(--intro-accent)',
+ background:
+ 'linear-gradient(145deg, color-mix(in srgb, var(--intro-accent) 7%, #171717), #090909 65%)',
+ 'box-shadow':
+ 'inset .5px .5px 1px #ffffff1c, inset -.5px -.5px 1px #0008, 0 1px 1px #131313, 0 4px 10px #0005',
+ }}
+ >
+ <MacroMarkIcon class="h-7 w-10 overflow-visible" />
+ </button>
+ </div>
+ <fieldset class="mt-6 w-full max-w-[270px]">
+ <legend class="mb-3 w-full text-xs text-ink-muted">
+ Your accent{' '}
+ <span class="text-ink-extra-muted">· {accent().name}</span>
+ </legend>
+ <div class="flex justify-between gap-2">
+ <For each={WORKSPACE_ACCENTS}>
+ {(item) => (
+ <label class="relative flex size-9 items-center justify-center rounded-full has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-ink">
+ <input
+ type="radio"
+ name="workspace-accent"
+ aria-label={item.name}
+ class="sr-only"
+ checked={accent().name === item.name}
+ onChange={() => changeAccent(item.name)}
+ />
+ <span
+ class="box-content flex size-6 items-center justify-center rounded-full border-solid"
+ style={{
+ background: item.color,
+ 'background-clip': 'padding-box',
+ 'border-width': accent().name === item.name ? '4px' : '0px',
+ 'border-color': 'var(--color-ink)',
+ 'box-shadow':
+ 'inset 0 1px 1px #ffffff66, inset 0 -1px 1px #00000030',
+ }}
+ >
+ {accent().name === item.name && (
+ <CheckIcon class="size-3.5 text-surface" />
+ )}
+ </span>
+ </label>
+ )}
+ </For>
+ </div>
+ </fieldset>
+ <div class="mt-5">
+ {props.action ?? (
+ <ContinueButton
+ label="Get started"
+ onClick={() => props.onContinue(accent().color)}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/onboarding/components/workspace-texture.tsx b/apps/web/src/features/onboarding/components/workspace-texture.tsx
new file mode 100644
index 0000000000..9cc62dab2f
--- /dev/null
+++ b/apps/web/src/features/onboarding/components/workspace-texture.tsx
@@ -0,0 +1,41 @@
+const textureMask =
+ 'radial-gradient(ellipse 50% 50% at center, black 0%, #0009 25%, #0003 45%, #00000008 60%, transparent 78%)';
+
+/** Shared grain and accent dots for the opening onboarding slides. */
+export function WorkspaceTexture(props: { accent: string; filterId: string }) {
+ return (
+ <>
+ <div
+ aria-hidden="true"
+ class="pointer-events-none absolute inset-0 opacity-20"
+ style={{
+ 'background-image': `radial-gradient(${props.accent} .7px, transparent .7px)`,
+ 'background-size': '8px 8px',
+ 'mask-image': textureMask,
+ }}
+ />
+ <svg
+ data-workspace-texture
+ aria-hidden="true"
+ class="pointer-events-none absolute inset-0 size-full"
+ style={{ opacity: 0.2, 'mask-image': textureMask }}
+ >
+ <filter id={props.filterId}>
+ <feTurbulence
+ type="fractalNoise"
+ baseFrequency=".025"
+ numOctaves="4"
+ stitchTiles="stitch"
+ />
+ <feColorMatrix type="saturate" values="0" />
+ </filter>
+ <rect
+ width="100%"
+ height="100%"
+ filter={`url(#${props.filterId})`}
+ opacity=".7"
+ />
+ </svg>
+ </>
+ );
+}
diff --git a/apps/web/src/features/onboarding/context/onboarding-context.tsx b/apps/web/src/features/onboarding/context/onboarding-context.tsx
new file mode 100644
index 0000000000..d67412c084
--- /dev/null
+++ b/apps/web/src/features/onboarding/context/onboarding-context.tsx
@@ -0,0 +1,133 @@
+import type { PaidPlanTier } from '@app/features/paywall/plans';
+import type { AppEvents } from '@app/lib/analytics/app-events';
+import type { GtmInviteOffer } from '@service-auth/generated/schemas/gtmInviteOffer';
+import { type Accessor, createContext, useContext } from 'solid-js';
+import type { CheckoutTerms } from '../core/checkout';
+import type { EmailAccount } from '../core/email-accounts';
+
+/** Data availability as a source reports it; primitives decide presentation. */
+export type Loadable<T> =
+ | { t: 'loading' }
+ | { t: 'error' }
+ | { t: 'ready'; value: T };
+
+/** The signed-in account onboarding is setting up. */
+export type Viewer = {
+ id: string;
+ email: string | undefined;
+ tutorialComplete: boolean;
+ /** An active or trialing paid license. */
+ licensed: boolean;
+};
+
+export type ViewerState =
+ | { t: 'loading' }
+ | { t: 'signed-out' }
+ | { t: 'signed-in'; viewer: Viewer };
+
+/** The server's onboarding record. */
+export type OnboardingRecord = {
+ status: 'active' | 'completed';
+ /** A domain the server would let this user claim a team for. */
+ suggestedTeamDomain: string | undefined;
+};
+
+export type EmailAccountsSource = {
+ accounts: Accessor<Loadable<readonly EmailAccount[]>>;
+ /** Re-reads the links; resolves once the request settles. */
+ refresh(): Promise<void>;
+};
+
+/** A connectable integration from the catalog. */
+export type Tool = { slug: string; name: string; iconUrl: string | null };
+
+type ToolCatalogSource = {
+ /** What the user typed; the catalog re-queries once typing settles. */
+ search: Accessor<string>;
+ setSearch(value: string): void;
+ entries: Accessor<readonly Tool[]>;
+ fetching: Accessor<boolean>;
+ failed: Accessor<boolean>;
+ hasMore: Accessor<boolean>;
+ loadMore(): void;
+ retry(): void;
+};
+
+export type Team = { name: string };
+export type TeamInvite = { id: string; invitedBy: string };
+
+export type TeamDirectorySource = {
+ teams: Accessor<Loadable<readonly Team[]>>;
+ invites: Accessor<Loadable<readonly TeamInvite[]>>;
+ /** Contact email addresses, for same-domain invite suggestions. */
+ contacts: Accessor<Loadable<readonly string[]>>;
+ retry(): void;
+};
+
+/** The promotion an invite link granted this account. */
+export type InviteOffer = GtmInviteOffer;
+
+export type CompletionResult = { t: 'completed' } | { t: 'failed' };
+
+type OnboardingEventName =
+ | Extract<keyof AppEvents, `onboarding_v4_${string}`>
+ | 'subscription_success';
+// The conditional mirrors the app's analytics signature so it can be passed through.
+type TrackOnboarding = <E extends OnboardingEventName>(
+ event: E,
+ data: E extends keyof AppEvents ? AppEvents[E] : never
+) => void;
+
+/**
+ * Everything onboarding needs from the app. Source factories run under the
+ * consuming owner, so nothing is fetched until a step asks for it.
+ */
+export type OnboardingContext = {
+ viewer: Accessor<ViewerState>;
+ /** Re-reads the viewer from the server, e.g. while a webhook settles. */
+ refreshViewer(): Promise<ViewerState>;
+ createOnboardingRecord(): Accessor<Loadable<OnboardingRecord>>;
+ createEmailAccounts(): EmailAccountsSource;
+ /** Starts Google consent for another inbox; on web the page navigates away. */
+ connectInbox(): Promise<void>;
+ createToolCatalog(): ToolCatalogSource;
+ /**
+ * Slugs of connected tools; undefined until known. `poll` keeps re-checking
+ * while the user may be connecting one.
+ */
+ createConnectedTools(options: {
+ poll: boolean;
+ }): Accessor<ReadonlySet<string> | undefined>;
+ /** Resolves when the hosted connect flow closes; reports its own failures. */
+ connectTool(tool: Tool): Promise<void>;
+ createTeamDirectory(): TeamDirectorySource;
+ /** Rejects on failure; the capability reports its own errors. */
+ createTeam(input: { name: string; invites: string[] }): Promise<void>;
+ /** Rejects on failure; the capability reports its own errors. */
+ joinTeam(inviteId: string): Promise<void>;
+ /** The invite promotion the account holds; null when it has none. */
+ createInviteOffer(): Accessor<Loadable<InviteOffer | null>>;
+ /** The hosted checkout URL; rejects with a message fit to show. */
+ startCheckout(tier: PaidPlanTier, terms: CheckoutTerms): Promise<string>;
+ /**
+ * Marks onboarding and the tutorial done and confirms the server agrees.
+ * `skipped` records that the user left without going through the steps.
+ */
+ completeOnboarding(options: { skipped: boolean }): Promise<CompletionResult>;
+ /** Finishes a tutorial flag left behind by a completed onboarding record. */
+ repairTutorial(): Promise<void>;
+ applyAccent(color: string, viewerId: string): void;
+ createGithubStars(): Accessor<number | undefined>;
+ track: TrackOnboarding;
+ notifyFailure(message: string): void;
+};
+
+const Context = createContext<OnboardingContext>();
+
+export const OnboardingProvider = Context.Provider;
+
+export function useOnboardingContext(): OnboardingContext {
+ const context = useContext(Context);
+ if (!context) throw new Error('OnboardingProvider is required');
+ return context;
+}
diff --git a/apps/web/src/features/onboarding/core/checkout.test.ts b/apps/web/src/features/onboarding/core/checkout.test.ts
new file mode 100644
index 0000000000..56b264d2c3
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/checkout.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+import { onboardingCheckoutRequest, parseCheckoutReturn } from './checkout';
+
+const ONBOARDING = 'https://macro.com/app/onboarding';
+
+describe('onboardingCheckoutRequest', () => {
+ it('returns both checkout legs to the onboarding flow with the plan', () => {
+ expect(onboardingCheckoutRequest(ONBOARDING, 'premium', 'trial')).toEqual({
+ successUrl: `${ONBOARDING}?subscriptionSuccess=true&type=premium`,
+ cancelUrl: `${ONBOARDING}?subscriptionCancel=true`,
+ plan: 'premium',
+ onboardingTrial: true,
+ });
+ });
+
+ it('requests the trial only for Premium', () => {
+ const request = onboardingCheckoutRequest(ONBOARDING, 'max', 'trial');
+ expect(request.plan).toBe('max');
+ expect(request.onboardingTrial).toBe(false);
+ expect(request.successUrl).toBe(
+ `${ONBOARDING}?subscriptionSuccess=true&type=max`
+ );
+ });
+});
+
+describe('invite offers', () => {
+ it('check out with paid terms so the server applies the invite promotion', () => {
+ expect(
+ onboardingCheckoutRequest(ONBOARDING, 'premium', 'invite-offer')
+ .onboardingTrial
+ ).toBe(false);
+ });
+});
+
+describe('parseCheckoutReturn', () => {
+ it.each([
+ [{}, undefined],
+ [{ subscriptionCancel: 'true' }, { t: 'cancelled' }],
+ [{ subscriptionSuccess: 'true' }, { t: 'success', tier: 'premium' }],
+ [
+ { subscriptionSuccess: 'true', type: 'max' },
+ { t: 'success', tier: 'max' },
+ ],
+ [
+ { subscriptionSuccess: 'true', type: 'anything' },
+ { t: 'success', tier: 'premium' },
+ ],
+ ])('%o → %o', (params, expected) => {
+ expect(parseCheckoutReturn(params)).toEqual(expected);
+ });
+
+ it('round-trips the legs the request builds', () => {
+ const request = onboardingCheckoutRequest(ONBOARDING, 'max', 'trial');
+ const leg = (url: string) =>
+ Object.fromEntries(new URL(url).searchParams.entries());
+ expect(parseCheckoutReturn(leg(request.successUrl))).toEqual({
+ t: 'success',
+ tier: 'max',
+ });
+ expect(parseCheckoutReturn(leg(request.cancelUrl))).toEqual({
+ t: 'cancelled',
+ });
+ });
+});
diff --git a/apps/web/src/features/onboarding/core/checkout.ts b/apps/web/src/features/onboarding/core/checkout.ts
new file mode 100644
index 0000000000..0cbc115f20
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/checkout.ts
@@ -0,0 +1,51 @@
+import type { PaidPlanTier } from '@app/features/paywall/plans';
+
+/** How the Stripe round-trip came back to the plan step, if it did. */
+export type CheckoutReturn =
+ | { t: 'success'; tier: PaidPlanTier }
+ | { t: 'cancelled' };
+
+/**
+ * What the checkout grants: the automatic first-subscription trial, or the
+ * promotion an invite link redeemed (which the server applies, and which a
+ * trial would replace).
+ */
+export type CheckoutTerms = 'trial' | 'invite-offer';
+
+export type OnboardingCheckoutRequest = {
+ successUrl: string;
+ cancelUrl: string;
+ plan: PaidPlanTier;
+ onboardingTrial: boolean;
+};
+
+/**
+ * The checkout request for a plan bought during onboarding. Both legs of the
+ * Stripe round-trip return to the onboarding flow: the flow is still
+ * incomplete during checkout, so success and cancel land back on the plan
+ * step, which reads the query params to show the paid or cancelled state.
+ */
+export function onboardingCheckoutRequest(
+ onboardingUrl: string,
+ tier: PaidPlanTier,
+ terms: CheckoutTerms
+): OnboardingCheckoutRequest {
+ return {
+ successUrl: `${onboardingUrl}?subscriptionSuccess=true&type=${tier}`,
+ cancelUrl: `${onboardingUrl}?subscriptionCancel=true`,
+ plan: tier,
+ onboardingTrial: terms === 'trial' && tier === 'premium',
+ };
+}
+
+/** Reads the query params `onboardingCheckoutRequest` put on each leg. */
+export function parseCheckoutReturn(params: {
+ subscriptionSuccess?: unknown;
+ subscriptionCancel?: unknown;
+ type?: unknown;
+}): CheckoutReturn | undefined {
+ if (params.subscriptionSuccess === 'true')
+ return { t: 'success', tier: params.type === 'max' ? 'max' : 'premium' };
+ if (params.subscriptionCancel === 'true') return { t: 'cancelled' };
+ return undefined;
+}
diff --git a/apps/web/src/features/onboarding/core/email-accounts.test.ts b/apps/web/src/features/onboarding/core/email-accounts.test.ts
new file mode 100644
index 0000000000..94f12805ab
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/email-accounts.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+import { type EmailAccount, orderEmailAccounts } from './email-accounts';
+
+const account = (
+ address: string,
+ isPrimary: boolean,
+ ownerId = 'me'
+): EmailAccount => ({ address, isPrimary, ownerId });
+
+describe('orderEmailAccounts', () => {
+ it('puts the viewer’s own primary inbox first and keeps shared inboxes', () => {
+ expect(
+ orderEmailAccounts(
+ [
+ account('[email protected]', true, 'someone-else'),
+ account('[email protected]', false),
+ account('[email protected]', true),
+ ],
+ 'me'
+ ).map((item) => item.address)
+ });
+});
diff --git a/apps/web/src/features/onboarding/core/email-accounts.ts b/apps/web/src/features/onboarding/core/email-accounts.ts
new file mode 100644
index 0000000000..63b27ac2d9
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/email-accounts.ts
@@ -0,0 +1,23 @@
+/** A connected Google inbox as onboarding shows it. */
+export type EmailAccount = {
+ address: string;
+ isPrimary: boolean;
+ /** The Macro user who owns the link — another user's for a shared inbox. */
+ ownerId: string;
+};
+
+/**
+ * The viewer's own primary inbox first. No ownership filter: linking a mailbox
+ * owned by another Macro user creates a SHARED link carrying the owner's id —
+ * filtering would hide an inbox the user just connected.
+ */
+export function orderEmailAccounts(
+ accounts: readonly EmailAccount[],
+ viewerId: string | undefined
+): EmailAccount[] {
+ const ownPrimary = (account: EmailAccount) =>
+ account.isPrimary && account.ownerId === viewerId;
+ return [...accounts].sort(
+ (a, b) => Number(ownPrimary(b)) - Number(ownPrimary(a))
+ );
+}
diff --git a/apps/web/src/features/onboarding/core/next-target.test.ts b/apps/web/src/features/onboarding/core/next-target.test.ts
new file mode 100644
index 0000000000..a91ad94cf0
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/next-target.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+import {
+ afterOnboardingTarget,
+ bypassTarget,
+ sanitizeNext,
+} from './next-target';
+
+describe('sanitizeNext', () => {
+ it.each([
+ ['/channel/abc', '/channel/abc'],
+ ['/md/1?x=2', '/md/1?x=2'],
+ ['//evil.com', undefined],
+ ['https://evil.com', undefined],
+ ['/a\\b', undefined],
+ ['/home', undefined],
+ ['/home/inbox', undefined],
+ [undefined, undefined],
+ [['/channel/abc'], undefined],
+ ])('%o → %o', (value, expected) => {
+ expect(sanitizeNext(value)).toBe(expected);
+ });
+});
+
+describe('afterOnboardingTarget', () => {
+ it('prefers the first valid deep link', () => {
+ expect(afterOnboardingTarget('/home', '/channel/x', '/md/y')).toBe(
+ '/channel/x'
+ );
+ });
+
+ it('falls back to Getting Started', () => {
+ expect(afterOnboardingTarget(undefined, '//evil.com')).toBe(
+ '/getting-started'
+ );
+ });
+});
+
+describe('bypassTarget', () => {
+ it('keeps the deep link, else enters the app instead of Getting Started', () => {
+ expect(bypassTarget(undefined, '/channel/x')).toBe('/channel/x');
+ expect(bypassTarget(undefined, undefined)).toBe('/home');
+ });
+});
diff --git a/apps/web/src/features/onboarding/core/next-target.ts b/apps/web/src/features/onboarding/core/next-target.ts
new file mode 100644
index 0000000000..23fedd7be9
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/next-target.ts
@@ -0,0 +1,31 @@
+import { AFTER_SETUP_ROUTE, DEFAULT_ROUTE } from '@app/constants/defaultRoute';
+
+/**
+ * Same-app relative paths only. A `next` at the default route is not a real
+ * deep link, so it falls through to the post-setup landing.
+ */
+export function sanitizeNext(value: unknown): string | undefined {
+ return typeof value === 'string' &&
+ value.startsWith('/') &&
+ !value.startsWith('//') &&
+ !value.includes('\\') &&
+ !value.startsWith(DEFAULT_ROUTE)
+ ? value
+ : undefined;
+}
+
+function firstDeepLink(candidates: readonly unknown[]): string | undefined {
+ for (const candidate of candidates) {
+ const next = sanitizeNext(candidate);
+ if (next) return next;
+ }
+ return undefined;
+}
+
+/** Where finishing onboarding lands: the first valid deep link, else Getting Started. */
+export const afterOnboardingTarget = (...candidates: readonly unknown[]) =>
+ firstDeepLink(candidates) ?? AFTER_SETUP_ROUTE;
+
+/** Where bypassing lands: the deep link, else straight in the app — Getting Started is onboarding too. */
+export const bypassTarget = (...candidates: readonly unknown[]) =>
+ firstDeepLink(candidates) ?? DEFAULT_ROUTE;
diff --git a/apps/web/src/features/onboarding/core/plan-comparison.ts b/apps/web/src/features/onboarding/core/plan-comparison.ts
new file mode 100644
index 0000000000..e86e3c0bf9
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/plan-comparison.ts
@@ -0,0 +1,16 @@
+/** Feature comparison shown below the trial offer. */
+export const PLAN_COMPARISON = [
+ { feature: 'Connected email accounts', guest: 'Up to 2', pro: 'Unlimited' },
+ {
+ feature: 'Email branding',
+ guest: '“Sent with Macro” footer',
+ pro: 'No watermark',
+ },
+ { feature: 'AI models', guest: 'Haiku', pro: 'All models' },
+ { feature: 'Storage', guest: '5 GB', pro: '1 TB' },
+ {
+ feature: 'Calls, recording & transcription',
+ guest: 'Not included',
+ pro: 'Included',
+ },
+] as const;
diff --git a/apps/web/src/features/onboarding/core/signup-draft.test.ts b/apps/web/src/features/onboarding/core/signup-draft.test.ts
new file mode 100644
index 0000000000..902a547b48
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/signup-draft.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+import {
+ nextSignupStep,
+ parseSignupDraft,
+ previousSignupStep,
+ serializeSignupDraft,
+} from './signup-draft';
+
+describe('parseSignupDraft', () => {
+ it.each([
+ [null, undefined],
+ ['not json', undefined],
+ ['{"step":"plan"}', undefined],
+ ['[]', undefined],
+ ['{"step":"vision"}', { step: 'vision', authenticating: false }],
+ [
+ '{"step":"work","accent":"#65d8ac","authenticating":true}',
+ { step: 'work', accent: '#65d8ac', authenticating: true },
+ ],
+ [
+ '{"step":"vision","accent":"red","authenticating":true}',
+ { step: 'vision', authenticating: false },
+ ],
+ ])('%s → %o', (raw, expected) => {
+ expect(parseSignupDraft(raw)).toEqual(expected);
+ });
+
+ it('round-trips a serialized draft', () => {
+ const draft = {
+ step: 'work',
+ accent: '#7abde5',
+ authenticating: true,
+ } as const;
+ expect(parseSignupDraft(serializeSignupDraft(draft))).toEqual(draft);
+ });
+});
+
+describe('signup step order', () => {
+ it('walks welcome → vision → security → work', () => {
+ expect(nextSignupStep('welcome')).toBe('vision');
+ expect(nextSignupStep('security')).toBe('work');
+ expect(nextSignupStep('work')).toBe('work');
+ expect(previousSignupStep('work')).toBe('security');
+ expect(previousSignupStep('welcome')).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/onboarding/core/signup-draft.ts b/apps/web/src/features/onboarding/core/signup-draft.ts
new file mode 100644
index 0000000000..537f7653ae
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/signup-draft.ts
@@ -0,0 +1,50 @@
+const SIGNUP_STEPS = ['welcome', 'vision', 'security', 'work'] as const;
+export type SignupStep = (typeof SIGNUP_STEPS)[number];
+
+/** Only local presentation choices cross the sign-up redirect, never credentials. */
+export type SignupDraft = {
+ step: SignupStep;
+ accent?: string;
+ /** Google sign-up started from the work step; the OAuth return resumes there. */
+ authenticating?: boolean;
+};
+
+const isSignupStep = (value: unknown): value is SignupStep =>
+ SIGNUP_STEPS.some((step) => step === value);
+
+const isHexColor = (value: unknown): value is string =>
+ typeof value === 'string' && /^#[\da-f]{6}$/i.test(value);
+
+/** Validates a stored draft; anything malformed reads as no draft. */
+export function parseSignupDraft(raw: string | null): SignupDraft | undefined {
+ let value: unknown;
+ try {
+ value = JSON.parse(raw ?? 'null');
+ } catch {
+ return undefined;
+ }
+ if (!value || typeof value !== 'object' || !('step' in value)) return;
+ if (!isSignupStep(value.step)) return;
+ return {
+ step: value.step,
+ accent:
+ 'accent' in value && isHexColor(value.accent) ? value.accent : undefined,
+ authenticating:
+ 'authenticating' in value &&
+ value.authenticating === true &&
+ value.step === 'work',
+ };
+}
+
+export const serializeSignupDraft = (draft: SignupDraft) =>
+ JSON.stringify(draft);
+
+export function previousSignupStep(step: SignupStep): SignupStep | undefined {
+ const index = SIGNUP_STEPS.indexOf(step);
+ return index > 0 ? SIGNUP_STEPS[index - 1] : undefined;
+}
+
+export function nextSignupStep(step: SignupStep): SignupStep {
+ const index = SIGNUP_STEPS.indexOf(step);
+ return SIGNUP_STEPS[Math.min(index + 1, SIGNUP_STEPS.length - 1)];
+}
diff --git a/apps/web/src/features/setup/flow/shared.test.ts b/apps/web/src/features/onboarding/core/staff.test.ts
similarity index 93%
rename from apps/web/src/features/setup/flow/shared.test.ts
rename to apps/web/src/features/onboarding/core/staff.test.ts
index e4e72dd2bb..1d7737a479 100644
--- a/apps/web/src/features/setup/flow/shared.test.ts
+++ b/apps/web/src/features/onboarding/core/staff.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { canBypassOnboarding, isMacroStaffEmail } from './shared';
+import { canBypassOnboarding, isMacroStaffEmail } from './staff';
describe('canBypassOnboarding', () => {
it('shows Bypass for @macro.com accounts', () => {
diff --git a/apps/web/src/features/onboarding/core/staff.ts b/apps/web/src/features/onboarding/core/staff.ts
new file mode 100644
index 0000000000..a178b5baaa
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/staff.ts
@@ -0,0 +1,13 @@
+import { emailDomain } from './team';
+
+const MACRO_STAFF_DOMAIN = 'macro.com';
+
+/** Whether the address belongs to a Macro staff account (`@macro.com`). */
+export function isMacroStaffEmail(address: string | undefined): boolean {
+ return emailDomain(address) === MACRO_STAFF_DOMAIN;
+}
+
+/** Whether this account gets the staff Bypass button on the onboarding flow. */
+export function canBypassOnboarding(address: string | undefined): boolean {
+ return isMacroStaffEmail(address?.trim());
+}
diff --git a/apps/web/src/features/onboarding/core/steps.test.ts b/apps/web/src/features/onboarding/core/steps.test.ts
new file mode 100644
index 0000000000..d3c4890905
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/steps.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+import { restoreOnboardingStep } from './steps';
+
+describe('onboarding resume', () => {
+ it.each([
+ ['email', 'work'],
+ ['connect-linear', 'tools'],
+ ['building', 'plan'],
+ ['summary', 'plan'],
+ ['personal', 'personal'],
+ ['team', 'team'],
+ ])('migrates %s to %s', (saved, expected) => {
+ expect(restoreOnboardingStep(saved)).toBe(expected);
+ });
+ it.each([undefined, null, {}, 17, 'unknown'])(
+ 'starts safely for invalid saved steps',
+ (saved) => {
+ expect(restoreOnboardingStep(saved)).toBe('welcome');
+ }
+ );
+ it('restores the checkout step even when session storage was lost', () => {
+ expect(restoreOnboardingStep(undefined, true)).toBe('plan');
+ expect(restoreOnboardingStep('work', true)).toBe('plan');
+ });
+});
diff --git a/apps/web/src/features/onboarding/core/steps.ts b/apps/web/src/features/onboarding/core/steps.ts
new file mode 100644
index 0000000000..7be05b6e5f
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/steps.ts
@@ -0,0 +1,56 @@
+export const ONBOARDING_STEPS = [
+ 'welcome',
+ 'vision',
+ 'security',
+ 'work',
+ 'personal',
+ 'tools',
+ 'team',
+ 'plan',
+] as const;
+export type OnboardingStep = (typeof ONBOARDING_STEPS)[number];
+
+/** How the user left a step; analytics records it and skipping can fork. */
+export type StepOutcome = 'completed' | 'skipped';
+
+/** The opening slides that share the story stage's measured handoffs. */
+export type StoryStep = Extract<
+ OnboardingStep,
+ 'welcome' | 'vision' | 'security' | 'tools'
+>;
+
+export const isStoryStep = (step: OnboardingStep): step is StoryStep =>
+ step === 'welcome' ||
+ step === 'vision' ||
+ step === 'security' ||
+ step === 'tools';
+
+export function nextOnboardingStep(
+ step: OnboardingStep,
+ outcome: StepOutcome
+): OnboardingStep {
+ // Without a first account, offering a second account would be misleading.
+ if (step === 'work' && outcome === 'skipped') return 'tools';
+ const index = ONBOARDING_STEPS.indexOf(step);
+ return ONBOARDING_STEPS[Math.min(index + 1, ONBOARDING_STEPS.length - 1)];
+}
+
+export function previousOnboardingStep(
+ step: OnboardingStep
+): OnboardingStep | undefined {
+ const index = ONBOARDING_STEPS.indexOf(step);
+ return index > 0 ? ONBOARDING_STEPS[index - 1] : undefined;
+}
+
+/** Migrate in-progress sessions from the previous flow without losing OAuth returns. */
+export function restoreOnboardingStep(
+ saved: unknown,
+ checkoutReturn = false
+): OnboardingStep {
+ if (checkoutReturn) return 'plan';
+ if (typeof saved !== 'string') return 'welcome';
+ if (saved === 'email') return 'work';
+ if (saved.startsWith('connect-')) return 'tools';
+ if (saved === 'building' || saved === 'summary') return 'plan';
+ return ONBOARDING_STEPS.find((step) => step === saved) ?? 'welcome';
+}
diff --git a/apps/web/src/features/setup/flow/teamInvites.test.ts b/apps/web/src/features/onboarding/core/team.test.ts
similarity index 96%
rename from apps/web/src/features/setup/flow/teamInvites.test.ts
rename to apps/web/src/features/onboarding/core/team.test.ts
index 9c8d0814b6..b81a6bfd8b 100644
--- a/apps/web/src/features/setup/flow/teamInvites.test.ts
+++ b/apps/web/src/features/onboarding/core/team.test.ts
@@ -4,9 +4,9 @@ import {
prefillableTeammates,
removeInviteSlot,
validInviteEmails,
-} from './teamInvites';
+} from './team';
-const contact = (email: string) => ({ email });
+const contact = (email: string) => email;
describe('prefillableTeammates', () => {
it('picks same-domain contacts, skipping the user and duplicates', () => {
diff --git a/apps/web/src/features/setup/flow/teamInvites.ts b/apps/web/src/features/onboarding/core/team.ts
similarity index 55%
rename from apps/web/src/features/setup/flow/teamInvites.ts
rename to apps/web/src/features/onboarding/core/team.ts
index 59700a6c8f..f06a18385a 100644
--- a/apps/web/src/features/setup/flow/teamInvites.ts
+++ b/apps/web/src/features/onboarding/core/team.ts
@@ -1,28 +1,42 @@
-import { emailDomain, isPlausibleEmail } from './shared';
-
/** How many same-domain teammates get pre-added to the invite list. */
export const PREFILL_CAP = 6;
+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
+ * (`suggestedTeamDomain`) — 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);
+}
+
/**
* Same-domain teammates worth pre-adding to the invite list: the user's
* contacts on `domain`, minus themselves, deduped and capped.
*
* Empty when the domain isn't team-worthy — the server decides that via
- * `suggested_team_domain`.
+ * `suggestedTeamDomain`.
*/
export function prefillableTeammates(args: {
- contacts: { email: string }[];
+ contacts: readonly string[];
domain: string | undefined;
ownEmail: string | undefined;
}): string[] {
const { contacts, domain, ownEmail } = args;
if (!domain) return [];
const teammates = new Set(
- contacts
- .map((contact) => contact.email)
- .filter(
- (address) => address !== ownEmail && emailDomain(address) === domain
- )
+ contacts.filter(
+ (address) => address !== ownEmail && emailDomain(address) === domain
+ )
);
return [...teammates].slice(0, PREFILL_CAP);
}
diff --git a/apps/web/src/features/onboarding/core/workspace-accent.ts b/apps/web/src/features/onboarding/core/workspace-accent.ts
new file mode 100644
index 0000000000..5620bbd7ab
--- /dev/null
+++ b/apps/web/src/features/onboarding/core/workspace-accent.ts
@@ -0,0 +1,16 @@
+export const WORKSPACE_ACCENTS = [
+ { name: 'Pearl', color: '#e8e2db' },
+ { name: 'Lilac', color: '#b8a1ed' },
+ { name: 'Coral', color: '#f77d67' },
+ { name: 'Amber', color: '#f4c65c' },
+ { name: 'Mint', color: '#65d8ac' },
+ { name: 'Sky', color: '#7abde5' },
+] as const;
+
+export type WorkspaceAccent = (typeof WORKSPACE_ACCENTS)[number];
+
+const DEFAULT_WORKSPACE_ACCENT: WorkspaceAccent = WORKSPACE_ACCENTS[4];
+
+export const workspaceAccentNamed = (name: string): WorkspaceAccent =>
+ WORKSPACE_ACCENTS.find((accent) => accent.name === name) ??
+ DEFAULT_WORKSPACE_ACCENT;
diff --git a/apps/web/src/features/onboarding/create-app-onboarding-context.ts b/apps/web/src/features/onboarding/create-app-onboarding-context.ts
new file mode 100644
index 0000000000..8deebe5648
--- /dev/null
+++ b/apps/web/src/features/onboarding/create-app-onboarding-context.ts
@@ -0,0 +1,248 @@
+import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { toast } from '@core/component/Toast/Toast';
+import { deriveIsAuthenticated } from '@core/context/user';
+import { useAddInboxFlow } from '@core/email-link';
+import {
+ createPipedreamCatalogConnect,
+ createPipedreamCatalogSearch,
+} from '@core/pipedream/catalog';
+import { idToDisplayName, idToEmail } from '@core/user/util';
+import { useCreateCheckoutSessionMutation } from '@queries/auth';
+import { authKeys } from '@queries/auth/keys';
+import { useCompleteTutorialMutation } from '@queries/auth/tutorial';
+import { type UserInfoData, useUserInfoQuery } from '@queries/auth/user-info';
+import { queryClient } from '@queries/client';
+import { useContactsQuery } from '@queries/contacts/contacts';
+import { invalidateEmailLinks, useEmailLinksQuery } from '@queries/email/link';
+import { useGithubStarsQuery } from '@queries/github-stars';
+import { useGtmInviteOfferQuery } from '@queries/gtm-invite/links';
+import {
+ useCompleteOnboardingMutation,
+ useOnboardingQuery,
+} from '@queries/onboarding';
+import { usePipedreamConnectedSlugs } from '@queries/pipedream-connectors';
+import {
+ useJoinTeamMutation,
+ useUserInvitesQuery,
+} from '@queries/team/invitations';
+import {
+ useCreateTeamWithInvitesMutation,
+ useUserTeamsQuery,
+} from '@queries/team/teams';
+import { applyWorkspaceAccent } from './apply-workspace-accent';
+import type {
+ Loadable,
+ OnboardingContext,
+ ViewerState,
+} from './context/onboarding-context';
+import { onboardingCheckoutRequest } from './core/checkout';
+
+/** How often connected tools re-check while the user is on the tools step. */
+const CONNECTED_TOOLS_POLL_MS = 5_000;
+
+type UserInfoResult = {
+ isLoading: boolean;
+ isError: boolean;
+ isSuccess: boolean;
+ error: Error | null;
+ data: UserInfoData | undefined;
+};
+
+function toViewerState(result: UserInfoResult): ViewerState {
+ // Guarded: an unguarded `data` read suspends while the query is pending.
+ const data = result.isSuccess ? result.data : undefined;
+ // A signed-out visitor's request 401s rather than answering unauthenticated.
+ const authenticated = deriveIsAuthenticated({
+ isLoading: result.isLoading,
+ isError: result.isError,
+ error: result.error,
+ data,
+ });
+ if (authenticated === false) return { t: 'signed-out' };
+ if (!data?.userId) return { t: 'loading' };
+ return {
+ t: 'signed-in',
+ viewer: {
+ id: data.userId,
+ email: data.email ?? undefined,
+ tutorialComplete: data.tutorialComplete === true,
+ licensed:
+ data.licenseStatus === 'active' || data.licenseStatus === 'trialing',
+ },
+ };
+}
+
+/** TanStack status → source availability; data already loaded wins over a background failure. */
+function loadable<T, R>(
+ query: { isSuccess: boolean; isError: boolean; data: T | undefined },
+ map: (data: T) => R
+): Loadable<R> {
+ if (query.isSuccess && query.data !== undefined)
+ return { t: 'ready', value: map(query.data) };
+ if (query.isError) return { t: 'error' };
+ return { t: 'loading' };
+}
+
+/** Real queries, mutations, and app services behind the onboarding contract. */
+export function createAppOnboardingContext(): OnboardingContext {
+ const analytics = useAnalytics();
+ const userInfo = useUserInfoQuery();
+ const startAddInbox = useAddInboxFlow();
+ const createTeam = useCreateTeamWithInvitesMutation();
+ const joinTeam = useJoinTeamMutation();
+ const checkout = useCreateCheckoutSessionMutation();
+ const completeOnboarding = useCompleteOnboardingMutation();
+ const completeTutorial = useCompleteTutorialMutation();
+
+ const viewer = () => toViewerState(userInfo);
+ const needsOnboarding = () => {
+ const state = viewer();
+ return state.t === 'signed-in' && !state.viewer.tutorialComplete;
+ };
+ const refetchViewer = () =>
+ queryClient
+ .refetchQueries({ queryKey: authKeys.userInfo.queryKey })
+ .catch(() => {});
+
+ return {
+ viewer,
+ refreshViewer: async () => {
+ return toViewerState(await userInfo.refetch());
+ },
+
+ createOnboardingRecord: () => {
+ // Reading the record creates it and starts gathers, so only a viewer who
+ // is actually onboarding may read it.
+ const query = useOnboardingQuery({ enabled: needsOnboarding });
+ return () =>
+ query.isPlaceholderData
+ ? { t: 'loading' }
+ : loadable(query, (data) => ({
+ status: data.row.status === 'completed' ? 'completed' : 'active',
+ suggestedTeamDomain: data.suggested_team_domain ?? undefined,
+ }));
+ },
+
+ createEmailAccounts: () => {
+ const query = useEmailLinksQuery();
+ return {
+ accounts: () =>
+ loadable(query, (data) =>
+ data.links.map((link) => ({
+ address: link.email_address,
+ isPrimary: link.is_primary,
+ ownerId: link.macro_id,
+ }))
+ ),
+ refresh: async () => invalidateEmailLinks(),
+ };
+ },
+ connectInbox: () => startAddInbox(),
+
+ createToolCatalog: () => {
+ const catalog = createPipedreamCatalogSearch(() => new Set<string>());
+ return {
+ search: catalog.searchInput,
+ setSearch: catalog.onSearchInput,
+ entries: () =>
+ catalog.entries().map((entry) => ({
+ slug: entry.app_slug,
+ name: entry.display_name,
+ iconUrl: entry.icon_url ?? null,
+ })),
+ fetching: () => catalog.query.isFetching,
+ failed: () => catalog.query.isError,
+ hasMore: () => catalog.query.hasNextPage,
+ loadMore: () => void catalog.query.fetchNextPage(),
+ retry: () => void catalog.query.refetch(),
+ };
+ },
+ createConnectedTools: ({ poll }) => {
+ const connected = usePipedreamConnectedSlugs({
+ refetchInterval: poll ? CONNECTED_TOOLS_POLL_MS : undefined,
+ });
+ return () => (connected.ready() ? connected.slugs() : undefined);
+ },
+ connectTool: (tool) =>
+ createPipedreamCatalogConnect({
+ entry: () => ({ app_slug: tool.slug, display_name: tool.name }),
+ }).connect(),
+
+ createTeamDirectory: () => {
+ const teams = useUserTeamsQuery();
+ const invites = useUserInvitesQuery();
+ const contacts = useContactsQuery();
+ return {
+ teams: () =>
+ loadable(teams, (data) => data.map((team) => ({ name: team.name }))),
+ invites: () =>
+ loadable(invites, (data) =>
+ (data.invites ?? []).map((invite) => ({
+ id: invite.id,
+ invitedBy: idToDisplayName(invite.invited_by),
+ }))
+ ),
+ contacts: () =>
+ loadable(contacts, (data) => data.contacts.map(idToEmail)),
+ retry: () => {
+ void teams.refetch();
+ void invites.refetch();
+ },
+ };
+ },
+ createTeam: async ({ name, invites }) => {
+ await createTeam.mutateAsync({
+ name,
+ invites: invites.map((email) => ({ email })),
+ });
+ },
+ joinTeam: async (inviteId) => {
+ await joinTeam.mutateAsync({ teamInviteId: inviteId });
+ },
+
+ createInviteOffer: () => {
+ const query = useGtmInviteOfferQuery({ enabled: needsOnboarding });
+ return () => loadable(query, (offer) => offer ?? null);
+ },
+ startCheckout: (tier, terms) =>
+ checkout.mutateAsync(
+ onboardingCheckoutRequest(
+ `${window.location.origin}${ROUTER_BASE_CONCAT}onboarding`,
+ tier,
+ terms
+ )
+ ),
+ completeOnboarding: async ({ skipped }) => {
+ const [onboardingResult] = await Promise.allSettled([
+ completeOnboarding.mutateAsync({ skipped }),
+ 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') return { t: 'failed' };
+ // The Layout redirect keys off tutorialComplete, so leaving before the
+ // cache reflects the PATCH would bounce straight back. Read the cache,
+ // not the observer: its store flushes on a later task.
+ await refetchViewer();
+ const data = queryClient.getQueryData<UserInfoData>(
+ authKeys.userInfo.queryKey
+ );
+ return data?.tutorialComplete === true
+ ? { t: 'completed' }
+ : { t: 'failed' };
+ },
+ repairTutorial: async () => {
+ await completeTutorial.mutateAsync();
+ await refetchViewer();
+ },
+
+ applyAccent: applyWorkspaceAccent,
+ createGithubStars: () => {
+ const stars = useGithubStarsQuery();
+ return () => (stars.isSuccess ? stars.data : undefined);
+ },
+ track: (event, data) => analytics.track(event, data),
+ notifyFailure: (message) => toast.failure(message),
+ };
+}
diff --git a/apps/web/src/features/onboarding/onboarding.tsx b/apps/web/src/features/onboarding/onboarding.tsx
new file mode 100644
index 0000000000..5a2fab900b
--- /dev/null
+++ b/apps/web/src/features/onboarding/onboarding.tsx
@@ -0,0 +1,61 @@
+import { InviteOfferPanel } from '@app/features/gtm-invite/InviteOfferPanel';
+import { useImportQuery } from '@queries/import';
+import { useNavigate, useSearchParams } from '@solidjs/router';
+import type { JSX } from 'solid-js';
+import { OnboardingProvider } from './context/onboarding-context';
+import { parseCheckoutReturn } from './core/checkout';
+import { createAppOnboardingContext } from './create-app-onboarding-context';
+import { OnboardingFlowView } from './views/onboarding-flow-view';
+import { SignupJourneyView } from './views/signup-journey-view';
+
+/** The signed-in onboarding flow, wired to the app's services and router. */
+export function Onboarding() {
+ const context = createAppOnboardingContext();
+ const navigate = useNavigate();
+ const [params] = useSearchParams();
+ // Polling the import state keeps gather runs starting while the user is in
+ // the flow; the steps themselves never read it.
+ useImportQuery({
+ enabled: () => {
+ const viewer = context.viewer();
+ return viewer.t === 'signed-in' && !viewer.viewer.tutorialComplete;
+ },
+ });
+ return (
+ <OnboardingProvider value={context}>
+ <OnboardingFlowView
+ next={typeof params.next === 'string' ? params.next : undefined}
+ checkoutReturn={parseCheckoutReturn(params)}
+ onNavigate={(target) => navigate(target, { replace: true })}
+ onRedirect={(url) => {
+ window.location.href = url;
+ }}
+ onSignedOut={() => navigate('/login', { replace: true })}
+ renderInviteOffer={(offer, actions) => (
+ <InviteOfferPanel
+ offer={offer}
+ finishing={actions.finishing()}
+ onStartCheckout={actions.onClaim}
+ onContinueFree={actions.onContinueFree}
+ />
+ )}
+ />
+ </OnboardingProvider>
+ );
+}
+
+/** The signed-out opening slides, hosted by the sign-up page. */
+export function OnboardingSignup(props: {
+ onGoogle: () => Promise<void>;
+ onBackFromEmail: () => void;
+ emailForm?: JSX.Element;
+ showingEmail: boolean;
+}) {
+ return (
+ <OnboardingProvider value={createAppOnboardingContext()}>
+ <SignupJourneyView {...props} />
+ </OnboardingProvider>
+ );
+}
+
+export { clearSignupDraft } from './primitives/flow-storage';
diff --git a/apps/web/src/features/onboarding/primitives/email-accounts.ts b/apps/web/src/features/onboarding/primitives/email-accounts.ts
new file mode 100644
index 0000000000..a55e9ab5ef
--- /dev/null
+++ b/apps/web/src/features/onboarding/primitives/email-accounts.ts
@@ -0,0 +1,84 @@
+import { createEffect, createSignal, onCleanup } from 'solid-js';
+import type {
+ EmailAccountsSource,
+ Loadable,
+ OnboardingContext,
+} from '../context/onboarding-context';
+import { type EmailAccount, orderEmailAccounts } from '../core/email-accounts';
+import { readConnectBaseline, saveConnectBaseline } from './flow-storage';
+
+/** How often the step re-checks for freshly-linked inboxes while visible. */
+const EMAIL_ACCOUNTS_POLL_MS = 5_000;
+
+export type InboxSlot = 'work' | 'personal';
+
+/**
+ * Connecting Google inboxes. On web, connecting is a full-page OAuth redirect,
+ * so a landed link is detected against a baseline saved before leaving.
+ */
+export function createEmailAccounts(
+ context: Pick<OnboardingContext, 'viewer' | 'connectInbox' | 'track'>,
+ source: EmailAccountsSource
+) {
+ const [connecting, setConnecting] = createSignal<InboxSlot>();
+
+ // The links have a long stale time; a connect that just completed (this tab
+ // or another) must show up the moment the user is back.
+ void source.refresh();
+ const interval = setInterval(
+ () => void source.refresh(),
+ EMAIL_ACCOUNTS_POLL_MS
+ );
+ onCleanup(() => clearInterval(interval));
+
+ const accounts = (): Loadable<EmailAccount[]> => {
+ const state = source.accounts();
+ if (state.t !== 'ready') return state;
+ const viewer = context.viewer();
+ return {
+ t: 'ready',
+ value: orderEmailAccounts(
+ state.value,
+ viewer.t === 'signed-in' ? viewer.viewer.id : undefined
+ ),
+ };
+ };
+ const list = () => {
+ const state = accounts();
+ return state.t === 'ready' ? state.value : [];
+ };
+
+ createEffect(() => {
+ const state = source.accounts();
+ if (state.t !== 'ready') return;
+ const baseline = readConnectBaseline();
+ if (baseline === undefined) return;
+ const count = state.value.length;
+ if (count > baseline)
+ context.track('onboarding_v4_email_connected', {
+ connected_count: count,
+ });
+ if (count !== baseline) saveConnectBaseline(undefined);
+ });
+
+ const connect = async (slot: InboxSlot) => {
+ if (connecting() !== undefined) return;
+ setConnecting(slot);
+ context.track('onboarding_v4_email_connect_clicked', { slot });
+ saveConnectBaseline(list().length);
+ try {
+ await context.connectInbox();
+ } finally {
+ setConnecting(undefined);
+ }
+ };
+
+ return {
+ accounts,
+ primary: () => list()[0],
+ secondary: () => list()[1],
+ connecting,
+ connect,
+ retry: () => void source.refresh(),
+ };
+}
diff --git a/apps/web/src/features/onboarding/primitives/flow-finish.test.ts b/apps/web/src/features/onboarding/primitives/flow-finish.test.ts
new file mode 100644
index 0000000000..67d84a076e
--- /dev/null
+++ b/apps/web/src/features/onboarding/primitives/flow-finish.test.ts
@@ -0,0 +1,127 @@
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ createFakeOnboarding,
+ type FakeOnboardingWorld,
+} from '../tests/fake-onboarding-context';
+import { createFlowFinish } from './flow-finish';
+import {
+ readSavedNext,
+ readSavedStep,
+ saveNext,
+ saveStep,
+} from './flow-storage';
+
+const VIEWER = 'macro|[email protected]';
+
+let dispose: (() => void) | undefined;
+afterEach(() => dispose?.());
+beforeEach(() => sessionStorage.clear());
+
+function setup(world: Partial<FakeOnboardingWorld> = {}, next?: string) {
+ const fake = createFakeOnboarding(world);
+ const navigate = vi.fn();
+ const redirect = vi.fn();
+ const finish = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFlowFinish(fake.context, {
+ next: () => next,
+ onNavigate: navigate,
+ onRedirect: redirect,
+ });
+ });
+ return { fake, finish, navigate, redirect };
+}
+
+describe('leaving onboarding', () => {
+ it('keeps setup retryable and shows the reason when a trial is rejected', async () => {
+ const message =
+ 'The 30-day trial is only available for your first Premium subscription';
+ saveStep(VIEWER, 'plan');
+ const { fake, finish, navigate, redirect } = setup({
+ failures: { checkout: message },
+ });
+ await finish.startPremiumCheckout('premium');
+ expect(fake.notifications()).toEqual([message]);
+ expect(fake.calls()).not.toContain('completeOnboarding');
+ expect(navigate).not.toHaveBeenCalled();
+ expect(redirect).not.toHaveBeenCalled();
+ expect(readSavedStep(VIEWER)).toBe('plan');
+ expect(finish.finishing()).toBe(false);
+ });
+
+ it('hands the page to checkout and stays busy while it unloads', async () => {
+ const { finish, redirect } = setup();
+ await finish.startPremiumCheckout('premium');
+ expect(redirect).toHaveBeenCalledWith(
+ 'https://checkout.stripe.test/premium'
+ );
+ expect(finish.finishing()).toBe(true);
+ });
+
+ it.each(['guest', 'paid'] as const)(
+ 'returns to the original deep link when completing as %s',
+ async (plan) => {
+ saveNext('/channel/example');
+ saveStep(VIEWER, 'plan');
+ const { fake, finish, navigate } = setup();
+ if (plan === 'guest') await finish.finishFree();
+ else await finish.finishPremium('max');
+ expect(navigate).toHaveBeenCalledWith('/channel/example');
+ expect(readSavedNext()).toBeUndefined();
+ expect(readSavedStep(VIEWER)).toBeUndefined();
+ expect(finish.finishing()).toBe(true);
+ expect(fake.events().at(-1)).toEqual({
+ event: 'onboarding_v4_completed',
+ data: expect.objectContaining({
+ plan: plan === 'guest' ? 'free' : 'max',
+ plan_skipped: false,
+ }),
+ });
+ }
+ );
+
+ it('prefers the live ?next over the saved one, and remembers it for OAuth returns', async () => {
+ saveNext('/md/older');
+ const { finish, navigate } = setup({}, '/channel/live');
+ expect(readSavedNext()).toBe('/channel/live');
+ await finish.finishFree();
+ expect(navigate).toHaveBeenCalledWith('/channel/live');
+ });
+
+ it('lands on Getting Started without a deep link', async () => {
+ const { finish, navigate } = setup({}, '/home');
+ await finish.finishFree(true);
+ expect(navigate).toHaveBeenCalledWith('/getting-started');
+ });
+
+ it('stays on setup with saved progress when completion fails', async () => {
+ saveStep(VIEWER, 'team');
+ const { fake, finish, navigate } = setup({
+ failures: { completion: 'offline' },
+ });
+ await finish.finishFree();
+ expect(navigate).not.toHaveBeenCalled();
+ expect(readSavedStep(VIEWER)).toBe('team');
+ expect(fake.notifications()).toHaveLength(1);
+ expect(finish.finishing()).toBe(false);
+ });
+
+ it('lets staff bypass from any step, recorded as skipped and landing in the app', async () => {
+ saveStep(VIEWER, 'tools');
+ const { fake, finish, navigate } = setup();
+ await finish.bypass('tools');
+ expect(fake.calls()).toContain('completeOnboarding:skipped');
+ expect(fake.events()).toEqual([
+ { event: 'onboarding_v4_bypassed', data: { step: 'tools' } },
+ ]);
+ expect(navigate).toHaveBeenCalledWith('/home');
+ expect(readSavedStep(VIEWER)).toBeUndefined();
+ });
+
+ it('keeps the deep link when bypassing', async () => {
+ const { finish, navigate } = setup({}, '/channel/launch');
+ await finish.bypass('welcome');
+ expect(navigate).toHaveBeenCalledWith('/channel/launch');
+ });
+});
diff --git a/apps/web/src/features/onboarding/primitives/flow-finish.ts b/apps/web/src/features/onboarding/primitives/flow-finish.ts
new file mode 100644
index 0000000000..04fb1686c6
--- /dev/null
+++ b/apps/web/src/features/onboarding/primitives/flow-finish.ts
@@ -0,0 +1,133 @@
+import type { PaidPlanTier, PlanTier } from '@app/features/paywall/plans';
+import { type Accessor, createSignal } from 'solid-js';
+import type {
+ CompletionResult,
+ OnboardingContext,
+} from '../context/onboarding-context';
+import type { CheckoutTerms } from '../core/checkout';
+import {
+ afterOnboardingTarget,
+ bypassTarget,
+ sanitizeNext,
+} from '../core/next-target';
+import { clearFlowProgress, readSavedNext, saveNext } from './flow-storage';
+
+type FinishCapabilities = Pick<
+ OnboardingContext,
+ 'completeOnboarding' | 'startCheckout' | 'track' | 'notifyFailure'
+>;
+
+/**
+ * The "leave onboarding" workflow: complete onboarding, then land in the app
+ * (the preserved `?next` deep link, or the Getting Started checklist).
+ */
+export function createFlowFinish(
+ context: FinishCapabilities,
+ options: {
+ next: Accessor<string | undefined>;
+ onNavigate: (target: string) => void;
+ /** Leaves the app for hosted checkout. */
+ onRedirect: (url: string) => void;
+ /** Rollup stamped onto `onboarding_v4_completed`. */
+ completionRollup?: () => {
+ emails_connected: number;
+ connectors_connected: string[];
+ };
+ }
+) {
+ const [finishing, setFinishing] = createSignal(false);
+
+ // The inbox-OAuth callback returns to bare /onboarding, so persist the deep
+ // link as soon as it is known; it is read again after the round-trip.
+ const persistNext = () => {
+ const next = sanitizeNext(options.next());
+ if (next) saveNext(next);
+ };
+ persistNext();
+
+ const afterTarget = () =>
+ afterOnboardingTarget(options.next(), readSavedNext());
+
+ const trackCompleted = (plan: PlanTier, planSkipped: boolean) => {
+ context.track('onboarding_v4_completed', {
+ plan,
+ plan_skipped: planSkipped,
+ emails_connected: 0,
+ connectors_connected: [],
+ ...options.completionRollup?.(),
+ });
+ };
+
+ const leave = async (input: {
+ skipped: boolean;
+ target: string;
+ onCompleted: () => void;
+ }) => {
+ if (finishing()) return;
+ setFinishing(true);
+ const result = await context
+ .completeOnboarding({ skipped: input.skipped })
+ .catch((): CompletionResult => ({ t: 'failed' }));
+ if (result.t === 'failed') {
+ context.notifyFailure("Couldn't finish setup — please try again");
+ setFinishing(false);
+ return;
+ }
+ clearFlowProgress();
+ input.onCompleted();
+ // Stay finishing: the flow now reads as complete, and dropping the flag
+ // would let it navigate a second time, after the saved deep link is gone.
+ options.onNavigate(input.target);
+ };
+
+ // Targets resolve before completing: completion clears the saved deep link.
+ const complete = (plan: PlanTier, planSkipped: boolean) =>
+ leave({
+ skipped: false,
+ target: afterTarget(),
+ onCompleted: () => trackCompleted(plan, planSkipped),
+ });
+
+ /**
+ * Hand the page to Stripe WITHOUT completing the flow: both checkout legs
+ * return to the plan step, which finishes only once payment is confirmed.
+ */
+ const startPremiumCheckout = async (
+ tier: PaidPlanTier,
+ terms: CheckoutTerms = 'trial'
+ ) => {
+ if (finishing()) return;
+ setFinishing(true);
+ try {
+ const url = await context.startCheckout(tier, terms);
+ // Leave `finishing` set: the page is navigating away, and re-enabling
+ // the buttons mid-unload invites a double checkout.
+ options.onRedirect(url);
+ } catch (error) {
+ context.notifyFailure(
+ error instanceof Error
+ ? error.message
+ : "Couldn't start checkout — please try again"
+ );
+ setFinishing(false);
+ }
+ };
+
+ return {
+ finishing,
+ afterTarget,
+ persistNext,
+ /** Finish as a Guest (or with the plan step skipped) and enter the app. */
+ finishFree: (planSkipped = false) => complete('free', planSkipped),
+ startPremiumCheckout,
+ /** Finish after checkout confirmed payment, recording the tier Stripe returned. */
+ finishPremium: (tier: PaidPlanTier = 'premium') => complete(tier, false),
+ /** Staff escape hatch: leave from any step, recorded server-side as skipped. */
+ bypass: (step: string) =>
+ leave({
+ skipped: true,
+ target: bypassTarget(options.next(), readSavedNext()),
+ onCompleted: () => context.track('onboarding_v4_bypassed', { step }),
+ }),
+ };
+}
diff --git a/apps/web/src/features/onboarding/primitives/flow-storage.ts b/apps/web/src/features/onboarding/primitives/flow-storage.ts
new file mode 100644
index 0000000000..155b4ab4a2
--- /dev/null
+++ b/apps/web/src/features/onboarding/primitives/flow-storage.ts
@@ -0,0 +1,90 @@
+import {
+ parseSignupDraft,
+ type SignupDraft,
+ serializeSignupDraft,
+} from '../core/signup-draft';
+import type { OnboardingStep } from '../core/steps';
+
+/**
+ * Session state that must survive full-page round-trips: Google sign-up,
+ * inbox OAuth, and Stripe checkout all reload the app mid-flow.
+ */
+const KEYS = {
+ /** `{ user, step }`: the step to resume, scoped to who saved it. */
+ step: 'onboarding-flow-step',
+ /** The `?next` deep link; the inbox OAuth callback returns to bare /onboarding. */
+ next: 'onboarding-flow-next',
+ /** Inbox count when a connect started, to detect a landed link after reload. */
+ connectBaseline: 'onboarding-flow-email-baseline',
+ /** Presentation choices from the signed-out slides. */
+ signupDraft: 'onboarding-signup-draft',
+} as const;
+
+function read(key: string): string | null {
+ try {
+ return sessionStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+function write(key: string, value: string | undefined) {
+ try {
+ if (value === undefined) sessionStorage.removeItem(key);
+ else sessionStorage.setItem(key, value);
+ } catch {
+ // Storage blocked: the flow still works, it just can't resume.
+ }
+}
+
+/** The saved step for `userId`; another user's progress is discarded. */
+export function readSavedStep(userId: string): string | undefined {
+ const raw = read(KEYS.step);
+ if (raw === null) return undefined;
+ try {
+ const saved: unknown = JSON.parse(raw);
+ if (
+ saved &&
+ typeof saved === 'object' &&
+ 'user' in saved &&
+ saved.user === userId &&
+ 'step' in saved &&
+ typeof saved.step === 'string'
+ )
+ return saved.step;
+ } catch {
+ // Fall through: malformed progress is discarded like a stranger's.
+ }
+ write(KEYS.step, undefined);
+ write(KEYS.next, undefined);
+ return undefined;
+}
+
+export const saveStep = (userId: string, step: OnboardingStep) =>
+ write(KEYS.step, JSON.stringify({ user: userId, step }));
+
+export const readSavedNext = () => read(KEYS.next) ?? undefined;
+export const saveNext = (next: string) => write(KEYS.next, next);
+
+/** Forget resumable progress once the user leaves onboarding for good. */
+export function clearFlowProgress() {
+ write(KEYS.step, undefined);
+ write(KEYS.next, undefined);
+}
+
+export function readConnectBaseline(): number | undefined {
+ const raw = read(KEYS.connectBaseline);
+ if (raw === null) return undefined;
+ const value = Number(raw);
+ return Number.isFinite(value) ? value : undefined;
+}
+
+export const saveConnectBaseline = (count: number | undefined) =>
+ write(KEYS.connectBaseline, count === undefined ? undefined : String(count));
+
+export const readSignupDraft = () => parseSignupDraft(read(KEYS.signupDraft));
+
+export const saveSignupDraft = (draft: SignupDraft) =>
+ write(KEYS.signupDraft, serializeSignupDraft(draft));
+
+export const clearSignupDraft = () => write(KEYS.signupDraft, undefined);
diff --git a/apps/web/src/features/onboarding/primitives/onboarding-flow.ts b/apps/web/src/features/onboarding/primitives/onboarding-flow.ts
new file mode 100644
index 0000000000..8637c49c83
--- /dev/null
+++ b/apps/web/src/features/onboarding/primitives/onboarding-flow.ts
@@ -0,0 +1,159 @@
+import { type Accessor, createEffect, createSignal, on } from 'solid-js';
+import type {
+ Loadable,
+ OnboardingContext,
+ OnboardingRecord,
+ Viewer,
+} from '../context/onboarding-context';
+import type { CheckoutReturn } from '../core/checkout';
+import {
+ nextOnboardingStep,
+ ONBOARDING_STEPS,
+ type OnboardingStep,
+ restoreOnboardingStep,
+ type StepOutcome,
+} from '../core/steps';
+import {
+ clearSignupDraft,
+ readSavedStep,
+ readSignupDraft,
+ saveStep,
+} from './flow-storage';
+
+type FlowCapabilities = Pick<
+ OnboardingContext,
+ 'viewer' | 'applyAccent' | 'repairTutorial' | 'track'
+>;
+
+/** Where the flow stands for the signed-in viewer. */
+export type FlowStatus =
+ | { t: 'loading' }
+ | { t: 'signed-out' }
+ /** Onboarding is already done; the host should leave. */
+ | { t: 'complete' }
+ | { t: 'active'; viewer: Viewer; step: OnboardingStep };
+
+/**
+ * The step machine: restores progress across OAuth/Stripe round-trips, saves
+ * every step, and reports the funnel. Motion between steps belongs to the view,
+ * which calls `commit` once its transition is ready to swap content.
+ */
+export function createOnboardingFlow(
+ context: FlowCapabilities,
+ options: {
+ checkoutReturn: Accessor<CheckoutReturn | undefined>;
+ record: Accessor<Loadable<OnboardingRecord>>;
+ /** Whether the viewer signed up with Google (has an inbox) or an email code. */
+ signupMethod: Accessor<'google' | 'email_code' | undefined>;
+ /** While leaving, a completed tutorial is the flow's own doing. */
+ finishing: Accessor<boolean>;
+ }
+) {
+ const [step, setStep] = createSignal<OnboardingStep>();
+ const index = () => {
+ const current = step();
+ return current ? ONBOARDING_STEPS.indexOf(current) : -1;
+ };
+
+ const viewer = (): Viewer | undefined => {
+ const state = context.viewer();
+ return state.t === 'signed-in' ? state.viewer : undefined;
+ };
+ const needsOnboarding = () => viewer()?.tutorialComplete === false;
+
+ // Restore once per viewer: the signed-out draft's OAuth return wins, then
+ // saved progress; a checkout return always lands on the plan step.
+ createEffect(
+ on(
+ () => viewer()?.id,
+ (userId) => {
+ if (!userId || step()) return;
+ const draft = readSignupDraft();
+ const initial = restoreOnboardingStep(
+ draft?.authenticating ? 'work' : readSavedStep(userId),
+ options.checkoutReturn() !== undefined
+ );
+ saveStep(userId, initial);
+ if (draft?.authenticating && draft.accent)
+ context.applyAccent(draft.accent, userId);
+ clearSignupDraft();
+ setStep(initial);
+ }
+ )
+ );
+
+ let started = false;
+ createEffect(() => {
+ const current = step();
+ const method = options.signupMethod();
+ if (!current || !needsOnboarding() || started || !method) return;
+ started = true;
+ context.track('onboarding_v4_started', {
+ signup_method: method,
+ entry_step: current,
+ });
+ });
+
+ createEffect(
+ on(step, (current) => {
+ if (current && needsOnboarding())
+ context.track('onboarding_v4_step', {
+ step: current,
+ index: index(),
+ state: 'viewed',
+ });
+ })
+ );
+
+ // Repair partially completed setup without sending the user into a redirect
+ // loop: the server says done but the tutorial flag never landed.
+ let repairing = false;
+ createEffect(() => {
+ const record = options.record();
+ if (
+ repairing ||
+ !needsOnboarding() ||
+ record.t !== 'ready' ||
+ record.value.status !== 'completed'
+ )
+ return;
+ repairing = true;
+ context.repairTutorial().catch(() => {
+ repairing = false;
+ });
+ });
+
+ const status = (): FlowStatus => {
+ const state = context.viewer();
+ if (state.t === 'loading') return { t: 'loading' };
+ if (state.t === 'signed-out') return { t: 'signed-out' };
+ if (!state.viewer.tutorialComplete || options.finishing()) {
+ const current = step();
+ return current
+ ? { t: 'active', viewer: state.viewer, step: current }
+ : { t: 'loading' };
+ }
+ return { t: 'complete' };
+ };
+
+ /** Show `next` and save it as the step to resume. */
+ const commit = (next: OnboardingStep) => {
+ const userId = viewer()?.id;
+ if (userId) saveStep(userId, next);
+ setStep(next);
+ };
+
+ /** Record how the user left the current step and return where to go next. */
+ const leave = (outcome: StepOutcome): OnboardingStep | undefined => {
+ const current = step();
+ if (!current) return undefined;
+ context.track('onboarding_v4_step', {
+ step: current,
+ index: index(),
+ state: outcome,
+ });
+ return nextOnboardingStep(current, outcome);
+ };
+
+ return { status, step, index, commit, leave };
+}
diff --git a/apps/web/src/features/onboarding/primitives/plan-confirmation.ts b/apps/web/src/features/onboarding/primitives/plan-confirmation.ts
new file mode 100644
index 0000000000..d6a6ce249c
--- /dev/null
+++ b/apps/web/src/features/onboarding/primitives/plan-confirmation.ts
@@ -0,0 +1,77 @@
+import type { PaidPlanTier } from '@app/features/paywall/plans';
+import { createSignal, onCleanup } from 'solid-js';
+import type { OnboardingContext } from '../context/onboarding-context';
+import type { CheckoutReturn } from '../core/checkout';
+
+/** Webhook settling can lag the Stripe redirect; poll this long before asking for a retry. */
+const LICENSE_POLL_ATTEMPTS = 10;
+const LICENSE_POLL_MS = 1_000;
+
+export type PlanState =
+ /** No paid license: offer the trial. */
+ | { t: 'offer' }
+ | { t: 'confirming' }
+ /** Paid, or back from checkout: continuing re-checks the license. */
+ | { t: 'continue'; stillWaiting: boolean };
+
+/**
+ * Stripe owns payment details. A success URL alone is not proof of payment:
+ * the flow finishes only once the server reports an active or trialing license.
+ */
+export function createPlanConfirmation(
+ context: Pick<OnboardingContext, 'viewer' | 'refreshViewer' | 'track'>,
+ options: {
+ checkoutReturn: CheckoutReturn | undefined;
+ onConfirmed: (tier: PaidPlanTier) => Promise<void>;
+ }
+) {
+ const returned = options.checkoutReturn?.t === 'success';
+ const tier: PaidPlanTier =
+ options.checkoutReturn?.t === 'success'
+ ? options.checkoutReturn.tier
+ : 'premium';
+ const licensed = () => {
+ const viewer = context.viewer();
+ return viewer.t === 'signed-in' && viewer.viewer.licensed;
+ };
+ const [confirming, setConfirming] = createSignal(returned);
+ const [stillWaiting, setStillWaiting] = createSignal(false);
+ let disposed = false;
+ onCleanup(() => {
+ disposed = true;
+ });
+
+ const confirm = async () => {
+ setConfirming(true);
+ setStillWaiting(false);
+ try {
+ for (let attempt = 0; attempt < LICENSE_POLL_ATTEMPTS; attempt++) {
+ if (disposed) return;
+ const viewer = await context.refreshViewer();
+ if (disposed) return;
+ if (viewer.t === 'signed-in' && viewer.viewer.licensed) {
+ await options.onConfirmed(tier);
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, LICENSE_POLL_MS));
+ }
+ setStillWaiting(true);
+ } catch {
+ setStillWaiting(true);
+ } finally {
+ if (!disposed) setConfirming(false);
+ }
+ };
+
+ if (returned) context.track('subscription_success', { type: tier });
+ if (returned || licensed()) void confirm();
+
+ const state = (): PlanState => {
+ if (confirming()) return { t: 'confirming' };
+ if (returned || licensed())
+ return { t: 'continue', stillWaiting: stillWaiting() };
+ return { t: 'offer' };
+ };
+
+ return { state, confirm };
+}
diff --git a/apps/web/src/features/onboarding/primitives/signup-journey.ts b/apps/web/src/features/onboarding/primitives/signup-journey.ts
new file mode 100644
index 0000000000..1c5bc9aeee
--- /dev/null
+++ b/apps/web/src/features/onboarding/primitives/signup-journey.ts
@@ -0,0 +1,47 @@
+import { createSignal } from 'solid-js';
+import type { SignupStep } from '../core/signup-draft';
+import { readSignupDraft, saveSignupDraft } from './flow-storage';
+
+/**
+ * The signed-out slides. Only the step and accent cross the Google sign-up
+ * redirect; the flow resumes at the work step once the account exists.
+ */
+export function createSignupJourney(options: { showingEmail: boolean }) {
+ const draft = readSignupDraft();
+ const [step, setStep] = createSignal<SignupStep>(
+ options.showingEmail ? 'work' : (draft?.step ?? 'welcome')
+ );
+ const [accent, setAccent] = createSignal(draft?.accent);
+ const [connecting, setConnecting] = createSignal(false);
+ const [error, setError] = createSignal<string>();
+
+ /** Show `next`; moving between slides drops any pending sign-up. */
+ const commit = (next: SignupStep) => {
+ saveSignupDraft({ step: next, accent: accent() });
+ setStep(next);
+ };
+
+ const connectGoogle = async (startSignup: () => Promise<void>) => {
+ if (connecting()) return;
+ saveSignupDraft({ step: 'work', accent: accent(), authenticating: true });
+ setConnecting(true);
+ setError();
+ try {
+ await startSignup();
+ } catch {
+ setError("Couldn't open Google. Please try again.");
+ } finally {
+ setConnecting(false);
+ }
+ };
+
+ return {
+ step,
+ accent,
+ setAccent,
+ commit,
+ connecting,
+ error,
+ connectGoogle,
+ };
+}
diff --git a/apps/web/src/features/onboarding/primitives/team-step.ts b/apps/web/src/features/onboarding/primitives/team-step.ts
new file mode 100644
index 0000000000..5296330c94
--- /dev/null
+++ b/apps/web/src/features/onboarding/primitives/team-step.ts
@@ -0,0 +1,157 @@
+import { createEffect, createSignal } from 'solid-js';
+import type {
+ Loadable,
+ OnboardingContext,
+ OnboardingRecord,
+ TeamDirectorySource,
+ TeamInvite,
+} from '../context/onboarding-context';
+import {
+ deriveTeamName,
+ prefillableTeammates,
+ removeInviteSlot,
+ validInviteEmails,
+} from '../core/team';
+
+/** What the team step offers, in priority order. */
+export type TeamStepState =
+ | { t: 'loading' }
+ | { t: 'error' }
+ /** Already a member: auto-joined by domain, or just created/joined here. */
+ | { t: 'on-team'; name: string }
+ | { t: 'invites'; invites: readonly TeamInvite[] }
+ | { t: 'create' };
+
+export function createTeamStep(
+ context: Pick<OnboardingContext, 'joinTeam' | 'track'>,
+ directory: TeamDirectorySource
+) {
+ const [joining, setJoining] = createSignal(false);
+
+ const state = (): TeamStepState => {
+ const teams = directory.teams();
+ const invites = directory.invites();
+ if (teams.t === 'error' || invites.t === 'error') return { t: 'error' };
+ if (teams.t === 'loading' || invites.t === 'loading')
+ return { t: 'loading' };
+ const team = teams.value[0];
+ if (team) return { t: 'on-team', name: team.name };
+ if (invites.value.length > 0)
+ return { t: 'invites', invites: invites.value };
+ return { t: 'create' };
+ };
+
+ // 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(() => {
+ const teams = directory.teams();
+ if (membershipReported || teams.t !== 'ready') return;
+ membershipReported = true;
+ if (teams.value.length > 0)
+ context.track('onboarding_v4_team', { action: 'already_on_team' });
+ });
+
+ const join = async (inviteId: string) => {
+ if (joining()) return;
+ setJoining(true);
+ try {
+ await context.joinTeam(inviteId);
+ context.track('onboarding_v4_team', { action: 'joined_invite' });
+ } catch {
+ // The capability reports its own failure; the invite stays offered.
+ } finally {
+ setJoining(false);
+ }
+ };
+
+ return { state, joining, join, retry: directory.retry };
+}
+
+/** The create form's prefill, once contacts and the domain suggestion settle. */
+export type TeamFormSeed = { domain: string | undefined; prefilled: string[] };
+
+export function teamFormSeed(input: {
+ record: Loadable<OnboardingRecord>;
+ contacts: Loadable<readonly string[]>;
+ ownEmail: string | undefined;
+}): TeamFormSeed | undefined {
+ // Settled, not succeeded: an errored source opens the plain form.
+ if (input.record.t === 'loading' || input.contacts.t === 'loading') return;
+ const domain =
+ input.record.t === 'ready'
+ ? input.record.value.suggestedTeamDomain
+ : undefined;
+ return {
+ domain,
+ prefilled: prefillableTeammates({
+ contacts: input.contacts.t === 'ready' ? input.contacts.value : [],
+ domain,
+ ownEmail: input.ownEmail,
+ }),
+ };
+}
+
+/**
+ * The create-team form, initialized once from its seed so the name and invite
+ * rows stay user-owned. Same-domain teammates are pre-added rather than
+ * offered: removing a row is how the user opts one out.
+ */
+export function createTeamForm(
+ context: Pick<OnboardingContext, 'createTeam' | 'track'>,
+ seed: TeamFormSeed,
+ options: { ownEmail: string | undefined; onCreated: () => void }
+) {
+ const [name, setName] = createSignal(
+ seed.domain ? deriveTeamName(seed.domain) : ''
+ );
+ const [slots, setSlots] = createSignal<string[]>(
+ seed.prefilled.length > 0 ? [...seed.prefilled, ''] : ['', '']
+ );
+ const [pending, setPending] = createSignal(false);
+
+ const invites = () => validInviteEmails(slots(), options.ownEmail);
+ const canCreate = () => name().trim().length > 0 && !pending();
+
+ const create = async () => {
+ if (!canCreate()) return;
+ const sent = invites();
+ setPending(true);
+ try {
+ await context.createTeam({ name: name().trim(), invites: sent });
+ } catch {
+ // The capability reports its own failure; keep the form intact.
+ return;
+ } finally {
+ setPending(false);
+ }
+ const kept = new Set(sent);
+ context.track('onboarding_v4_team', {
+ action: 'created',
+ invites_sent: sent.length,
+ invites_prefilled: seed.prefilled.length,
+ invites_removed: seed.prefilled.filter((address) => !kept.has(address))
+ .length,
+ used_domain_suggestion: seed.domain !== undefined,
+ });
+ options.onCreated();
+ };
+
+ return {
+ name,
+ setName,
+ slots,
+ setSlot: (index: number, value: string) =>
+ setSlots((current) =>
+ current.map((slot, i) => (i === index ? value : slot))
+ ),
+ removeSlot: (index: number) =>
+ setSlots((current) => removeInviteSlot(current, index)),
+ addSlot: () => setSlots((current) => [...current, '']),
+ invites,
+ pending,
+ canCreate,
+ suggested: seed.prefilled.length > 0,
+ create,
+ };
+}
diff --git a/apps/web/src/features/onboarding/primitives/workspace-accent.ts b/apps/web/src/features/onboarding/primitives/workspace-accent.ts
new file mode 100644
index 0000000000..9da54fe3f8
--- /dev/null
+++ b/apps/web/src/features/onboarding/primitives/workspace-accent.ts
@@ -0,0 +1,15 @@
+import { makePersisted } from '@solid-primitives/storage';
+import { createSignal } from 'solid-js';
+import { workspaceAccentNamed } from '../core/workspace-accent';
+
+/** The workspace accent follows the user between the introductory slides. */
+export function createWorkspaceAccent() {
+ const [appearance, setAppearance] = makePersisted(
+ createSignal({ color: 'Mint' }),
+ { name: 'macro-workspace-intro-appearance' }
+ );
+ return {
+ accent: () => workspaceAccentNamed(appearance().color),
+ select: (name: string) => setAppearance({ color: name }),
+ };
+}
diff --git a/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts b/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts
new file mode 100644
index 0000000000..e94a4760cf
--- /dev/null
+++ b/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts
@@ -0,0 +1,256 @@
+import type { PaidPlanTier } from '@app/features/paywall/plans';
+import { createSignal } from 'solid-js';
+import { createStore, produce, unwrap } from 'solid-js/store';
+import type {
+ InviteOffer,
+ Loadable,
+ OnboardingContext,
+ OnboardingRecord,
+ Team,
+ TeamInvite,
+ Tool,
+ ViewerState,
+} from '../context/onboarding-context';
+import type { EmailAccount } from '../core/email-accounts';
+
+/** Everything the fake backend knows. Plain JSON, so a harness can persist it. */
+export type FakeOnboardingWorld = {
+ viewer: {
+ id: string;
+ email: string;
+ tutorialComplete: boolean;
+ licensed: boolean;
+ } | null;
+ emailAccounts: EmailAccount[];
+ /** Addresses the next inbox connects link, in order. */
+ inboxesToConnect: string[];
+ record: OnboardingRecord;
+ teams: Team[];
+ invites: TeamInvite[];
+ contacts: string[];
+ catalog: Tool[];
+ connectedTools: string[];
+ githubStars: number | undefined;
+ inviteOffer: InviteOffer | null;
+ /** License refreshes left before the Stripe webhook lands; undefined when none is pending. */
+ webhookPollsRemaining: number | undefined;
+ /** How many refreshes a checkout's webhook takes to land. */
+ webhookDelayPolls: number;
+ accent: string | undefined;
+ /** Capabilities that fail, with the message they report. */
+ failures: Partial<
+ Record<
+ | 'emailAccounts'
+ | 'teams'
+ | 'catalog'
+ | 'createTeam'
+ | 'joinTeam'
+ | 'checkout'
+ | 'completion',
+ string
+ >
+ >;
+};
+
+export type FakeEvent = { event: string; data: unknown };
+
+export const FAKE_VIEWER_ID = 'macro|[email protected]';
+
+export function defaultFakeWorld(): FakeOnboardingWorld {
+ return {
+ viewer: {
+ id: FAKE_VIEWER_ID,
+ email: '[email protected]',
+ tutorialComplete: false,
+ licensed: false,
+ },
+ emailAccounts: [],
+ inboxesToConnect: ['[email protected]', '[email protected]'],
+ record: { status: 'active', suggestedTeamDomain: 'acme.com' },
+ teams: [],
+ invites: [],
+ catalog: ['Linear', 'Notion', 'GitHub', 'Slack', 'Figma', 'HubSpot'].map(
+ (name) => ({ slug: name.toLowerCase(), name, iconUrl: null })
+ ),
+ connectedTools: [],
+ githubStars: 12_345,
+ inviteOffer: null,
+ webhookPollsRemaining: undefined,
+ webhookDelayPolls: 1,
+ accent: undefined,
+ failures: {},
+ };
+}
+
+/**
+ * An in-memory onboarding backend behind the real contract. `onChange` lets a
+ * harness persist the world; `roundTrip` models the inbox OAuth redirect by
+ * applying the change and then, say, reloading.
+ */
+export function createFakeOnboarding(
+ overrides: Partial<FakeOnboardingWorld> = {},
+ options: {
+ onChange?: (world: FakeOnboardingWorld) => void;
+ roundTrip?: (apply: () => void) => Promise<void>;
+ checkoutUrl?: (tier: PaidPlanTier) => string;
+ } = {}
+) {
+ const [world, setWorld] = createStore<FakeOnboardingWorld>({
+ ...defaultFakeWorld(),
+ ...overrides,
+ });
+ const [events, setEvents] = createSignal<FakeEvent[]>([]);
+ const [notifications, setNotifications] = createSignal<string[]>([]);
+ const [calls, setCalls] = createSignal<string[]>([]);
+
+ const update = (change: (draft: FakeOnboardingWorld) => void) => {
+ setWorld(produce(change));
+ options.onChange?.(structuredClone(unwrap(world)));
+ };
+ const call = (name: string) => setCalls((list) => [...list, name]);
+ const roundTrip = options.roundTrip ?? (async (apply) => apply());
+ const fail = (key: keyof FakeOnboardingWorld['failures']) => {
+ const message = world.failures[key];
+ if (message === undefined) return;
+ throw new Error(message);
+ };
+ const loadable = <T>(
+ failure: keyof FakeOnboardingWorld['failures'],
+ value: () => T
+ ): Loadable<T> =>
+ world.failures[failure] !== undefined
+ ? { t: 'error' }
+ : { t: 'ready', value: value() };
+
+ const viewerState = (): ViewerState =>
+ world.viewer
+ ? { t: 'signed-in', viewer: { ...world.viewer } }
+ : { t: 'signed-out' };
+
+ const context: OnboardingContext = {
+ viewer: viewerState,
+ refreshViewer: async () => {
+ call('refreshViewer');
+ const remaining = world.webhookPollsRemaining;
+ if (remaining !== undefined)
+ update((draft) => {
+ draft.webhookPollsRemaining =
+ remaining > 1 ? remaining - 1 : undefined;
+ if (remaining <= 1 && draft.viewer) draft.viewer.licensed = true;
+ });
+ return viewerState();
+ },
+ createOnboardingRecord: () => () => ({ t: 'ready', value: world.record }),
+ createEmailAccounts: () => ({
+ accounts: () => loadable('emailAccounts', () => world.emailAccounts),
+ refresh: async () => {},
+ }),
+ connectInbox: () => {
+ call('connectInbox');
+ return roundTrip(() =>
+ update((draft) => {
+ const address = draft.inboxesToConnect.shift();
+ if (!address) return;
+ draft.emailAccounts.push({
+ address,
+ isPrimary: draft.emailAccounts.length === 0,
+ ownerId: draft.viewer?.id ?? FAKE_VIEWER_ID,
+ });
+ })
+ );
+ },
+ createToolCatalog: () => {
+ const [search, setSearch] = createSignal('');
+ return {
+ search,
+ setSearch,
+ entries: () =>
+ world.failures.catalog !== undefined
+ ? []
+ : world.catalog.filter((tool) =>
+ tool.name.toLowerCase().includes(search().trim().toLowerCase())
+ ),
+ fetching: () => false,
+ failed: () => world.failures.catalog !== undefined,
+ hasMore: () => false,
+ loadMore: () => {},
+ retry: () => call('retryCatalog'),
+ };
+ },
+ createConnectedTools: () => () => new Set(world.connectedTools),
+ // Pipedream's hosted connect runs in an iframe, so no page round-trip.
+ connectTool: async (tool) => {
+ call(`connectTool:${tool.slug}`);
+ update((draft) => {
+ draft.connectedTools.push(tool.slug);
+ });
+ },
+ createTeamDirectory: () => ({
+ teams: () => loadable('teams', () => world.teams),
+ invites: () => loadable('teams', () => world.invites),
+ contacts: () => ({ t: 'ready', value: world.contacts }),
+ retry: () => call('retryTeams'),
+ }),
+ createTeam: async ({ name, invites }) => {
+ call(`createTeam:${name}:${invites.join(',')}`);
+ fail('createTeam');
+ update((draft) => {
+ draft.teams = [{ name }];
+ });
+ },
+ joinTeam: async (inviteId) => {
+ call(`joinTeam:${inviteId}`);
+ fail('joinTeam');
+ update((draft) => {
+ const invite = draft.invites.find((item) => item.id === inviteId);
+ draft.invites = draft.invites.filter((item) => item.id !== inviteId);
+ if (invite) draft.teams = [{ name: `${invite.invitedBy}'s team` }];
+ });
+ },
+ createInviteOffer: () => () => ({ t: 'ready', value: world.inviteOffer }),
+ startCheckout: async (tier, terms) => {
+ call(`startCheckout:${tier}:${terms}`);
+ fail('checkout');
+ update((draft) => {
+ draft.webhookPollsRemaining = draft.webhookDelayPolls;
+ });
+ return (
+ options.checkoutUrl?.(tier) ?? `https://checkout.stripe.test/${tier}`
+ );
+ },
+ completeOnboarding: async ({ skipped }) => {
+ call(skipped ? 'completeOnboarding:skipped' : 'completeOnboarding');
+ if (world.failures.completion !== undefined) return { t: 'failed' };
+ update((draft) => {
+ draft.record.status = 'completed';
+ if (draft.viewer) draft.viewer.tutorialComplete = true;
+ });
+ return { t: 'completed' };
+ },
+ repairTutorial: async () => {
+ call('repairTutorial');
+ update((draft) => {
+ if (draft.viewer) draft.viewer.tutorialComplete = true;
+ });
+ },
+ applyAccent: (color) => {
+ call(`applyAccent:${color}`);
+ update((draft) => {
+ draft.accent = color;
+ });
+ },
+ createGithubStars: () => () => world.githubStars,
+ track: (event, data) => setEvents((list) => [...list, { event, data }]),
+ notifyFailure: (message) => setNotifications((list) => [...list, message]),
+ };
+
+ return {
+ context,
+ world,
+ update,
+ events,
+ notifications,
+ calls,
+ };
+}
diff --git a/apps/web/src/features/onboarding/tests/invite-offer-stub.tsx b/apps/web/src/features/onboarding/tests/invite-offer-stub.tsx
new file mode 100644
index 0000000000..602dc779d1
--- /dev/null
+++ b/apps/web/src/features/onboarding/tests/invite-offer-stub.tsx
@@ -0,0 +1,20 @@
+import type { InviteOfferSlot } from '../views/plan-step';
+
+/** Stands in for the gtm-invite panel, which needs the app's analytics and queries. */
+export const renderInviteOfferStub: InviteOfferSlot = (offer, actions) => (
+ <section aria-label="Invite offer">
+ <h1>
+ Your first {offer.freeMonths} months are free, {offer.firstName}.
+ </h1>
+ <button
+ type="button"
+ disabled={actions.finishing()}
+ onClick={actions.onClaim}
+ >
+ Claim your free months
+ </button>
+ <button type="button" onClick={actions.onContinueFree}>
+ Continue as Guest instead
+ </button>
+ </section>
+);
diff --git a/apps/web/src/features/onboarding/tests/render.tsx b/apps/web/src/features/onboarding/tests/render.tsx
new file mode 100644
index 0000000000..09dbfa9b36
--- /dev/null
+++ b/apps/web/src/features/onboarding/tests/render.tsx
@@ -0,0 +1,26 @@
+import { render } from '@solidjs/testing-library';
+import type { JSX } from 'solid-js';
+import { vi } from 'vitest';
+import { OnboardingProvider } from '../context/onboarding-context';
+import {
+ createFakeOnboarding,
+ type FakeOnboardingWorld,
+} from './fake-onboarding-context';
+
+/** Reduced motion skips the WAAPI handoffs jsdom can't run. */
+export function stubOnboardingBrowser() {
+ vi.stubGlobal('matchMedia', () => ({ matches: true }));
+ HTMLElement.prototype.scrollTo = vi.fn();
+}
+
+/** Render `ui` under a fake onboarding backend seeded with `world`. */
+export function renderWithFakeOnboarding(
+ ui: () => JSX.Element,
+ world: Partial<FakeOnboardingWorld> = {}
+) {
+ const fake = createFakeOnboarding(world);
+ const result = render(() => (
+ <OnboardingProvider value={fake.context}>{ui()}</OnboardingProvider>
+ ));
+ return { ...result, fake };
+}
diff --git a/apps/web/src/features/onboarding/use-onboarding-checkout.test.ts b/apps/web/src/features/onboarding/use-onboarding-checkout.test.ts
deleted file mode 100644
index a00a74bcab..0000000000
--- a/apps/web/src/features/onboarding/use-onboarding-checkout.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * @vitest-environment jsdom
- */
-
-import { describe, expect, it } from 'vitest';
-
-import { onboardingCheckoutArgs } from './use-onboarding-checkout';
-
-describe('onboardingCheckoutArgs', () => {
- it('returns both checkout legs to the onboarding flow with the plan', () => {
- expect(onboardingCheckoutArgs('premium')).toEqual({
- successUrl: `${window.location.origin}/app/onboarding?subscriptionSuccess=true&type=premium`,
- cancelUrl: `${window.location.origin}/app/onboarding?subscriptionCancel=true`,
- plan: 'premium',
- });
- });
-
- it('carries the purchased tier back on the success leg', () => {
- const args = onboardingCheckoutArgs('max');
- expect(args.plan).toBe('max');
- expect(args.successUrl).toBe(
- `${window.location.origin}/app/onboarding?subscriptionSuccess=true&type=max`
- );
- expect(args.cancelUrl).toBe(
- `${window.location.origin}/app/onboarding?subscriptionCancel=true`
- );
- });
-});
diff --git a/apps/web/src/features/onboarding/use-onboarding-checkout.ts b/apps/web/src/features/onboarding/use-onboarding-checkout.ts
deleted file mode 100644
index b15c58f941..0000000000
--- a/apps/web/src/features/onboarding/use-onboarding-checkout.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
-import type { PaidPlanTier } from '@app/features/paywall/plans';
-import {
- type CreateCheckoutSessionArgs,
- useCreateCheckoutSessionMutation,
-} from '@queries/auth';
-import { useMutation } from '@tanstack/solid-query';
-
-const PENDING_TEAM_KEY = 'onboarding_pending_team';
-
-interface PendingTeamInfo {
- name: string;
- members: Array<{ email: string; tier: PaidPlanTier }>;
-}
-
-interface OnboardingCheckoutArgs {
- tier: PaidPlanTier;
-}
-
-interface OnboardingCheckoutResult {
- checkoutUrl: string;
-}
-
-/**
- * The checkout request for a plan bought during onboarding. Both legs of the
- * Stripe round-trip return to the onboarding flow: the flow is still
- * incomplete during checkout, so success and cancel land back on the plan
- * step (restored from sessionStorage), which reads the query params to show
- * the paid or cancelled state.
- */
-export function onboardingCheckoutArgs(
- tier: PaidPlanTier
-): CreateCheckoutSessionArgs {
- const onboardingUrl = `${window.location.origin}${ROUTER_BASE_CONCAT}onboarding`;
- return {
- successUrl: `${onboardingUrl}?subscriptionSuccess=true&type=${tier}`,
- cancelUrl: `${onboardingUrl}?subscriptionCancel=true`,
- plan: tier,
- };
-}
-
-// Pending team info is saved to localStorage before checkout redirect,
-// then retrieved and used to create the team after successful payment return.
-export function savePendingTeam(team: PendingTeamInfo): void {
- localStorage.setItem(PENDING_TEAM_KEY, JSON.stringify(team));
-}
-
-export function getPendingTeam(): PendingTeamInfo | null {
- const stored = localStorage.getItem(PENDING_TEAM_KEY);
- if (!stored) return null;
- try {
- return JSON.parse(stored) as PendingTeamInfo;
- } catch {
- return null;
- }
-}
-
-export function clearPendingTeam(): void {
- localStorage.removeItem(PENDING_TEAM_KEY);
-}
-
-export function useOnboardingCheckoutMutation(callbacks?: {
- onSuccess?: (result: OnboardingCheckoutResult) => void;
- onError?: (error: Error) => void;
-}) {
- const checkout = useCreateCheckoutSessionMutation();
- return useMutation(() => ({
- mutationFn: async (
- args: OnboardingCheckoutArgs
- ): Promise<OnboardingCheckoutResult> => ({
- checkoutUrl: await checkout.mutateAsync(
- onboardingCheckoutArgs(args.tier)
- ),
- }),
- onSuccess: callbacks?.onSuccess,
- onError: callbacks?.onError,
- }));
-}
diff --git a/apps/web/src/features/onboarding/views/email-step.tsx b/apps/web/src/features/onboarding/views/email-step.tsx
new file mode 100644
index 0000000000..b39ed46c47
--- /dev/null
+++ b/apps/web/src/features/onboarding/views/email-step.tsx
@@ -0,0 +1,34 @@
+import { GoogleAccountsStep } from '../components/google-accounts-step';
+import { useOnboardingContext } from '../context/onboarding-context';
+import { createEmailAccounts } from '../primitives/email-accounts';
+
+/** 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: {
+ mode: 'work' | 'personal';
+ onContinue: () => void;
+ onSkip: () => void;
+}) {
+ const context = useOnboardingContext();
+ const inboxes = createEmailAccounts(context, context.createEmailAccounts());
+ return (
+ <GoogleAccountsStep
+ mode={props.mode}
+ accountEmail={inboxes.primary()?.address}
+ workConnected={inboxes.primary() !== undefined}
+ personalEmail={inboxes.secondary()?.address}
+ connecting={inboxes.connecting()}
+ loading={inboxes.accounts().t === 'loading'}
+ error={
+ inboxes.accounts().t === 'error'
+ ? "Couldn't load your connected accounts."
+ : undefined
+ }
+ onRetry={inboxes.retry}
+ onConnectWork={() => void inboxes.connect('work')}
+ onConnectPersonal={() => void inboxes.connect('personal')}
+ onContinue={props.onContinue}
+ onSkip={props.onSkip}
+ />
+ );
+}
diff --git a/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx b/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx
new file mode 100644
index 0000000000..fbdfc3b5d1
--- /dev/null
+++ b/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx
@@ -0,0 +1,257 @@
+import { cleanup, fireEvent, screen, waitFor } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { CheckoutReturn } from '../core/checkout';
+import type { OnboardingStep } from '../core/steps';
+import {
+ readSavedStep,
+ saveSignupDraft,
+ saveStep,
+} from '../primitives/flow-storage';
+import {
+ FAKE_VIEWER_ID,
+ type FakeOnboardingWorld,
+} from '../tests/fake-onboarding-context';
+import { renderInviteOfferStub } from '../tests/invite-offer-stub';
+import {
+ renderWithFakeOnboarding,
+ stubOnboardingBrowser,
+} from '../tests/render';
+import { OnboardingFlowView } from './onboarding-flow-view';
+
+beforeEach(() => {
+ sessionStorage.clear();
+ localStorage.clear();
+ stubOnboardingBrowser();
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+function setup(
+ options: {
+ world?: Partial<FakeOnboardingWorld>;
+ resume?: OnboardingStep;
+ next?: string;
+ checkoutReturn?: CheckoutReturn;
+ } = {}
+) {
+ if (options.resume) saveStep(FAKE_VIEWER_ID, options.resume);
+ const navigate = vi.fn();
+ const redirect = vi.fn();
+ const signedOut = vi.fn();
+ const { fake } = renderWithFakeOnboarding(
+ () => (
+ <OnboardingFlowView
+ next={options.next}
+ checkoutReturn={options.checkoutReturn}
+ onNavigate={navigate}
+ onRedirect={redirect}
+ onSignedOut={signedOut}
+ renderInviteOffer={renderInviteOfferStub}
+ />
+ ),
+ options.world
+ );
+ return { fake, navigate, redirect, signedOut };
+}
+
+const heading = (name: string | RegExp) =>
+ screen.findByRole('heading', { name, level: 1 });
+const click = (name: string | RegExp) =>
+ fireEvent.click(screen.getByRole('button', { name }));
+
+describe('onboarding flow', () => {
+ it('walks every step and finishes as a Guest', async () => {
+ const { fake, navigate } = setup({ next: '/channel/launch' });
+
+ await heading('Create your workspace');
+ fireEvent.click(screen.getByRole('radio', { name: 'Sky' }));
+ click('Get started');
+ expect(fake.calls()).toContain('applyAccent:#7abde5');
+
+ await heading('Which features do you want to try first?');
+ click('Continue');
+ await heading('A workspace built to earn your trust.');
+ click('Continue');
+
+ await heading(/Connect your work/);
+ click('Connect work email');
+ await screen.findByText('[email protected]');
+ click('Continue');
+
+ await heading(/Add your personal/);
+ click('Skip for now');
+
+ await heading('Connect your tools.');
+ click('Connect Linear');
+ await screen.findByRole('button', { name: 'Connected to Linear' });
+ click('Continue');
+
+ await heading('Built for teams.');
+ expect(screen.getByDisplayValue('Acme')).toBeTruthy();
+ expect(screen.getByDisplayValue('[email protected]')).toBeTruthy();
+ click('Create team & invite 2');
+ await waitFor(() =>
+ expect(fake.calls()).toContain(
+ )
+ );
+
+ await heading('Free Claude & GPT for 30 days.');
+ // The scroll cue and the comparison share a label; the comparison's CTA finishes.
+ const guest = screen.getAllByRole('button', { name: 'Continue as Guest' });
+ fireEvent.click(guest[guest.length - 1]);
+
+ await waitFor(() =>
+ expect(navigate).toHaveBeenCalledWith('/channel/launch')
+ );
+ // Completing flips the viewer to complete; the flow must not leave twice.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(navigate).toHaveBeenCalledOnce();
+ expect(fake.world.viewer?.tutorialComplete).toBe(true);
+ expect(fake.events()).toContainEqual({
+ event: 'onboarding_v4_completed',
+ data: {
+ plan: 'free',
+ plan_skipped: false,
+ emails_connected: 1,
+ connectors_connected: ['linear'],
+ },
+ });
+ expect(
+ fake
+ .events()
+ .filter((e) => e.event === 'onboarding_v4_step')
+ .map((e) => e.data)
+ ).toContainEqual({ step: 'personal', index: 4, state: 'skipped' });
+ });
+
+ it('skips the personal account when the work account was skipped', async () => {
+ setup({ resume: 'work' });
+ await heading(/Connect your work/);
+ click('Skip for now');
+ await heading('Connect your tools.');
+ });
+
+ it('resumes the saved step, and Back returns to the previous one', async () => {
+ setup({ resume: 'team' });
+ await heading('Built for teams.');
+ click('Back to previous step');
+ await heading('Connect your tools.');
+ expect(readSavedStep(FAKE_VIEWER_ID)).toBe('tools');
+ });
+
+ it('resumes at the work step after Google sign-up and applies the chosen accent', async () => {
+ saveSignupDraft({ step: 'work', accent: '#f77d67', authenticating: true });
+ const { fake } = setup();
+ await heading(/Connect your work/);
+ expect(fake.world.accent).toBe('#f77d67');
+ });
+
+ it('returns from checkout to the plan step and finishes once the license lands', async () => {
+ const { navigate } = setup({
+ resume: 'welcome',
+ checkoutReturn: { t: 'success', tier: 'premium' },
+ world: { webhookPollsRemaining: 1 },
+ });
+ await heading('Free Claude & GPT for 30 days.');
+ await waitFor(
+ () => expect(navigate).toHaveBeenCalledWith('/getting-started'),
+ {
+ timeout: 3_000,
+ }
+ );
+ });
+
+ it('starts hosted checkout from the trial offer', async () => {
+ const { redirect } = setup({ resume: 'plan' });
+ await heading('Free Claude & GPT for 30 days.');
+ click('Start 30 day trial');
+ await waitFor(() =>
+ expect(redirect).toHaveBeenCalledWith(
+ 'https://checkout.stripe.test/premium'
+ )
+ );
+ });
+
+ it('joins a pending team invite instead of creating a team', async () => {
+ const { fake } = setup({
+ resume: 'team',
+ world: { invites: [{ id: 'inv-1', invitedBy: 'Grace' }] },
+ });
+ await screen.findByText('Grace invited you to their team');
+ click('Join');
+ await screen.findByText("You're on Grace's team");
+ expect(fake.events()).toContainEqual({
+ event: 'onboarding_v4_team',
+ data: { action: 'joined_invite' },
+ });
+ });
+
+ it('confirms an existing team membership', async () => {
+ const { fake } = setup({
+ resume: 'team',
+ world: { teams: [{ name: 'Acme' }] },
+ });
+ await screen.findByText("You're on Acme");
+ expect(fake.events()).toContainEqual({
+ event: 'onboarding_v4_team',
+ data: { action: 'already_on_team' },
+ });
+ });
+
+ it('sends a signed-out visitor to sign in', async () => {
+ const { signedOut } = setup({ world: { viewer: null } });
+ await waitFor(() => expect(signedOut).toHaveBeenCalled());
+ });
+
+ it('leaves immediately when onboarding is already complete', async () => {
+ const { navigate } = setup({
+ next: '/md/doc',
+ world: {
+ viewer: {
+ id: FAKE_VIEWER_ID,
+ email: '[email protected]',
+ tutorialComplete: true,
+ licensed: false,
+ },
+ },
+ });
+ await waitFor(() => expect(navigate).toHaveBeenCalledWith('/md/doc'));
+ });
+
+ it('repairs the tutorial flag when the server already completed onboarding', async () => {
+ const { fake, navigate } = setup({
+ world: {
+ record: { status: 'completed', suggestedTeamDomain: undefined },
+ },
+ });
+ await waitFor(() => expect(fake.calls()).toContain('repairTutorial'));
+ await waitFor(() => expect(navigate).toHaveBeenCalled());
+ });
+
+ it('offers staff a Bypass out of any step', async () => {
+ // Progress is saved per user, so staff start fresh on the first slide.
+ const { fake, navigate } = setup({
+ world: {
+ viewer: {
+ id: 'macro|[email protected]',
+ email: '[email protected]',
+ tutorialComplete: false,
+ licensed: false,
+ },
+ },
+ });
+ await heading('Create your workspace');
+ click('Bypass');
+ await waitFor(() => expect(navigate).toHaveBeenCalledWith('/home'));
+ expect(fake.calls()).toContain('completeOnboarding:skipped');
+ });
+
+ it('hides Bypass from everyone else', async () => {
+ setup({ resume: 'team' });
+ await heading('Built for teams.');
+ expect(screen.queryByRole('button', { name: 'Bypass' })).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/onboarding/views/onboarding-flow-view.tsx b/apps/web/src/features/onboarding/views/onboarding-flow-view.tsx
new file mode 100644
index 0000000000..9988a510e9
--- /dev/null
+++ b/apps/web/src/features/onboarding/views/onboarding-flow-view.tsx
@@ -0,0 +1,200 @@
+import LogoIcon from '@icon/macro-logo.svg';
+import { createEffect, Match, onCleanup, Show, Switch } from 'solid-js';
+import { BypassButton } from '../components/bypass-button';
+import {
+ animateStepChange,
+ focusStepHeading,
+} from '../components/motion/step-change';
+import { OnboardingShell } from '../components/onboarding-shell';
+import { PlanComparison } from '../components/plan-comparison';
+import { OnboardingTrustDetails } from '../components/trust-details';
+import { useOnboardingContext } from '../context/onboarding-context';
+import type { CheckoutReturn } from '../core/checkout';
+import { canBypassOnboarding } from '../core/staff';
+import {
+ isStoryStep,
+ type OnboardingStep,
+ previousOnboardingStep,
+ type StepOutcome,
+} from '../core/steps';
+import { createFlowFinish } from '../primitives/flow-finish';
+import { createOnboardingFlow } from '../primitives/onboarding-flow';
+import { EmailStep } from './email-step';
+import { type InviteOfferSlot, PlanStep } from './plan-step';
+import { StoryStageView } from './story-stage-view';
+import { TeamStep } from './team-step';
+import { ToolsStep } from './tools-step';
+
+function StepFallback() {
+ return (
+ <div
+ role="status"
+ aria-label="Loading setup"
+ class="flex justify-center py-10"
+ >
+ <LogoIcon class="size-6 animate-pulse text-ink/30" />
+ </div>
+ );
+}
+
+/** The signed-in onboarding steps, from the workspace slides to the trial offer. */
+export function OnboardingFlowView(props: {
+ /** A deep link to land on after onboarding. */
+ next: string | undefined;
+ checkoutReturn: CheckoutReturn | undefined;
+ onNavigate: (target: string) => void;
+ /** Leaves the app for hosted checkout. */
+ onRedirect: (url: string) => void;
+ onSignedOut: () => void;
+ /** Shown instead of the trial to an account holding an invite promotion. */
+ renderInviteOffer: InviteOfferSlot;
+}) {
+ const context = useOnboardingContext();
+ const emailAccounts = context.createEmailAccounts();
+ // Read once for the completion rollup; only the tools step polls.
+ const connectedTools = context.createConnectedTools({ poll: false });
+ const record = context.createOnboardingRecord();
+
+ const finish = createFlowFinish(context, {
+ next: () => props.next,
+ onNavigate: props.onNavigate,
+ onRedirect: props.onRedirect,
+ completionRollup: () => {
+ const accounts = emailAccounts.accounts();
+ return {
+ emails_connected: accounts.t === 'ready' ? accounts.value.length : 0,
+ connectors_connected: [...(connectedTools() ?? [])],
+ };
+ },
+ });
+ const flow = createOnboardingFlow(context, {
+ checkoutReturn: () => props.checkoutReturn,
+ record,
+ signupMethod: () => {
+ const accounts = emailAccounts.accounts();
+ if (accounts.t !== 'ready') return undefined;
+ return accounts.value.length > 0 ? 'google' : 'email_code';
+ },
+ finishing: finish.finishing,
+ });
+
+ // Leaving is the host's decision; the flow only reports why.
+ createEffect(() => {
+ const status = flow.status();
+ if (status.t === 'signed-out') props.onSignedOut();
+ else if (status.t === 'complete') props.onNavigate(finish.afterTarget());
+ });
+
+ let content!: HTMLDivElement;
+ let stopMotion: (() => void) | undefined;
+ onCleanup(() => stopMotion?.());
+
+ const step = () => {
+ const status = flow.status();
+ return status.t === 'active' ? status.step : undefined;
+ };
+ const storyStep = () => {
+ const current = step();
+ return current && isStoryStep(current) ? current : undefined;
+ };
+
+ const goTo = (next: OnboardingStep | undefined) => {
+ const current = step();
+ if (!next || !current || next === current) return;
+ stopMotion?.();
+ stopMotion = animateStepChange(content, current, next, () => {
+ flow.commit(next);
+ queueMicrotask(() => focusStepHeading(content));
+ });
+ };
+ const advance = (outcome: StepOutcome = 'completed') =>
+ goTo(flow.leave(outcome));
+ const viewerEmail = () => {
+ const viewer = context.viewer();
+ return viewer.t === 'signed-in' ? viewer.viewer.email : undefined;
+ };
+ const back = () => {
+ const current = step();
+ const previous = current && previousOnboardingStep(current);
+ return previous && !finish.finishing() ? () => goTo(previous) : undefined;
+ };
+
+ return (
+ <OnboardingShell
+ wide
+ onBack={back()}
+ overlay={
+ <Show when={canBypassOnboarding(viewerEmail()) && step()}>
+ {(current) => (
+ <BypassButton
+ disabled={finish.finishing()}
+ onBypass={() => void finish.bypass(current())}
+ />
+ )}
+ </Show>
+ }
+ explainerLabel={step() === 'plan' ? 'Continue as Guest' : undefined}
+ explainer={
+ step() === 'plan' ? (
+ <PlanComparison
+ disabled={finish.finishing()}
+ onContinueGuest={() => void finish.finishFree()}
+ onBackToPro={() => focusStepHeading(content, true)}
+ />
+ ) : step() === 'security' ||
+ step() === 'work' ||
+ step() === 'personal' ? (
+ <OnboardingTrustDetails
+ topic={step() === 'security' ? 'security' : 'google'}
+ />
+ ) : undefined
+ }
+ >
+ <div ref={content} class="flex flex-col gap-8">
+ <Switch fallback={<StepFallback />}>
+ <Match when={storyStep()}>
+ {(story) => (
+ <StoryStageView
+ step={story()}
+ onNext={() => advance()}
+ onWorkspaceContinue={(color) => {
+ const viewer = context.viewer();
+ if (viewer.t !== 'signed-in') return;
+ context.applyAccent(color, viewer.viewer.id);
+ advance();
+ }}
+ >
+ <ToolsStep onContinue={() => advance()} />
+ </StoryStageView>
+ )}
+ </Match>
+ <Match when={step() === 'work' || step() === 'personal'}>
+ <EmailStep
+ mode={step() === 'personal' ? 'personal' : 'work'}
+ onContinue={() => advance()}
+ onSkip={() => advance('skipped')}
+ />
+ </Match>
+ <Match when={step() === 'team'}>
+ <TeamStep
+ onContinue={() => advance()}
+ onSkip={() => advance('skipped')}
+ />
+ </Match>
+ <Match when={step() === 'plan'}>
+ <PlanStep
+ checkoutReturn={props.checkoutReturn}
+ finishing={finish.finishing()}
+ onStartCheckout={(tier, terms) =>
+ void finish.startPremiumCheckout(tier, terms)
+ }
+ onContinueFree={() => void finish.finishFree()}
+ renderInviteOffer={props.renderInviteOffer}
+ onPremiumPaid={finish.finishPremium}
+ />
+ </Match>
+ </Switch>
+ </div>
+ </OnboardingShell>
+ );
+}
diff --git a/apps/web/src/features/onboarding/views/plan-step.test.tsx b/apps/web/src/features/onboarding/views/plan-step.test.tsx
new file mode 100644
index 0000000000..71376ab5bf
--- /dev/null
+++ b/apps/web/src/features/onboarding/views/plan-step.test.tsx
@@ -0,0 +1,122 @@
+import { cleanup, fireEvent, screen, waitFor } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { CheckoutReturn } from '../core/checkout';
+import type { FakeOnboardingWorld } from '../tests/fake-onboarding-context';
+import { renderInviteOfferStub } from '../tests/invite-offer-stub';
+import { renderWithFakeOnboarding } from '../tests/render';
+import { PlanStep } from './plan-step';
+
+afterEach(cleanup);
+
+function setup(
+ checkoutReturn: CheckoutReturn | undefined,
+ world: Partial<FakeOnboardingWorld> = {}
+) {
+ const checkout = vi.fn();
+ const finish = vi.fn().mockResolvedValue(undefined);
+ const guest = vi.fn();
+ const { fake } = renderWithFakeOnboarding(
+ () => (
+ <PlanStep
+ checkoutReturn={checkoutReturn}
+ finishing={false}
+ onStartCheckout={checkout}
+ onPremiumPaid={finish}
+ onContinueFree={guest}
+ renderInviteOffer={renderInviteOfferStub}
+ />
+ ),
+ world
+ );
+ return { checkout, finish, guest, fake };
+}
+
+describe('live trial checkout', () => {
+ it('starts hosted checkout without collecting payment details locally', () => {
+ const { checkout, finish } = setup(undefined);
+ expect(screen.queryByRole('textbox')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Start 30 day trial' }));
+ expect(checkout).toHaveBeenCalledWith('premium', 'trial');
+ expect(finish).not.toHaveBeenCalled();
+ });
+
+ it('finishes only after the server confirms the license, with the returned tier', async () => {
+ const { finish, checkout, fake } = setup(
+ { t: 'success', tier: 'max' },
+ { webhookPollsRemaining: 2 }
+ );
+ await waitFor(() => expect(finish).toHaveBeenCalledWith('max'), {
+ timeout: 3_000,
+ });
+ expect(fake.calls().filter((c) => c === 'refreshViewer')).toHaveLength(2);
+ expect(fake.events()).toContainEqual({
+ event: 'subscription_success',
+ data: { type: 'max' },
+ });
+ expect(checkout).not.toHaveBeenCalled();
+ });
+
+ it('does not treat a success URL alone as payment confirmation', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ const { finish, fake } = setup({ t: 'success', tier: 'premium' });
+ await vi.runAllTimersAsync();
+ await screen.findByRole('alert');
+ expect(finish).not.toHaveBeenCalled();
+
+ fake.update((draft) => {
+ if (draft.viewer) draft.viewer.licensed = true;
+ });
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Continue to workspace' })
+ );
+ await waitFor(() => expect(finish).toHaveBeenCalledOnce());
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('leaves cancellation retryable without completing onboarding', () => {
+ const { finish } = setup({ t: 'cancelled' });
+ expect(
+ screen.getByRole('button', { name: 'Start 30 day trial' })
+ ).toBeTruthy();
+ expect(finish).not.toHaveBeenCalled();
+ });
+
+ it('lets existing paid members finish without buying again', async () => {
+ const { finish, checkout } = setup(undefined, {
+ viewer: {
+ id: 'macro|[email protected]',
+ email: '[email protected]',
+ tutorialComplete: false,
+ licensed: true,
+ },
+ });
+ await waitFor(() => expect(finish).toHaveBeenCalledWith('premium'));
+ expect(checkout).not.toHaveBeenCalled();
+ });
+
+ it('offers an invite’s free months instead of the trial, with paid terms', () => {
+ const { checkout, guest } = setup(undefined, {
+ inviteOffer: {
+ firstName: 'Ada',
+ freeMonths: 3,
+ linkId: 'link-1',
+ promoCode: 'ADA3',
+ redeemedAt: '2026-10-01T00:00:00Z',
+ },
+ });
+ expect(
+ screen.queryByRole('button', { name: 'Start 30 day trial' })
+ ).toBeNull();
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Claim your free months' })
+ );
+ expect(checkout).toHaveBeenCalledWith('premium', 'invite-offer');
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Continue as Guest instead' })
+ );
+ expect(guest).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/features/onboarding/views/plan-step.tsx b/apps/web/src/features/onboarding/views/plan-step.tsx
new file mode 100644
index 0000000000..d3f576a3c6
--- /dev/null
+++ b/apps/web/src/features/onboarding/views/plan-step.tsx
@@ -0,0 +1,114 @@
+import type { PaidPlanTier } from '@app/features/paywall/plans';
+import { type Accessor, type JSX, Show } from 'solid-js';
+import { match } from 'ts-pattern';
+import { ContinueButton } from '../components/controls';
+import {
+ type InviteOffer,
+ useOnboardingContext,
+} from '../context/onboarding-context';
+import type { CheckoutReturn, CheckoutTerms } from '../core/checkout';
+import { createPlanConfirmation } from '../primitives/plan-confirmation';
+
+/** The host's panel for an invite promotion, shown in place of the trial offer. */
+export type InviteOfferSlot = (
+ offer: InviteOffer,
+ actions: {
+ finishing: Accessor<boolean>;
+ onClaim: () => void;
+ onContinueFree: () => void;
+ }
+) => JSX.Element;
+
+/** Stripe owns payment details. Verify the webhook-updated license before leaving setup. */
+export function PlanStep(props: {
+ checkoutReturn: CheckoutReturn | undefined;
+ finishing: boolean;
+ onStartCheckout: (tier: PaidPlanTier, terms: CheckoutTerms) => void;
+ onPremiumPaid: (tier: PaidPlanTier) => Promise<void>;
+ onContinueFree: () => void;
+ renderInviteOffer: InviteOfferSlot;
+}) {
+ const context = useOnboardingContext();
+ const plan = createPlanConfirmation(context, {
+ checkoutReturn: props.checkoutReturn,
+ onConfirmed: props.onPremiumPaid,
+ });
+ const offer = context.createInviteOffer();
+ // An invite's free months beat the trial, which would replace them.
+ const inviteOffer = () => {
+ const state = offer();
+ return plan.state().t === 'offer' && state.t === 'ready'
+ ? state.value
+ : null;
+ };
+
+ const trialOffer = () => (
+ <section class="mx-auto flex w-full max-w-lg flex-col py-2 sm:py-4">
+ <header class="text-center">
+ <h1
+ tabindex="-1"
+ class="font-[Roboto_Slab_Variable] text-[clamp(1.75rem,8vw,3rem)] font-[315] leading-[1.12] tracking-tight outline-none text-balance"
+ >
+ Free Claude &amp; GPT for 30 days.
+ </h1>
+ <p class="mx-auto mt-6 max-w-[400px] text-sm leading-6 text-ink-muted text-balance sm:text-[15px]">
+ Every feature, every AI model and 1 TB of storage. Your first 30 days
+ are on us, then $40/user/month.
+ </p>
+ </header>
+ <Show
+ when={(() => {
+ const state = plan.state();
+ return state.t === 'continue' && state.stillWaiting;
+ })()}
+ >
+ <p role="alert" class="mt-8 text-center text-sm text-ink-muted">
+ We're still waiting for payment confirmation. Please try again in a
+ moment.
+ </p>
+ </Show>
+ <div class="mt-9">
+ <ContinueButton
+ label={match(plan.state())
+ .with({ t: 'confirming' }, () => 'Confirming your subscription…')
+ .otherwise((state) =>
+ props.finishing
+ ? 'Opening your workspace…'
+ : state.t === 'continue'
+ ? 'Continue to workspace'
+ : 'Start 30 day trial'
+ )}
+ // Until the invite lookup settles, starting a trial could skip it.
+ disabled={
+ plan.state().t === 'confirming' ||
+ props.finishing ||
+ (plan.state().t === 'offer' && offer().t === 'loading')
+ }
+ onClick={() =>
+ plan.state().t === 'offer'
+ ? props.onStartCheckout('premium', 'trial')
+ : void plan.confirm()
+ }
+ />
+ </div>
+ <Show when={plan.state().t === 'offer'}>
+ <p class="mx-auto mt-3 max-w-52 text-center text-xs leading-5 text-ink-extra-muted">
+ <span class="block">$40/user/month, billed monthly</span>
+ <span class="block">after the trial. Cancel anytime.</span>
+ </p>
+ </Show>
+ </section>
+ );
+
+ return (
+ <Show when={inviteOffer()} keyed fallback={trialOffer()}>
+ {(invite) =>
+ props.renderInviteOffer(invite, {
+ finishing: () => props.finishing,
+ onClaim: () => props.onStartCheckout('premium', 'invite-offer'),
+ onContinueFree: props.onContinueFree,
+ })
+ }
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/onboarding/views/signup-journey-view.test.tsx b/apps/web/src/features/onboarding/views/signup-journey-view.test.tsx
new file mode 100644
index 0000000000..ac0d0b4258
--- /dev/null
+++ b/apps/web/src/features/onboarding/views/signup-journey-view.test.tsx
@@ -0,0 +1,92 @@
+import { cleanup, fireEvent, screen } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { readSignupDraft, saveSignupDraft } from '../primitives/flow-storage';
+import {
+ renderWithFakeOnboarding,
+ stubOnboardingBrowser,
+} from '../tests/render';
+import { SignupJourneyView } from './signup-journey-view';
+
+beforeEach(() => {
+ sessionStorage.clear();
+ localStorage.clear();
+ stubOnboardingBrowser();
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+function setup() {
+ const google = vi.fn().mockResolvedValue(undefined);
+ renderWithFakeOnboarding(
+ () => (
+ <SignupJourneyView
+ onGoogle={google}
+ onBackFromEmail={() => {}}
+ showingEmail={false}
+ />
+ ),
+ { viewer: null }
+ );
+ return { google };
+}
+
+describe('sign-up starts before authentication', () => {
+ it('walks through color, interests, and security before starting Google signup', () => {
+ const { google } = setup();
+ expect(
+ screen.getByRole('heading', { name: 'Create your workspace' })
+ ).toBeTruthy();
+ fireEvent.click(screen.getByRole('radio', { name: 'Coral' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Get started' }));
+ expect(
+ screen.getByRole('heading', {
+ name: 'Which features do you want to try first?',
+ })
+ ).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }));
+ expect(
+ screen.getByRole('heading', {
+ name: 'A workspace built to earn your trust.',
+ })
+ ).toBeTruthy();
+ expect(
+ screen.getByRole('link', { name: /12\.3k GitHub stars/ })
+ ).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }));
+ expect(google).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Connect work email' }));
+ expect(google).toHaveBeenCalledOnce();
+ expect(readSignupDraft()).toEqual({
+ step: 'work',
+ accent: '#f77d67',
+ authenticating: true,
+ });
+ });
+
+ it('restores the work-email step after an OAuth return or cancellation', () => {
+ saveSignupDraft({ step: 'work', accent: '#65d8ac', authenticating: true });
+ const { google } = setup();
+ expect(
+ screen.queryByRole('heading', { name: 'Create your workspace' })
+ ).toBeNull();
+ expect(google).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Connect work email' }));
+ expect(google).toHaveBeenCalledOnce();
+ expect(readSignupDraft()?.accent).toBe('#65d8ac');
+ });
+
+ it('clears pending authentication when returning to an earlier step', () => {
+ saveSignupDraft({ step: 'work', accent: '#65d8ac', authenticating: true });
+ setup();
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Back to previous step' })
+ );
+ expect(readSignupDraft()).toEqual({
+ step: 'security',
+ accent: '#65d8ac',
+ authenticating: false,
+ });
+ });
+});
diff --git a/apps/web/src/features/onboarding/views/signup-journey-view.tsx b/apps/web/src/features/onboarding/views/signup-journey-view.tsx
new file mode 100644
index 0000000000..4b18b1c9f2
--- /dev/null
+++ b/apps/web/src/features/onboarding/views/signup-journey-view.tsx
@@ -0,0 +1,116 @@
+import { type JSX, onCleanup, Show } from 'solid-js';
+import { GoogleAccountsStep } from '../components/google-accounts-step';
+import {
+ animateStepChange,
+ focusStepHeading,
+} from '../components/motion/step-change';
+import { OnboardingShell } from '../components/onboarding-shell';
+import { OnboardingTrustDetails } from '../components/trust-details';
+import {
+ nextSignupStep,
+ previousSignupStep,
+ type SignupStep,
+} from '../core/signup-draft';
+import { createSignupJourney } from '../primitives/signup-journey';
+import { StoryStageView } from './story-stage-view';
+
+/** Public opening slides. Authentication happens only at the work-email step. */
+export function SignupJourneyView(props: {
+ /** Starts Google sign-up; on web the page navigates away. */
+ onGoogle: () => Promise<void>;
+ onBackFromEmail: () => void;
+ /** The host's email sign-up form, shown in place of Google when chosen. */
+ emailForm?: JSX.Element;
+ showingEmail: boolean;
+}) {
+ const journey = createSignupJourney({ showingEmail: props.showingEmail });
+ let content!: HTMLDivElement;
+ let stopMotion: (() => void) | undefined;
+ onCleanup(() => stopMotion?.());
+
+ const goTo = (next: SignupStep | undefined) => {
+ const current = journey.step();
+ if (!next || next === current) return;
+ stopMotion?.();
+ stopMotion = animateStepChange(content, current, next, () => {
+ journey.commit(next);
+ queueMicrotask(() => focusStepHeading(content));
+ });
+ };
+ const storyStep = () => {
+ const step = journey.step();
+ return step === 'work' ? undefined : step;
+ };
+
+ return (
+ <OnboardingShell
+ wide
+ onBack={
+ journey.step() === 'welcome'
+ ? undefined
+ : () => {
+ if (props.showingEmail) props.onBackFromEmail();
+ else goTo(previousSignupStep(journey.step()));
+ }
+ }
+ explainer={
+ journey.step() === 'security' || journey.step() === 'work' ? (
+ <OnboardingTrustDetails
+ topic={journey.step() === 'security' ? 'security' : 'google'}
+ />
+ ) : undefined
+ }
+ >
+ <div ref={content} class="flex flex-col gap-8">
+ <Show
+ when={journey.step() === 'work'}
+ fallback={
+ <StoryStageView
+ step={storyStep() ?? 'security'}
+ onNext={() => goTo(nextSignupStep(journey.step()))}
+ onWorkspaceContinue={(color) => {
+ journey.setAccent(color);
+ goTo('vision');
+ }}
+ />
+ }
+ >
+ <Show
+ when={props.showingEmail}
+ fallback={
+ <GoogleAccountsStep
+ mode="work"
+ connecting={journey.connecting() ? 'work' : undefined}
+ error={journey.error()}
+ onConnectWork={() => void journey.connectGoogle(props.onGoogle)}
+ onConnectPersonal={() => {}}
+ />
+ }
+ >
+ <div class="mx-auto flex w-full max-w-sm flex-col gap-8">
+ <h1
+ tabindex="-1"
+ class="text-center font-[Roboto_Slab_Variable] text-3xl font-[315] leading-tight tracking-tight"
+ >
+ Sign up with your work email.
+ </h1>
+ {props.emailForm}
+ </div>
+ </Show>
+ <p class="mx-auto max-w-xs text-center text-xs leading-5 text-ink-extra-muted">
+ Your work email becomes your Macro sign-in. By continuing, you agree
+ to our{' '}
+ <a href="/terms" class="underline underline-offset-2">
+ terms
+ </a>{' '}
+ and{' '}
+ <a href="/privacy" class="underline underline-offset-2">
+ privacy policy
+ </a>
+ .
+ </p>
+ </Show>
+ </div>
+ </OnboardingShell>
+ );
+}
diff --git a/apps/web/src/features/onboarding/views/story-stage-view.tsx b/apps/web/src/features/onboarding/views/story-stage-view.tsx
new file mode 100644
index 0000000000..67d34f2714
--- /dev/null
+++ b/apps/web/src/features/onboarding/views/story-stage-view.tsx
@@ -0,0 +1,29 @@
+import type { JSX } from 'solid-js';
+import { StoryStage } from '../components/story-stage';
+import { useOnboardingContext } from '../context/onboarding-context';
+import type { StoryStep } from '../core/steps';
+import { createWorkspaceAccent } from '../primitives/workspace-accent';
+
+/** The opening slides with the persisted accent and the trust slide's star count. */
+export function StoryStageView(props: {
+ step: StoryStep;
+ onNext: (features?: string[]) => void;
+ onWorkspaceContinue: (color: string) => void;
+ children?: JSX.Element;
+}) {
+ const context = useOnboardingContext();
+ const workspaceAccent = createWorkspaceAccent();
+ const githubStars = context.createGithubStars();
+ return (
+ <StoryStage
+ step={props.step}
+ accent={workspaceAccent.accent()}
+ githubStars={githubStars()}
+ onSelectAccent={workspaceAccent.select}
+ onNext={props.onNext}
+ onWorkspaceContinue={props.onWorkspaceContinue}
+ >
+ {props.children}
+ </StoryStage>
+ );
+}
diff --git a/apps/web/src/features/onboarding/views/team-step.tsx b/apps/web/src/features/onboarding/views/team-step.tsx
new file mode 100644
index 0000000000..e3217fcaaf
--- /dev/null
+++ b/apps/web/src/features/onboarding/views/team-step.tsx
@@ -0,0 +1,131 @@
+import { Match, Show, Switch } from 'solid-js';
+import { ContinueButton, SkipButton } from '../components/controls';
+import {
+ InvitesPanel,
+ OnTeamPanel,
+ TeamLoadError,
+ TeamStatus,
+} from '../components/team-panels';
+import { TeamSetup, TeamSetupFields } from '../components/team-setup';
+import { useOnboardingContext } from '../context/onboarding-context';
+import {
+ createTeamForm,
+ createTeamStep,
+ type TeamFormSeed,
+ teamFormSeed,
+} from '../primitives/team-step';
+
+/** Set up your team: already a member → confirmation, pending invites →
+ * join, otherwise create (with a domain-derived name and same-domain
+ * teammates pre-added to the invite list). */
+export function TeamStep(props: {
+ onContinue: () => void;
+ onSkip: () => void;
+}) {
+ const context = useOnboardingContext();
+ const directory = context.createTeamDirectory();
+ const team = createTeamStep(context, directory);
+ const record = context.createOnboardingRecord();
+ const ownEmail = () => {
+ const viewer = context.viewer();
+ return viewer.t === 'signed-in' ? viewer.viewer.email : undefined;
+ };
+ // Wait for contacts and the domain suggestion so the form mounts once,
+ // fully formed — nothing rewrites the user's rows afterwards.
+ const seed = () =>
+ teamFormSeed({
+ record: record(),
+ contacts: directory.contacts(),
+ ownEmail: ownEmail(),
+ });
+
+ return (
+ <TeamSetup>
+ <Switch>
+ <Match when={team.state().t === 'error'}>
+ <TeamLoadError onRetry={team.retry} />
+ </Match>
+ <Match when={team.state().t === 'loading'}>
+ <TeamStatus message="Loading your team…" />
+ </Match>
+ <Match when={onTeam(team.state())} keyed>
+ {(name) => <OnTeamPanel name={name} onContinue={props.onContinue} />}
+ </Match>
+ <Match when={pendingInvites(team.state())}>
+ {(invites) => (
+ <InvitesPanel
+ invites={invites()}
+ joining={team.joining()}
+ onJoin={(id) => void team.join(id)}
+ onSkip={props.onSkip}
+ />
+ )}
+ </Match>
+ <Match when={team.state().t === 'create'}>
+ <Show
+ when={seed()}
+ keyed
+ fallback={<TeamStatus message="Finding your teammates…" />}
+ >
+ {(ready) => (
+ <TeamForm
+ seed={ready}
+ ownEmail={ownEmail()}
+ onContinue={props.onContinue}
+ onSkip={props.onSkip}
+ />
+ )}
+ </Show>
+ </Match>
+ </Switch>
+ </TeamSetup>
+ );
+}
+
+const onTeam = (
+ state: ReturnType<ReturnType<typeof createTeamStep>['state']>
+) => (state.t === 'on-team' ? state.name : undefined);
+
+const pendingInvites = (
+ state: ReturnType<ReturnType<typeof createTeamStep>['state']>
+) => (state.t === 'invites' ? state.invites : undefined);
+
+function TeamForm(props: {
+ seed: TeamFormSeed;
+ ownEmail: string | undefined;
+ onContinue: () => void;
+ onSkip: () => void;
+}) {
+ const context = useOnboardingContext();
+ const form = createTeamForm(context, props.seed, {
+ ownEmail: props.ownEmail,
+ onCreated: props.onContinue,
+ });
+ return (
+ <div class="flex flex-col gap-3">
+ <TeamSetupFields
+ id="team"
+ name={form.name()}
+ emails={form.slots()}
+ disabled={form.pending()}
+ suggested={form.suggested}
+ onNameChange={form.setName}
+ onEmailChange={form.setSlot}
+ onRemoveEmail={form.removeSlot}
+ onAddEmail={form.addSlot}
+ />
+ <ContinueButton
+ label={
+ form.pending()
+ ? 'Creating workspace…'
+ : form.invites().length > 0
+ ? `Create team & invite ${form.invites().length}`
+ : 'Create team'
+ }
+ disabled={!form.canCreate()}
+ onClick={() => void form.create()}
+ />
+ <SkipButton disabled={form.pending()} onClick={props.onSkip} />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/onboarding/views/tools-step.tsx b/apps/web/src/features/onboarding/views/tools-step.tsx
new file mode 100644
index 0000000000..4b5430d506
--- /dev/null
+++ b/apps/web/src/features/onboarding/views/tools-step.tsx
@@ -0,0 +1,98 @@
+import SearchIcon from '@phosphor/magnifying-glass.svg';
+import { createSignal, For, Show } from 'solid-js';
+import { ContinueButton } from '../components/controls';
+import { ToolTile } from '../components/tool-tile';
+import { type Tool, useOnboardingContext } from '../context/onboarding-context';
+
+/** Uses the same searchable, paginated catalog and hosted connection flow as Settings. */
+export function ToolsStep(props: { onContinue: () => void }) {
+ const context = useOnboardingContext();
+ const catalog = context.createToolCatalog();
+ const connected = context.createConnectedTools({ poll: true });
+ const [busy, setBusy] = createSignal<string>();
+
+ const connect = async (tool: Tool) => {
+ if (busy()) return;
+ setBusy(tool.slug);
+ try {
+ await context.connectTool(tool);
+ } finally {
+ setBusy(undefined);
+ }
+ };
+
+ return (
+ <div class="flex flex-col gap-7">
+ <label class="flex items-center gap-3 rounded-full border border-edge bg-input px-5 py-4 shadow-sm focus-within:ring-1 focus-within:ring-ink/30">
+ <SearchIcon aria-hidden="true" class="size-5 shrink-0 text-ink/35" />
+ <input
+ type="search"
+ aria-label="Search integrations and MCPs"
+ placeholder="Search integrations and MCPs"
+ value={catalog.search()}
+ onInput={(event) => catalog.setSearch(event.currentTarget.value)}
+ class="min-w-0 flex-1 bg-transparent text-base outline-none placeholder:text-ink-placeholder"
+ />
+ </label>
+ <div
+ role="region"
+ aria-label="Available integrations"
+ tabindex="0"
+ class="h-[32rem] overflow-y-auto rounded-xl px-1 py-1 outline-none focus-visible:ring-1 focus-visible:ring-ink/30"
+ style={{ 'scrollbar-gutter': 'stable' }}
+ >
+ <div class="grid grid-cols-3 gap-x-2 gap-y-5 sm:grid-cols-4">
+ <For each={catalog.entries()}>
+ {(tool) => (
+ <ToolTile
+ tool={tool}
+ busy={busy() === tool.slug}
+ disabled={busy() !== undefined || connected() === undefined}
+ connected={connected()?.has(tool.slug) ?? false}
+ onConnect={() => void connect(tool)}
+ />
+ )}
+ </For>
+ </div>
+ <Show when={catalog.failed()}>
+ <p role="alert" class="py-6 text-center text-sm text-ink-muted">
+ Couldn't load integrations.{' '}
+ <button type="button" class="underline" onClick={catalog.retry}>
+ Try again
+ </button>
+ </p>
+ </Show>
+ <Show when={catalog.fetching()}>
+ <p role="status" class="py-6 text-center text-sm text-ink-muted">
+ Loading integrations…
+ </p>
+ </Show>
+ <Show
+ when={
+ !catalog.fetching() &&
+ !catalog.failed() &&
+ catalog.entries().length === 0
+ }
+ >
+ <p class="py-6 text-center text-sm text-ink-muted">
+ No integrations match “{catalog.search()}”. Try another name.
+ </p>
+ </Show>
+ <Show when={catalog.hasMore()}>
+ <button
+ type="button"
+ disabled={catalog.fetching()}
+ onClick={catalog.loadMore}
+ class="mx-auto block rounded-full border border-edge px-4 py-2 text-sm text-ink-muted disabled:opacity-40"
+ >
+ Load more
+ </button>
+ </Show>
+ </div>
+ <ContinueButton
+ disabled={busy() !== undefined}
+ onClick={props.onContinue}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/paywall/plans.test.ts b/apps/web/src/features/paywall/plans.test.ts
index 1e81fad8bd..1f7f8ce4a4 100644
--- a/apps/web/src/features/paywall/plans.test.ts
+++ b/apps/web/src/features/paywall/plans.test.ts
@@ -2,8 +2,9 @@ import { describe, expect, it } from 'vitest';
import { PLAN_BY_TIER, PLANS } from './plans';
describe('plan catalogs', () => {
- it('offers only Free and Premium during onboarding', () => {
+ it('offers Guest access and Premium during onboarding', () => {
expect(PLANS.map((plan) => plan.tier)).toEqual(['free', 'premium']);
+ expect(PLAN_BY_TIER.free.name).toBe('Guest');
});
it('retains Max for current-plan display', () => {
diff --git a/apps/web/src/features/paywall/plans.ts b/apps/web/src/features/paywall/plans.ts
index 8bc2a10849..4378074ea4 100644
--- a/apps/web/src/features/paywall/plans.ts
+++ b/apps/web/src/features/paywall/plans.ts
@@ -32,7 +32,7 @@ export type PaidPlanTier = Exclude<PlanTier, 'free'>;
const FREE_PLAN = {
tier: 'free',
- name: 'Free',
+ name: 'Guest',
price: 0,
highlighted: false,
} as const satisfies Plan;
diff --git a/apps/web/src/features/setup/ConnectorRow.tsx b/apps/web/src/features/setup/ConnectorRow.tsx
deleted file mode 100644
index be6ab2351d..0000000000
--- a/apps/web/src/features/setup/ConnectorRow.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import type { FeaturedMcpServer } from '@core/component/AI/constant/mcpServers';
-import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';
-import SpinnerIcon from '@phosphor/spinner-gap.svg';
-import { cn, Layer } from '@ui';
-import { Match, Switch } from 'solid-js';
-import { StatusDot } from '../settings/integration-ui';
-import { createConnectorConnect } from './useConnectorConnect';
-
-/**
- * One connector in the onboarding flow: brand icon, name, and an explicit
- * trailing status. Clicking an unconnected row starts OAuth in a popup.
- */
-export function ConnectorRow(props: {
- server: FeaturedMcpServer;
- connected: boolean;
- authenticated: boolean;
-}) {
- const { connect, busy } = createConnectorConnect({
- server: props.server,
- connected: () => props.connected,
- authenticated: () => props.authenticated,
- });
-
- return (
- <Layer depth={2}>
- <button
- type="button"
- title={
- props.authenticated
- ? `${props.server.server_name} is connected`
- : props.server.tagline
- }
- 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',
- !props.authenticated && 'hover:border-ink/10'
- )}
- >
- <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 shrink-0">
- <Switch
- 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>
- }
- >
- <Match when={props.authenticated}>
- <span class="flex items-center gap-1.5 text-xs text-ink-muted">
- <StatusDot state="connected" />
- Connected
- </span>
- </Match>
- <Match when={busy()}>
- <span class="flex items-center gap-1.5 text-xs text-ink-muted">
- <SpinnerIcon class="size-3 shrink-0 animate-spin" />
- Connecting…
- </span>
- </Match>
- </Switch>
- </span>
- </button>
- </Layer>
- );
-}
diff --git a/apps/web/src/features/setup/ImportEntityPill.tsx b/apps/web/src/features/setup/ImportEntityPill.tsx
deleted file mode 100644
index ab18bb0dd7..0000000000
--- a/apps/web/src/features/setup/ImportEntityPill.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import { buildSimpleEntityUrl } from '@core/util/url';
-import SpinnerIcon from '@phosphor/spinner-gap.svg';
-import { entityLabel, type ImportEntity } from '@queries/import';
-import { type JSX, Match, Switch } from 'solid-js';
-import { ItemPill } from './primitives';
-
-/** One ledger row as a pill, styled by its status. */
-export function ImportEntityPill(props: {
- entity: ImportEntity;
- icon?: JSX.Element;
-}) {
- const code = () => {
- const identifier = props.entity.metadata.identifier;
- return typeof identifier === 'string' ? identifier : undefined;
- };
- const hoverDetail = () => {
- const meta = props.entity.metadata;
- const detail = meta.description ?? meta.summary ?? meta.purpose;
- return typeof detail === 'string' ? detail : undefined;
- };
-
- return (
- <Switch>
- <Match when={props.entity.status === 'imported'}>
- <ItemPill
- icon={props.icon}
- code={code()}
- label={entityLabel(props.entity)}
- importedHref={
- props.entity.entity_id && props.entity.entity_type
- ? buildSimpleEntityUrl({
- type: props.entity.entity_type,
- id: props.entity.entity_id,
- })
- : undefined
- }
- />
- </Match>
- <Match when={props.entity.status === 'importing'}>
- <ItemPill
- icon={props.icon}
- code={code()}
- label={entityLabel(props.entity)}
- title="Importing…"
- status={
- <SpinnerIcon class="size-3 shrink-0 animate-spin text-ink-extra-muted" />
- }
- />
- </Match>
- <Match when={true}>
- <ItemPill
- icon={props.icon}
- code={code()}
- label={entityLabel(props.entity)}
- title={hoverDetail()}
- />
- </Match>
- </Switch>
- );
-}
diff --git a/apps/web/src/features/setup/Module.tsx b/apps/web/src/features/setup/Module.tsx
deleted file mode 100644
index 72bb2e9569..0000000000
--- a/apps/web/src/features/setup/Module.tsx
+++ /dev/null
@@ -1,513 +0,0 @@
-import {
- createEffect,
- createUniqueId,
- For,
- onCleanup,
- onMount,
-} from 'solid-js';
-import './SetupGraphic.css';
-
-/**
- * The dashed orbit rings — behind the body. They stay put during the click
- * burst while their dashes spin and they scale.
- */
-export function ModuleRings(props: { phaseMs?: number }) {
- const phaseMs = props.phaseMs ?? 0;
- // WebKit pixel-snaps moving dashed SVG strokes at this scale, making the
- // otherwise smooth orbit look like it jumps. Keep the static construction
- // marks in Safari rather than shipping visibly broken motion there.
- const animateDashes =
- typeof navigator === 'undefined' ||
- !/Safari/.test(navigator.userAgent) ||
- /Chrome|Chromium|Android/.test(navigator.userAgent);
- return (
- <>
- <g class="ring-motion ring-small-motion">
- <path
- class="ring-small"
- d="M367.2,58.7c0,19.4-16.8,41.9-37.5,50.2-20.7,8.3-37.5-.8-37.5-20.2s16.8-41.9,37.5-50.2c20.7-8.3,37.5.8,37.5,20.2Z"
- >
- {animateDashes && (
- <animate
- attributeName="stroke-dashoffset"
- begin={`${phaseMs}ms`}
- dur={`${AMBIENT_MOTION.ringDash.durationMs}ms`}
- from="0"
- repeatCount="indefinite"
- to={`-${AMBIENT_MOTION.ringDash.distance}`}
- />
- )}
- </path>
- </g>
- <g class="ring-motion ring-large-motion">
- <path
- class="ring-large"
- d="M409.5,71.5c0,30.9-26.7,66.6-59.6,79.8-32.9,13.2-59.6-1.2-59.6-32.2s26.7-66.6,59.6-79.8c32.9-13.2,59.6,1.2,59.6,32.2Z"
- >
- {animateDashes && (
- <animate
- attributeName="stroke-dashoffset"
- begin={`${phaseMs}ms`}
- dur={`${AMBIENT_MOTION.ringDash.durationMs}ms`}
- from="0"
- repeatCount="indefinite"
- to={`-${AMBIENT_MOTION.ringDash.distance}`}
- />
- )}
- </path>
- </g>
- </>
- );
-}
-
-/**
- * The small vent arcs — part of the body mass. They thrust with the body
- * and flash accent during the click burst.
- */
-export function ModuleVents() {
- return (
- <>
- <path class="vent" d="M326.9,143.4c1.9-7.8,5.1-15.7,9.3-23.2" />
- <path class="vent" d="M331.6,149.1c1.9-7.8,5.1-15.7,9.3-23.2" />
- <path class="vent" d="M337,155c1.9-7.8,5.1-15.7,9.3-23.2" />
- </>
- );
-}
-
-/**
- * The module's "body": the tile silhouette and the face ellipse the logo sits
- * on — the piece that thrusts forward (+D) during the click burst.
- */
-export function ModuleBody() {
- return (
- <>
- <path
- class="panel"
- d="M396.2,227.8c8.7,1.1,18.7-.2,29.4-4.5,31.5-12.6,57.4-45.9,59.7-75.9h0s.3-5.7.3-5.7l-.3-5.5-.9-5.2-3.8-13.3-2.1-4.8-2.7-4.3-3.3-3.8-42.1-39.9-3.8-3.3-4.3-2.7-4.7-2.1-5.1-1.5-8.3-1.9-5.1-.8-5.4-.2-5.6.4-5.8,1-5.9,1.5-6,2.1-6,2.7-5.9,3.2-5.8,3.7-5.6,4.1-5.4,4.6-5.1,4.9-4.8,5.3-4.4,5.5-4,5.8-3.6,5.9-3.1,6-2.6,6.1-2,6.1-1.4,6-.9,5.9-.3,5.7.3,5.5.9,5.2,3.8,13.3,2.1,4.8,2.7,4.3,3.3,3.8,42.1,39.9,3.8,3.3,4.3,2.7,4.7,2.1,5.1,1.5,8.3,1.9,5.1.8"
- />
- <path
- class="hairline"
- d="M478.6,147.8c0,26.5-22.9,57.2-51.1,68.5-28.2,11.3-51.1-1.1-51.1-27.6s22.9-57.2,51.1-68.5,51.1,1.1,51.1,27.6Z"
- />
- </>
- );
-}
-
-/**
- * The full isometric tile (back + body), minus its logo.
- */
-export function ModuleTile() {
- return (
- <>
- <ModuleRings />
- <ModuleBody />
- <ModuleVents />
- </>
- );
-}
-
-const LOGO_FACE_PERSPECTIVE = {
- heightScale: 0.8101,
- shearDegrees: 21.79,
- rotationDegrees: 21.79,
-} as const;
-
-const LOGO_FACE_PLACEMENT = {
- // The 24×24 logo's fixed scale and origin on the module face.
- scale: 3,
- translateX: 394.09,
- translateY: 150.228,
-} as const;
-
-const toSvgMatrixNumber = (value: number) => Number(value.toFixed(3));
-
-/**
- * Places a flat 24×24 brand logo onto a module's face, matching the isometric
- * perspective. Illustrator applies vertical scale → shear → rotation; SVG's
- * Y-down coordinate system requires the design angles to be negated here.
- */
-export const LOGO_FACE_TRANSFORM = (() => {
- const rotation = (-LOGO_FACE_PERSPECTIVE.rotationDegrees * Math.PI) / 180;
- const shear = Math.tan((-LOGO_FACE_PERSPECTIVE.shearDegrees * Math.PI) / 180);
- const cosine = Math.cos(rotation);
- const sine = Math.sin(rotation);
- const { heightScale } = LOGO_FACE_PERSPECTIVE;
- const { scale, translateX, translateY } = LOGO_FACE_PLACEMENT;
-
- // scale → skewX → rotate, written as SVG's matrix(a b c d e f).
- const xAxisX = scale * cosine;
- const xAxisY = scale * sine;
- const yAxisX = scale * heightScale * (cosine * shear - sine);
- const yAxisY = scale * heightScale * (sine * shear + cosine);
-
- return `matrix(${toSvgMatrixNumber(xAxisX)} ${toSvgMatrixNumber(xAxisY)} ${toSvgMatrixNumber(yAxisX)} ${toSvgMatrixNumber(yAxisY)} ${translateX} ${translateY})`;
-})();
-
-/**
- * A brand mark to sit on a module face: one or more path `d` strings, filled
- * with `currentColor`, positioned by `transform` (defaults to the flat-logo
- * face transform via {@link LOGO_FACE_TRANSFORM}).
- */
-export type ModuleLogo = { paths: string[]; transform?: string };
-
-/**
- * A module's activity state, reflected in its logo:
- * - `idle` — logo in ink.
- * - `downloading` — logo pulses between ink and accent (pairs with the
- * connector's travelling pulse).
- * - `linked` — logo held solid accent.
- */
-export type ModuleState = 'idle' | 'downloading' | 'linked';
-
-const AMBIENT_MOTION = {
- bob: {
- distancePx: 4,
- durationMs: 4500,
- },
- ringBreathe: {
- minScale: 0.97,
- maxScale: 1.03,
- },
- ringDash: {
- // One full dash period (dash 6 + gap 6), so travel loops seamlessly.
- distance: 12,
- durationMs: 3000,
- },
-} as const;
-
-const BOB_KEYFRAMES: Keyframe[] = [
- {
- transform: `translateY(${AMBIENT_MOTION.bob.distancePx}px)`,
- easing: 'ease-in-out',
- },
- {
- transform: `translateY(${-AMBIENT_MOTION.bob.distancePx}px)`,
- offset: 0.5,
- easing: 'ease-in-out',
- },
- { transform: `translateY(${AMBIENT_MOTION.bob.distancePx}px)` },
-];
-const RING_BREATHE_KEYFRAMES: Keyframe[] = [
- {
- transform: `scale(${AMBIENT_MOTION.ringBreathe.minScale})`,
- easing: 'ease-in-out',
- },
- {
- transform: `scale(${AMBIENT_MOTION.ringBreathe.maxScale})`,
- offset: 0.5,
- easing: 'ease-in-out',
- },
- { transform: `scale(${AMBIENT_MOTION.ringBreathe.minScale})` },
-];
-// The module's long axis in local coords: the "depth" axis. The face is at the
-// +D (down-right) end and the rings at the −D (up-left) end. On click the body
-// thrusts +D while the rings stay put; the jet trail streaks −D behind it.
-const POS_D = { x: 0.7256, y: 0.6881 };
-const THRUST = 24;
-const THRUST_X = (POS_D.x * THRUST).toFixed(1);
-const THRUST_Y = (POS_D.y * THRUST).toFixed(1);
-
-/**
- * Click burst timing. Asymmetric on purpose: a quick ramp to the peak, a brief
- * hold there, then a slow settle back. The keyframe offsets carve the ~2.1s
- * duration into roughly ramp / hold / settle; RAMP and SETTLE ease each phase.
- */
-const ACCELERATION = {
- durationMs: 2100,
- peakIn: 0.17, // ramped to peak by here (~360ms)
- peakOut: 0.4, // held at peak until here (~480ms), then settles (~1.26s)
- largeRingScale: 1.2,
- smallRingScale: 0.8,
- dashTravel: 144,
- jetTrail: {
- length: 230,
- halfWidth: 15,
- startScaleY: 2.4,
- peakOpacity: 0.9,
- },
-} as const;
-const RAMP = 'cubic-bezier(0.1, 0.75, 0.3, 1)'; // fast punch
-const SETTLE = 'cubic-bezier(0.35, 0, 0.3, 1)'; // slow ease back
-
-// The body thrusts forward (+D), holds, then eases back.
-const ACCEL_BODY: Keyframe[] = [
- { transform: 'translate(0,0)', easing: RAMP },
- {
- transform: `translate(${THRUST_X}px,${THRUST_Y}px)`,
- offset: ACCELERATION.peakIn,
- },
- {
- transform: `translate(${THRUST_X}px,${THRUST_Y}px)`,
- offset: ACCELERATION.peakOut,
- easing: SETTLE,
- },
- { transform: 'translate(0,0)' },
-];
-// Rings stay put but change size — large grows, small shrinks — hold, settle.
-// (No geometric rotation: the ellipses are in perspective; their dashes spin,
-// via ACCEL_*_DASH.) Composited onto the ambient breathe, so start/end neutral.
-const ACCEL_LARGE_RING: Keyframe[] = [
- { transform: 'scale(1)', easing: RAMP },
- {
- transform: `scale(${ACCELERATION.largeRingScale})`,
- offset: ACCELERATION.peakIn,
- },
- {
- transform: `scale(${ACCELERATION.largeRingScale})`,
- offset: ACCELERATION.peakOut,
- easing: SETTLE,
- },
- { transform: 'scale(1)' },
-];
-const ACCEL_SMALL_RING: Keyframe[] = [
- { transform: 'scale(1)', easing: RAMP },
- {
- transform: `scale(${ACCELERATION.smallRingScale})`,
- offset: ACCELERATION.peakIn,
- },
- {
- transform: `scale(${ACCELERATION.smallRingScale})`,
- offset: ACCELERATION.peakOut,
- easing: SETTLE,
- },
- { transform: 'scale(1)' },
-];
-// The dashes spin fast around each ring, opposite directions, throughout the
-// burst. Sweeping a whole number of dash periods (12 = dash 6 + gap 6) lands
-// neutral, so composited onto the ambient dash travel it leaves no seam.
-const ACCEL_LARGE_DASH: Keyframe[] = [
- { strokeDashoffset: '0' },
- { strokeDashoffset: `-${ACCELERATION.dashTravel}` },
-];
-const ACCEL_SMALL_DASH: Keyframe[] = [
- { strokeDashoffset: '0' },
- { strokeDashoffset: `${ACCELERATION.dashTravel}` },
-];
-// The "jet trail": a rect laid along the −D axis via JET_TRAIL_TRANSFORM (local
-// +x → −D), so its length runs backward from the module and its local y is the
-// (perpendicular) width. Positioned so the opaque gradient end sits at the
-// module and fades to transparent up-left.
-const JET_TRAIL_TRANSFORM = 'translate(420 162) rotate(223.5)';
-
-// Jet trail: starts wide and faint, focuses to a thin, bright streak at the peak
-// (scaleY narrows it about its centerline), holds, then fades out. scaleY is
-// on an inner group whose transform-origin is its center.
-const ACCEL_JET_TRAIL: Keyframe[] = [
- {
- transform: `scaleY(${ACCELERATION.jetTrail.startScaleY})`,
- opacity: 0,
- easing: RAMP,
- },
- {
- transform: 'scaleY(1)',
- opacity: ACCELERATION.jetTrail.peakOpacity,
- offset: ACCELERATION.peakIn,
- },
- {
- transform: 'scaleY(1)',
- opacity: ACCELERATION.jetTrail.peakOpacity,
- offset: ACCELERATION.peakOut,
- easing: SETTLE,
- },
- { transform: 'scaleY(1)', opacity: 0 },
-];
-
-const prefersReducedMotion = () =>
- window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
-/**
- * A single hovering module: the isometric tile with a brand logo on its face,
- * bobbing gently while its orbit rings breathe and their dashes travel.
- *
- * Renders as an embeddable `<g>` (drop it into any SVG whose root carries the
- * `setup-graphic` class for styling). Ambient motion is self-driven with WAAPI
- * so it survives a parent's DOM re-attach without restarting — a CSS animation
- * would visibly pop. Pass `phaseMs` (a negative offset) so several modules
- * don't move in unison.
- *
- * Clicking the module plays an "acceleration" burst: the body thrusts forward
- * (+D), the vents flash to accent, the large ring grows and its dashes spin
- * one way while the small ring shrinks and its dashes spin the other, and an
- * jet trail focuses in behind it — a quick ramp, a brief hold, then a slow
- * settle back.
- *
- * `state` reflects activity in the logo's color (see {@link ModuleState}); it
- * updates reactively, so it can be toggled at runtime.
- */
-export function Module(props: {
- logo: ModuleLogo;
- /** Transform positioning the module (e.g. translate/scale). */
- place?: string;
- /** Phase offset in ms (negative) so modules bob out of sync. */
- phaseMs?: number;
- /** Whether to run the ambient bob/ring motion (default true). */
- animate?: boolean;
- /** Activity state reflected in the logo color (default 'idle'). */
- state?: ModuleState;
- class?: string;
-}) {
- let root: SVGGElement | undefined;
- let logoGroup: SVGGElement | undefined;
- let ventsGroup: SVGGElement | undefined;
- const jetTrailGradientId = createUniqueId();
- const animations: Animation[] = [];
- let clickAnimations: Animation[] = [];
- onCleanup(() => {
- for (const animation of animations) animation.cancel();
- for (const animation of clickAnimations) animation.cancel();
- });
-
- // Drive color from `state`, reactively (toggle-able at runtime). The logo
- // and vents are `currentColor`, so a `color` on their group recolors them.
- // Both the linked hold and the downloading pulse use a live `var(--color-
- // accent)` (inline for linked, a CSS animation for downloading) rather than
- // a probed concrete color: the themed accent is applied after mount, so a
- // value baked at effect time would be the pre-theme fallback (green).
- createEffect(() => {
- const state = props.state ?? 'idle';
- if (!logoGroup || !root) return;
- logoGroup.classList.remove('logo-downloading');
- logoGroup.style.color = '';
- if (ventsGroup) ventsGroup.style.color = '';
- if (state === 'linked') {
- logoGroup.style.color = 'var(--color-accent)';
- if (ventsGroup) ventsGroup.style.color = 'var(--color-accent)';
- } else if (state === 'downloading' && !prefersReducedMotion()) {
- logoGroup.classList.add('logo-downloading');
- }
- });
-
- onMount(() => {
- if (!root || props.animate === false || prefersReducedMotion()) return;
- const delay = props.phaseMs ?? 0;
- animations.push(
- root.animate(BOB_KEYFRAMES, {
- duration: AMBIENT_MOTION.bob.durationMs,
- iterations: Number.POSITIVE_INFINITY,
- delay,
- })
- );
- for (const ring of root.querySelectorAll<SVGGElement>('.ring-motion')) {
- animations.push(
- ring.animate(RING_BREATHE_KEYFRAMES, {
- duration: AMBIENT_MOTION.bob.durationMs,
- iterations: Number.POSITIVE_INFINITY,
- delay,
- })
- );
- }
- });
-
- // The click "acceleration" burst. Ring scale + dash composite onto the
- // ambient animations (composite: 'add') and start/end neutral, so no restart
- // pop; the body and jet trail have no ambient motion, so they just replace.
- const accelerate = () => {
- if (!root || prefersReducedMotion()) return;
- for (const animation of clickAnimations) animation.cancel();
- clickAnimations = [];
- const accent = 'var(--color-accent)';
- const dur = { duration: ACCELERATION.durationMs } as const;
- const add = {
- duration: ACCELERATION.durationMs,
- composite: 'add' as const,
- };
- // Dashes spin fast then wind down (ease-out) over the whole burst.
- const spin = { ...add, easing: 'ease-out' };
-
- const body = root.querySelector<SVGElement>('.module-body');
- const large = root.querySelector<SVGGElement>('.ring-large-motion');
- const small = root.querySelector<SVGGElement>('.ring-small-motion');
- const jetTrail = root.querySelector<SVGElement>('.module-jet-trail-scale');
- if (body) clickAnimations.push(body.animate(ACCEL_BODY, dur));
- if (large) {
- clickAnimations.push(large.animate(ACCEL_LARGE_RING, add));
- clickAnimations.push(large.animate(ACCEL_LARGE_DASH, spin));
- }
- if (small) {
- clickAnimations.push(small.animate(ACCEL_SMALL_RING, add));
- clickAnimations.push(small.animate(ACCEL_SMALL_DASH, spin));
- }
- if (jetTrail) clickAnimations.push(jetTrail.animate(ACCEL_JET_TRAIL, dur));
- for (const vent of root.querySelectorAll<SVGElement>(
- '.module-vents path'
- )) {
- // Flash from the state-specific resting stroke so linked-module vents
- // don't jump from accent back to ink.
- const resting =
- props.state === 'linked' ? 'var(--color-accent)' : 'var(--color-ink)';
- clickAnimations.push(
- vent.animate(
- [
- { stroke: resting, opacity: 0.4, easing: RAMP },
- { stroke: accent, opacity: 1, offset: ACCELERATION.peakIn },
- {
- stroke: accent,
- opacity: 1,
- offset: ACCELERATION.peakOut,
- easing: SETTLE,
- },
- { stroke: resting, opacity: 0.4 },
- ],
- dur
- )
- );
- }
- };
-
- return (
- <g
- ref={root}
- class={`module-bob ${props.class ?? ''}`}
- onClick={(event) => {
- // Don't also trigger a parent's click (e.g. the setup scene's slide).
- event.stopPropagation();
- accelerate();
- }}
- >
- <g class="module" transform={props.place}>
- <defs>
- <linearGradient
- id={jetTrailGradientId}
- gradientUnits="userSpaceOnUse"
- x1="0"
- y1="0"
- x2={ACCELERATION.jetTrail.length}
- y2="0"
- >
- <stop offset="0%" class="module-jet-trail-hot" />
- <stop offset="100%" class="module-jet-trail-cold" />
- </linearGradient>
- </defs>
- {/* Accent jet trail behind the module — hidden until the click burst. The
- inner group's width (scaleY) and opacity are what animate. */}
- <g class="module-jet-trail" transform={JET_TRAIL_TRANSFORM}>
- <g class="module-jet-trail-scale">
- <rect
- x="0"
- y={-ACCELERATION.jetTrail.halfWidth}
- width={ACCELERATION.jetTrail.length}
- height={ACCELERATION.jetTrail.halfWidth * 2}
- fill={`url(#${jetTrailGradientId})`}
- />
- </g>
- </g>
- {/* Rings stay put behind; the body mass — card, face, logo, and the
- vents on top of it — thrusts forward on click. */}
- <ModuleRings phaseMs={props.phaseMs} />
- <g class="module-body">
- <ModuleBody />
- <g
- ref={logoGroup}
- class="module-logo"
- transform={props.logo.transform ?? LOGO_FACE_TRANSFORM}
- >
- <For each={props.logo.paths}>{(d) => <path d={d} />}</For>
- </g>
- <g ref={ventsGroup} class="module-vents">
- <ModuleVents />
- </g>
- </g>
- </g>
- </g>
- );
-}
diff --git a/apps/web/src/features/setup/SetupGraphic.css b/apps/web/src/features/setup/SetupGraphic.css
deleted file mode 100644
index 37e65c38d1..0000000000
--- a/apps/web/src/features/setup/SetupGraphic.css
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Styles for the /setup empty-state isometric scene (SetupGraphic.tsx).
- */
-.setup-graphic {
- --setup-silhouette: oklch(from var(--color-surface) calc(l + 0.035) c h);
- /* Don't clip the scene's motion (module bob, click bursts, halos) or the
- handoff shrink to the viewBox. */
- overflow: visible;
-}
-
-.setup-graphic :is(.arc, .vent, .edge, .card-mid, .ring-small, .guide, .ring-large, .card-back, .card-front) {
- stroke-linecap: round;
-}
-
-.setup-graphic
- :is(.arc, .vent, .edge, .card-mid, .ring-small, .guide, .ring-large, .card-back, .card-front, .hairline, .panel, .knob) {
- stroke: currentcolor;
- stroke-width: 2px;
-}
-
-.setup-graphic :is(.arc, .vent, .edge, .ring-small, .guide, .ring-large, .hairline) {
- fill: none;
-}
-
-.setup-graphic :is(.arc, .vent, .ring-small, .ring-large, .hairline, .panel, .knob) {
- stroke-miterlimit: 10;
-}
-
-.setup-graphic :is(.vent, .ring-small, .guide, .dot) {
- opacity: 0.4;
-}
-
-.setup-graphic :is(.edge, .card-mid, .guide, .card-back, .card-front) {
- stroke-linejoin: round;
-}
-
-/* Card silhouettes. */
-.setup-graphic :is(.card-mid, .card-back, .card-front, .panel, .knob) {
- fill: var(--setup-silhouette);
- transition: fill 700ms ease;
-}
-
-.setup-graphic :is(.ring-small, .ring-large) {
- stroke-dasharray: 6;
-}
-
-/* Left-face shading on all three blocks.
- Always black (not currentColor) so the faces darken like shadow in both
- themes; dark surfaces need a stronger shadow to register at all. */
-.setup-graphic .shade {
- fill: #000;
- opacity: 0.1;
- transition: opacity 700ms ease;
-}
-
-html[data-theme-light='false'] .setup-graphic .shade {
- opacity: 0.3;
-}
-
-/* The "powered up" finale — a composite-level final state (the `poweredUp`
- prop toggles .powered on the root), independent of any module's `linked`
- state. The hovering modules fade out and the three cards fill in: their
- linework (currentColor, so a color change on .blocks carries the strokes and
- currentColor fills) and silhouette fills turn accent, and the left-face
- shading fades away — leaving a solid accent Macro mark. Plain transitions,
- not keyframe animations, so a Suspense re-attach renders the end state
- rather than replaying it. (The white LED sparks are hidden here too, but the
- real guarantee is JS: SetupGraphic cancels the LED WAAPI animations when
- powering up, since a running animation would otherwise beat this CSS.) */
-.setup-graphic .blocks {
- transition: color 700ms ease;
-}
-.setup-graphic :is(.modules, .connectors) {
- transition: opacity 700ms ease;
-}
-/* The modules fade out, and their tethers go with them. */
-.setup-graphic.powered :is(.modules, .connectors) {
- opacity: 0;
- pointer-events: none;
-}
-.setup-graphic.powered .blocks {
- color: var(--color-accent);
-}
-/* Scoped to .blocks: `.panel`/`.knob` are also used by the module bodies, and
- those should only fade out — never fill accent. */
-.setup-graphic.powered
- .blocks
- :is(.card-mid, .card-back, .card-front, .panel, .knob) {
- fill: var(--color-accent);
-}
-.setup-graphic.powered .led-spark {
- opacity: 0;
-}
-.setup-graphic.powered .shade,
-/* out-specificity the dark-theme .shade opacity rule above */
-html[data-theme-light='false'] .setup-graphic.powered .shade {
- opacity: 0;
-}
-
-@media (prefers-reduced-motion: reduce) {
- .setup-graphic .blocks,
- .setup-graphic .modules,
- .setup-graphic :is(.card-mid, .card-back, .card-front, .panel, .knob),
- .setup-graphic .shade {
- transition: none;
- }
-}
-
-/* Geometry-only reference for the brand handoff (see `.logo-ref` in
- SetupGraphic.tsx): never painted, never hit-tested, but still laid out so
- `getBoundingClientRect()` returns the logo's true position. `opacity: 0`
- rather than `display: none`/`visibility: hidden` — those would zero out or
- drop the measurable geometry. */
-.setup-graphic .logo-ref {
- opacity: 0;
- pointer-events: none;
-}
-
-/* LED halo: a soft filled accent disc behind each inset that breathes
- (expands and contracts) once lit. Hidden (opacity 0) at rest; the
- illuminate pass drives its scale + opacity via WAAPI. transform-box/-origin
- make the scale grow about its own center. */
-.setup-graphic .led-halo {
- fill: var(--color-accent);
- opacity: 0;
- transform-box: fill-box;
- transform-origin: center;
-}
-
-/* LED spark: a small fully-white specular dot in the inset's upper-left,
- suggesting the bulb's light source. Faded in with the illuminate pass. */
-.setup-graphic .led-spark {
- fill: #fff;
- opacity: 0;
-}
-
-/* Dashed connector tethers from modules to block features. Authored in
- viewBox space (unscaled), so a 1.3 stroke matches the scaled block linework;
- kept subtle like the scene's other construction lines. */
-.setup-graphic .connector {
- fill: none;
- stroke: currentcolor;
- stroke-width: 1.3;
- stroke-dasharray: 6;
- stroke-linecap: round;
- opacity: 0.55;
-}
-
-/* "Downloading" pulse: a clean accent segment travelling along a connector
- (the dash + stroke-dashoffset are set by DownloadPulse), with just a hint of
- glow so it stays crisp. */
-.setup-graphic .download-pulse {
- fill: none;
- stroke: var(--color-accent);
- stroke-width: 2.5;
- stroke-linecap: round;
- pointer-events: none;
- filter: drop-shadow(0 0 1px var(--color-accent));
-}
-
-/* "Downloading" logo pulse: the module's currentColor logo eases between ink
- and accent. Unlike the module's other motion (WAAPI, to survive a Suspense
- re-attach), this is CSS so it pulses to a *live* var(--color-accent): the
- brand accent is applied after mount, and a WAAPI keyframe would bake the
- pre-theme fallback color instead. A re-attach at worst restarts the pulse
- from ink — a negligible blip for a slow color fade. Toggled by the
- `logo-downloading` class (set in Module for the downloading state). */
-@keyframes setup-logo-download {
- 0%,
- 100% {
- color: var(--color-ink);
- }
- 50% {
- color: var(--color-accent);
- }
-}
-.setup-graphic .logo-downloading {
- animation: setup-logo-download 1600ms ease-in-out infinite;
-}
-@media (prefers-reduced-motion: reduce) {
- .setup-graphic .logo-downloading {
- animation: none;
- }
-}
-
-/* Ambient module motion — the bob and orbit rings' breathe are driven with
- WAAPI (see SetupGraphic.tsx), while dash travel uses native SVG animation.
- This avoids Safari's jitter when WAAPI animates a dashed SVG stroke. When a
- query above it re-suspends, the page's Suspense boundary re-attaches this
- subtree; that restarts CSS animations (a visible pop) but leaves the
- WAAPI animations running. The wrapper owns scale while the nested path owns dash
- travel: separating those properties avoids Safari re-rasterizing a dashed
- path as its transform changes. */
-.setup-graphic .module .ring-motion {
- transform-box: fill-box;
- transform-origin: center;
-}
-
-/* Accent "acceleration" jet trail behind the module, revealed on click (driven by
- WAAPI). Non-interactive; gradient goes opaque accent at the module to
- transparent up-left along the −D axis. The inner group carries the animated
- opacity and the width scale (scaleY about its own center). */
-.setup-graphic .module-jet-trail {
- pointer-events: none;
-}
-.setup-graphic .module-jet-trail-scale {
- opacity: 0;
- transform-box: fill-box;
- transform-origin: center;
-}
-.setup-graphic .module-jet-trail-hot {
- stop-color: var(--color-accent);
- stop-opacity: 0.85;
-}
-.setup-graphic .module-jet-trail-cold {
- stop-color: var(--color-accent);
- stop-opacity: 0;
-}
diff --git a/apps/web/src/features/setup/SetupGraphic.tsx b/apps/web/src/features/setup/SetupGraphic.tsx
deleted file mode 100644
index 80ea56a111..0000000000
--- a/apps/web/src/features/setup/SetupGraphic.tsx
+++ /dev/null
@@ -1,966 +0,0 @@
-import { createEffect, For, on, onCleanup, onMount, Show } from 'solid-js';
-import { Module, type ModuleLogo, type ModuleState } from './Module';
-import { MODULE_LOGOS } from './moduleLogos';
-import './SetupGraphic.css';
-
-type Point = { x: number; y: number };
-type ConnectorLayer = 'front' | 'mid' | 'back';
-type ConnectorAxis = 'frontFace' | 'sideFace';
-
-const point = (x: number, y: number): Point => ({ x, y });
-const toSvgNumber = (value: number) => Number(value.toFixed(1));
-
-const SCENE = {
- viewBox: '-10 -28 930 700',
- blocks: {
- center: point(444, 457),
- scale: 0.667,
- inverseScale: 1.49925,
- },
- module: {
- scale: 0.667,
- // The point on the module body where each tether originates. Slots may
- // opt into a different local point when their face needs a slight nudge.
- defaultConnectorAnchor: point(397.5, 140),
- },
-} as const;
-
-const MOTION = {
- downloadPulse: {
- segmentLength: 70,
- millisecondsPerUnit: 3,
- },
- leds: {
- staggerMs: 110,
- onsetMs: 300,
- haloFlashMs: 450,
- breatheMs: 2600,
- halo: {
- startScale: 0.7,
- peakScale: 2.4,
- restingScale: 0.85,
- peakOpacity: 0.6,
- restingOpacity: 0.28,
- breatheScale: 1.2,
- breatheOpacity: 0.14,
- },
- },
- cardSlide: {
- delayMs: 800,
- durationMs: 2600,
- outOffset: 0.2,
- holdOffset: 0.4,
- distance: point(34.8, 33.1),
- },
- modulePhaseMs: 1100,
-} as const;
-
-const connectorAxisSlopes: Record<ConnectorAxis, number> = {
- // The two non-vertical axes in the isometric artwork. Keeping these shared
- // means a tether's lower arm stays aligned to its card face as its module
- // moves; only the slot's placement needs updating.
- frontFace: -0.4,
- sideFace: 0.948,
-};
-
-const moduleTransform = (position: Point, moduleAnchor: Point) =>
- `translate(${position.x} ${position.y}) scale(${SCENE.module.scale}) translate(${-moduleAnchor.x} ${-moduleAnchor.y})`;
-
-const transformModulePoint = (
- position: Point,
- moduleAnchor: Point,
- localPoint: Point
-): Point => ({
- x: position.x + SCENE.module.scale * (localPoint.x - moduleAnchor.x),
- y: position.y + SCENE.module.scale * (localPoint.y - moduleAnchor.y),
-});
-
-const connectorPath = (start: Point, target: Point, axis: ConnectorAxis) => {
- const elbow = point(
- start.x,
- target.y - connectorAxisSlopes[axis] * (target.x - start.x)
- );
- return `M${toSvgNumber(start.x)} ${toSvgNumber(start.y)} L${toSvgNumber(elbow.x)} ${toSvgNumber(elbow.y)} L${toSvgNumber(target.x)} ${toSvgNumber(target.y)}`;
-};
-
-/**
- * A "downloading" pulse: an accent glow segment that travels along a connector
- * from the module to the card, on repeat. Built from a short dash swept with
- * stroke-dashoffset (WAAPI, so a Suspense re-attach can't restart it). Rendered
- * in the same layer as its connector, so it's occluded by the cards the same
- * way. The connector `d` runs module→card, so the pulse flows that direction.
- */
-function DownloadPulse(props: { d: string }) {
- if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
- return null;
- }
-
- let path: SVGPathElement | undefined;
- let animation: Animation | undefined;
- onCleanup(() => animation?.cancel());
- onMount(() => {
- if (!path) return;
- const total = path.getTotalLength();
- const { segmentLength, millisecondsPerUnit } = MOTION.downloadPulse;
- // One bright dash, gap = full path (so only one is on the wire at a time);
- // sweeping the whole period runs it start→end and loops seamlessly.
- path.setAttribute('stroke-dasharray', `${segmentLength} ${total}`);
- animation = path.animate(
- [
- { strokeDashoffset: '0' },
- { strokeDashoffset: `${-(segmentLength + total)}` },
- ],
- {
- duration: Math.round((segmentLength + total) * millisecondsPerUnit),
- iterations: Number.POSITIVE_INFINITY,
- easing: 'linear',
- }
- );
- });
- return <path ref={path} class="download-pulse" d={props.d} />;
-}
-
-/**
- * The fixed module positions around the blocks. Each slot is pure geometry —
- * where the module sits (`position`, mapped from its local `moduleAnchor`) and
- * the dashed tether to a block feature (`connector`) — independent of which
- * logo lands on it.
- *
- * A connector's `layer` sets its draw order: `front` over all cards; `back`
- * behind all cards; `mid` between the back and middle cards. Coordinates are
- * absolute viewBox units (modules/connectors are siblings of the scaled
- * blocks), so the `mid` group counters the blocks transform to stay so.
- */
-type Slot = {
- // Move a module by changing only this position; its tether follows.
- position: Point;
- moduleAnchor: Point;
- connector: {
- target: Point;
- axis: ConnectorAxis;
- layer: ConnectorLayer;
- source?: Point;
- };
-};
-
-const createSlot = (slot: Slot) => {
- const connectorAnchor =
- slot.connector.source ?? SCENE.module.defaultConnectorAnchor;
- const connectorStart = transformModulePoint(
- slot.position,
- slot.moduleAnchor,
- connectorAnchor
- );
-
- return {
- place: moduleTransform(slot.position, slot.moduleAnchor),
- connector: {
- d: connectorPath(
- connectorStart,
- slot.connector.target,
- slot.connector.axis
- ),
- layer: slot.connector.layer,
- },
- };
-};
-
-const SLOTS = {
- // Tethers to the pill cutout on the front card.
- frontPill: createSlot({
- position: point(90, 275),
- moduleAnchor: point(447.5, 48.3),
- connector: {
- target: point(228.7, 495.4),
- axis: 'frontFace',
- layer: 'front',
- },
- }),
- // Tethers to the back side of the middle card.
- midBack: createSlot({
- position: point(270, 190),
- moduleAnchor: point(447.5, 168.3),
- connector: {
- target: point(374.6, 442.3),
- axis: 'sideFace',
- layer: 'back',
- source: point(397.5, 146.3),
- },
- }),
- // Tethers to the small circular port on the middle card.
- midPort: createSlot({
- position: point(410, 145),
- moduleAnchor: point(447.5, -98.3),
- connector: {
- target: point(429.5, 556.8),
- axis: 'frontFace',
- layer: 'front',
- },
- }),
- // Tethers to the far side of the middle card.
- midFar: createSlot({
- position: point(670, 210),
- moduleAnchor: point(507.5, 128.3),
- connector: {
- target: point(489.8, 465.7),
- axis: 'frontFace',
- layer: 'mid',
- source: point(397.5, 134.3),
- },
- }),
- // Tethers to the far side of the back card.
- backFar: createSlot({
- position: point(855, 290),
- moduleAnchor: point(507.5, 248.3),
- connector: {
- target: point(694.8, 465.7),
- axis: 'frontFace',
- layer: 'back',
- source: point(397.5, 139.6),
- },
- }),
-} satisfies Record<
- string,
- { place: string; connector: { d: string; layer: ConnectorLayer } }
->;
-
-type SlotName = keyof typeof SLOTS;
-
-/** One module to render: which {@link SLOTS slot} it fills, its logo, whether
- * to draw its connector (default true), and its activity `state` (default
- * 'idle'). `downloading` runs the connector pulse; `linked` hides the
- * connector. */
-export type ModuleConfig = {
- slot: SlotName;
- logo: ModuleLogo;
- connector?: boolean;
- state?: ModuleState;
-};
-
-/** Default: every slot filled with its conventional brand logo, connectors on.
- * Slots are geometry-named, so the logo for each is spelled out here. */
-const DEFAULT_MODULES: ModuleConfig[] = [
- { slot: 'frontPill', logo: MODULE_LOGOS.Linear },
- { slot: 'midBack', logo: MODULE_LOGOS.Google },
- { slot: 'midPort', logo: MODULE_LOGOS.GitHub },
- { slot: 'midFar', logo: MODULE_LOGOS.Notion },
- { slot: 'backFar', logo: MODULE_LOGOS.Slack },
-];
-
-/**
- * Undoes the `.blocks` transform, so a connector placed among the blocks'
- * children (to sit at a specific card in the draw order) still renders at its
- * absolute viewBox coordinates.
- */
-const INVERSE_BLOCKS_TRANSFORM = `translate(${SCENE.blocks.center.x} ${SCENE.blocks.center.y}) scale(${SCENE.blocks.inverseScale}) translate(${-SCENE.blocks.center.x} ${-SCENE.blocks.center.y})`;
-
-const BLOCKS_TRANSFORM = `translate(${SCENE.blocks.center.x} ${SCENE.blocks.center.y}) scale(${SCENE.blocks.scale}) translate(${-SCENE.blocks.center.x} ${-SCENE.blocks.center.y})`;
-
-/**
- * The isometric empty-state scene for `/setup`: the Macro logo re-imagined as
- * three technical isometric blocks (`front_card`, `middle_card`, `back_card`),
- * with hovering modules around it. Inlined (rather than imported as an asset)
- * so animation can target the named groups.
- *
- * Pass `modules` to choose which {@link SLOTS slots} appear and which logo each
- * carries (and whether to draw each tether); omit it for all five slots with
- * their brand logos. Each connector follows its module.
- *
- * The back card's front section (`animating_card`) slides out and back once on
- * mount; clicking the graphic replays it. When it settles, the inset LED
- * indicators illuminate bottom-to-top and hold a faint pulsing glow with a
- * breathing halo; a fresh slide darkens them until it settles again.
- */
-export function SetupGraphic(props: {
- class?: string;
- modules?: ModuleConfig[];
- /** The composite-level "powered up" finale: the modules fade out and the
- * three cards fill in accent with their shading gone. Independent of any
- * module's `linked` state. */
- poweredUp?: boolean;
-}) {
- const modules = () => props.modules ?? DEFAULT_MODULES;
- // Connectors follow their modules: one per shown module whose connector
- // isn't disabled and isn't in the `linked` state (which hides it), carrying
- // the slot's tether geometry + draw layer, plus whether its pulse is running.
- const connectorsIn = (layer: ConnectorLayer) =>
- modules()
- .filter(
- (m) =>
- m.connector !== false &&
- m.state !== 'linked' &&
- SLOTS[m.slot].connector.layer === layer
- )
- .map((m) => ({
- ...SLOTS[m.slot].connector,
- downloading: m.state === 'downloading',
- }));
-
- let svg: SVGSVGElement | undefined;
- let animatingCard: SVGGElement | undefined;
- let slideAnimation: Animation | undefined;
- let slideDelay: ReturnType<typeof setTimeout> | undefined;
- // The LEDs, ordered bottom-to-top (illumination order): each carries its
- // inset dot, halo ring, and specular spark. Plus the WAAPI animations
- // currently driving them.
- type Led = {
- inset: SVGElement;
- halo: SVGElement | null;
- spark: SVGElement | null;
- };
- let leds: Led[] = [];
- let ledAnimations: Animation[] = [];
- onCleanup(() => {
- clearTimeout(slideDelay);
- for (const animation of ledAnimations) animation.cancel();
- });
-
- const reducedMotion = () =>
- window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- const darkenLeds = () => {
- for (const animation of ledAnimations) animation.cancel();
- ledAnimations = [];
- };
-
- // Light the LEDs bottom-to-top: each ramps from its resting ink dot to a
- // glowing accent dot with a white specular spark (staggered onset) while
- // its halo flashes big, then settles into an endless faint pulse with a
- // breathing halo. Driven with WAAPI so a Suspense re-attach can't replay
- // the onset.
- const illuminateLeds = () => {
- darkenLeds();
- const accent = 'var(--color-accent)';
- const ink = 'var(--color-ink)';
- const lit = `drop-shadow(0 0 1.5px ${accent})`;
- const bright = `drop-shadow(0 0 4px ${accent})`;
- const motion = !reducedMotion();
-
- leds.forEach(({ inset, halo, spark }, index) => {
- const delay = index * MOTION.leds.staggerMs;
- const onset = inset.animate(
- [
- { fill: ink, opacity: 0.4, filter: 'drop-shadow(0 0 0 transparent)' },
- { fill: accent, opacity: 1, filter: lit },
- ],
- {
- duration: MOTION.leds.onsetMs,
- delay,
- easing: 'ease-out',
- fill: 'both',
- }
- );
- ledAnimations.push(onset);
- // Spark fades in over the same onset window and holds.
- if (spark) {
- ledAnimations.push(
- spark.animate([{ opacity: 0 }, { opacity: 0.9 }], {
- duration: MOTION.leds.onsetMs,
- delay,
- easing: 'ease-out',
- fill: 'both',
- })
- );
- }
- // Halo flashes big as the LED comes on, then settles to the breathe
- // baseline; the endless breathe picks up from there. (Motion only —
- // reduced-motion leaves the halo hidden.)
- if (halo && motion) {
- const flash = halo.animate(
- [
- { transform: `scale(${MOTION.leds.halo.startScale})`, opacity: 0 },
- {
- transform: `scale(${MOTION.leds.halo.peakScale})`,
- opacity: MOTION.leds.halo.peakOpacity,
- offset: 0.45,
- },
- {
- transform: `scale(${MOTION.leds.halo.restingScale})`,
- opacity: MOTION.leds.halo.restingOpacity,
- },
- ],
- {
- duration: MOTION.leds.haloFlashMs,
- delay,
- easing: 'ease-out',
- fill: 'both',
- }
- );
- ledAnimations.push(flash);
- flash.finished
- .then(() => {
- // Breathe: expand and contract, synced with the glow pulse.
- const breathe = halo.animate(
- [
- {
- transform: `scale(${MOTION.leds.halo.restingScale})`,
- opacity: MOTION.leds.halo.restingOpacity,
- },
- {
- transform: `scale(${MOTION.leds.halo.breatheScale})`,
- opacity: MOTION.leds.halo.breatheOpacity,
- },
- {
- transform: `scale(${MOTION.leds.halo.restingScale})`,
- opacity: MOTION.leds.halo.restingOpacity,
- },
- ],
- {
- duration: MOTION.leds.breatheMs,
- iterations: Number.POSITIVE_INFINITY,
- easing: 'ease-in-out',
- }
- );
- ledAnimations.push(breathe);
- })
- .catch(() => {
- // finished rejects when darkenLeds() cancels the flash.
- });
- }
- onset.finished
- .then(() => {
- if (!motion) return;
- const pulse = inset.animate(
- [
- { filter: lit, opacity: 1 },
- { filter: bright, opacity: 0.9 },
- { filter: lit, opacity: 1 },
- ],
- {
- duration: MOTION.leds.breatheMs,
- iterations: Number.POSITIVE_INFINITY,
- }
- );
- ledAnimations.push(pulse);
- })
- .catch(() => {
- // finished rejects when darkenLeds() cancels a pending onset.
- });
- });
- };
-
- // Slide the back card's front section out and back once along its pipes —
- // the isometric depth axis, unit vector (0.7245, 0.6892) from the pipe
- // paths (e.g. "M740.7,486.2 l-51.3,-48.8"), in user units so it scales
- // with the scene. Driven imperatively (WAAPI) rather than by a CSS
- // animation: the page's Suspense boundary re-attaches this subtree when a
- // query above it re-suspends (e.g. failing queries retrying), and
- // re-inserted elements cancel and replay CSS animations, while WAAPI
- // animations survive.
- const playSlide = () => {
- if (props.poweredUp) return; // no card slide in the static powered finale
- if (!animatingCard || slideAnimation?.playState === 'running') return;
- darkenLeds();
- slideAnimation = animatingCard.animate(
- [
- {
- transform: 'translate(0, 0)',
- easing: 'cubic-bezier(0.16, 1, 0.3, 1)',
- },
- {
- transform: `translate(${MOTION.cardSlide.distance.x}px, ${MOTION.cardSlide.distance.y}px)`,
- offset: MOTION.cardSlide.outOffset,
- easing: 'linear',
- },
- {
- transform: `translate(${MOTION.cardSlide.distance.x}px, ${MOTION.cardSlide.distance.y}px)`,
- offset: MOTION.cardSlide.holdOffset,
- easing: 'cubic-bezier(0.3, 0, 0.2, 1)',
- },
- { transform: 'translate(0, 0)' },
- ],
- { duration: MOTION.cardSlide.durationMs }
- );
- slideAnimation.finished.then(illuminateLeds).catch(() => {
- // finished rejects if a fresh slide cancels this one; that slide
- // owns the next illuminate.
- });
- };
-
- onMount(() => {
- const groups = svg ? [...svg.querySelectorAll<SVGGElement>('.led')] : [];
- leds = groups
- .flatMap((group) => {
- const inset = group.querySelector<SVGElement>('.led-inset');
- if (!inset) return [];
- const halo = group.querySelector<SVGGraphicsElement>('.led-halo');
- const spark = group.querySelector<SVGGraphicsElement>('.led-spark');
- // Fit the halo/spark to the inset's geometry (getBBox is transform-
- // independent, so this is correct even mid-slide).
- const box = (inset as SVGGraphicsElement).getBBox();
- const cx = box.x + box.width / 2;
- const cy = box.y + box.height / 2;
- if (halo) {
- // Nudge the halo center down-and-right off the inset center, so the
- // glow sits slightly below/ahead of the bulb rather than dead on.
- halo.setAttribute('cx', `${cx + box.width * 0.22}`);
- halo.setAttribute('cy', `${cy + box.height * 0.32}`);
- halo.setAttribute('r', `${Math.max(box.width, box.height) * 0.9}`);
- }
- if (spark) {
- // Upper-left of the ellipse — the implied light source.
- spark.setAttribute('cx', `${box.x + box.width * 0.3}`);
- spark.setAttribute('cy', `${box.y + box.height * 0.28}`);
- spark.setAttribute('r', `${box.width * 0.13}`);
- }
- return [{ inset, halo, spark, cy }];
- })
- // Illuminate bottom-to-top by screen height (larger y = lower = first),
- // so the front card's LED joins the back card's sweep by position.
- .sort((a, b) => b.cy - a.cy)
- .map(({ inset, halo, spark }) => ({ inset, halo, spark }));
- // Powered from the start: skip the slide + LED sweep — the finale is a
- // static state (cards filled, modules faded, LEDs dark), driven by CSS.
- if (props.poweredUp) return;
- if (reducedMotion()) {
- // No slide, no pulse — just show the LEDs already lit.
- illuminateLeds();
- return;
- }
- slideDelay = setTimeout(playSlide, MOTION.cardSlide.delayMs);
- });
-
- // Powering up/down after mount. On: cancel any pending slide and kill the
- // LED animations, so the white sparks (and halos) return to their hidden
- // CSS resting state under `.powered` — a running WAAPI animation would
- // otherwise keep them lit over the CSS. Off: relight the LEDs. Deferred, so
- // the initial state is left to onMount above.
- createEffect(
- on(
- () => props.poweredUp,
- (powered) => {
- if (powered) {
- clearTimeout(slideDelay);
- darkenLeds();
- } else if (leds.length && !reducedMotion()) {
- illuminateLeds();
- }
- },
- { defer: true }
- )
- );
-
- return (
- <svg
- ref={svg}
- // Framed tightly to the actual content (modules + blocks + connectors),
- // not the original artboard: the top module's rings sit above the old
- // y=0 and were clipped, and the artboard left ~140 units of dead space
- // below the blocks. The padding absorbs the modules' bob/breathe. `meet`
- // then always shows the whole scene, and the tighter frame keeps the
- // modules near the top edge and the blocks near the bottom.
- viewBox={SCENE.viewBox}
- fill="currentColor"
- class={`setup-graphic text-ink ${props.poweredUp ? 'powered ' : ''}${props.class ?? ''}`}
- onClick={playSlide}
- aria-hidden="true"
- >
- <g class="scene">
- {/* Tethers that sit behind every card. */}
- <g class="connectors">
- <For each={connectorsIn('back')}>
- {(connector) => (
- <>
- <path class="connector" d={connector.d} />
- <Show when={connector.downloading}>
- <DownloadPulse d={connector.d} />
- </Show>
- </>
- )}
- </For>
- </g>
- {/* The block assembly, shrunk to 2/3 about its center so the modules
- can orbit farther out around it. */}
- <g class="blocks" transform={BLOCKS_TRANSFORM}>
- <g id="back_card">
- <g id="stable_card">
- <path
- class="card-back"
- d="M743.3,606l-60.4,24.1-6.7-3.6-173.4-164.4v-239.6l2.4-6.8,4.4-2.2,53.7-21.5,6.7,3.6,173.4,164.4v245.9Z"
- />
- <path class="guide" d="M513.1,217l166.3,157.7" />
- <path class="guide" d="M676.2,619v-73.3" />
- <path
- class="arc"
- d="M634.9,458.9c2.7-13,12.4-15.3,23.9-4.3l17.3,16.4"
- />
- <path
- class="vent"
- d="M673.9,540.3l-15-14.2c-13.6-12.9-24.7-39.4-24.7-59.1s0-1.9,0-2.8"
- />
- <path
- class="vent"
- d="M535.4,221.2c1.8-3.6,5.5-6.8,11-9,12.4-5,29-2.8,37.1,4.8h0s33.1,31.5,33.1,31.5c2.5,2.4,3.9,5,4.2,7.7"
- />
- <path
- class="arc"
- d="M620.1,261.5c-1.6,3.9-5.5,7.5-11.4,9.8-12.4,5-29,2.8-37-4.8l-33.2-31.5h0c-3.8-3.6-5-7.7-4-11.6"
- />
- <path
- class="vent"
- d="M536.9,225.2c2.1-2.6,5.3-5,9.5-6.7,12.4-5,29-2.8,37.1,4.8l33.2,31.5"
- />
- <path class="guide" d="M676.2,465.7v-78.7l6.7-9,53.7-21.5" />
- <path
- class="card-back"
- d="M783.3,526.6l-73-69.2-34,13.6-17.3-16.4c-8.7,4.5-12.2,8.2-12.2,8.2-3.5,14.1,4.8,22.6,4.8,22.6l89.2,84.6"
- />
- <path
- class="knob"
- d="M743.3,572c-4.1-2.6-6.6-7.2-6.6-13.4,0-13.2,11.4-28.5,25.5-34.1,14.1-5.6,25.5.5,25.5,13.7s-11.4,28.5-25.5,34.1-14.2,2.6-18.8-.3"
- />
- <path class="guide" d="M678.9,541.1l22.1-8.8" />
- <path
- class="card-back"
- d="M740.7,486.2l-51.3-48.8c-3-2.7-4.8-6.8-4.8-12.1,0-13.2,11.4-28.5,25.5-34.1,9.3-3.7,17.4-2.3,21.8,2.9l51.5,48.8"
- />
- <path
- class="knob"
- d="M743.3,488.3c-4.1-2.6-6.6-7.2-6.6-13.4,0-13.2,11.4-28.5,25.5-34.1,14.1-5.6,25.5.5,25.5,13.7s-11.4,28.5-25.5,34.1-14.2,2.6-18.8-.3"
- />
- <path
- class="card-back"
- d="M740.7,653.7l-51.3-48.8c-3-2.7-4.8-6.8-4.8-12.1,0-13.2,11.4-28.5,25.5-34.1,9.3-3.7,17.4-2.3,21.8,2.9l51.5,48.8"
- />
- <path
- class="knob"
- d="M743.3,655.8c-4.1-2.6-6.6-7.2-6.6-13.4,0-13.2,11.4-28.5,25.5-34.1,14.1-5.6,25.5.5,25.5,13.7s-11.4,28.5-25.5,34.1-14.2,2.6-18.8-.3"
- />
- <line class="vent" x1="513.3" y1="394" x2="513.3" y2="457.6" />
- <line class="vent" x1="518.2" y1="397.5" x2="518.2" y2="462.2" />
- <line class="vent" x1="523.4" y1="402.6" x2="523.4" y2="467.2" />
- <path class="guide" d="M563.9,222.1l-21.2,8.5" />
- <path class="guide" d="M609.1,262.9l-21.2,8.5" />
- <g class="dot">
- <path d="M565.5,229c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M573,231.8c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M574.1,237.1c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M581.6,239.9c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M582.7,245.3c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M590.2,248.1c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M591.3,253.4c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M598.8,256.2c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M599.9,261.6c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M559.1,231.5c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M566.6,234.3c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M567.7,239.7c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M575.2,242.5c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M576.3,247.8c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M583.8,250.6c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M584.9,256c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M592.4,258.8c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M593.5,264.1c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M552.7,234.1c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M560.2,236.9c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M561.3,242.2c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M568.8,245c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M569.9,250.4c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M577.4,253.2c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M578.5,258.5c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M586,261.3c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M587.1,266.7c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M553.8,239.4c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M562.4,247.6c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M571,255.7c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- <path d="M579.6,263.9c-.8.3-2,.2-2.5-.3s-.3-1.2.5-1.5,2-.2,2.5.3.3,1.2-.5,1.5Z" />
- </g>
- <path
- class="guide"
- d="M507.1,261.5l67.4,63.9v-18.2h.8s91.5,86.7,91.5,86.7v58.6"
- />
- {/* Stable half of the back card's left-face shading. The
- Illustrator export had one polygon spanning the whole
- assembly; it's split along the sliding piece's outline so
- the moving half (in animating_card) travels with the
- slide. */}
- <path
- class="shade"
- d="M502.8,222.6 L685.5,396 L685.5,480 L702.2,495.9 C715.8,508.8 726.9,535.3 726.9,557 L706.7,537.8 L704.9,539.7 L692.6,548.8 L685.7,551.5 L685.7,635.5 L502.8,462.1 Z"
- />
- </g>
- <g id="animating_card" ref={animatingCard}>
- <path
- class="panel"
- d="M837.9,514.7l2.1-6.2v-56.6l-87.4-82.9-6.7-3.6-53.7,21.5-6.7,9v84.1l16.7,15.9c13.6,12.9,24.7,39.4,24.7,59.1s0,1.9,0,2-.2-.1-.2-.1l-20.2-19.2-.7.9-1.1,1-12.3,9.1-6.9,2.7v84.1l87.4,82.9,6.7,3.6,53.7-21.5,4.4-2.2,2.4-6.8v-57l-1.3-2.7h0s1.3-3.8,1.3-3.8v-112.4l-2.1-.8Z"
- />
- <path class="guide" d="M830.7,637.5l7-2.8,1-3" />
- <path class="guide" d="M838.6,512.7l-2.4,6.8-6.2,2.6" />
- <path class="edge" d="M793.5,705.9v-47l-1.6-7.4" />
- <path class="guide" d="M816.8,681.3l7.9,7.5" />
- <path
- class="edge"
- d="M814.6,477.9l2.3,4.5,1.9,4.3,1.7,4.4,1.5,4.5,1.3,4.5,1.1,4.4,1.2,6.5.5,4.2.3,5.8v134.3s-.2,3.9-.2,3.9l-.4,3.5-.7,3.2-1.1,3.8-1.7,4-1.3,2.3-1.5,2.2-2.6,3-4.1,3.3-4.6,2.3-5,1.3-4,.3-5.7-.6"
- />
- <path class="guide" d="M830.1,449.5l-50.4,20.2-84.6-80.2" />
- <path
- class="guide"
- d="M828.2,475.4v43.8l-1.7,4.7,1.7,2.3v112.4l-1.7-1,1.7,7.6v47l-31.3,12.5"
- />
- <path
- class="edge"
- d="M791.9,651.5l1.6-5v-106.6l-1.7-2.1,1.7-4.8v-46.7l34.6-13.8"
- />
- <path
- class="guide"
- d="M789.4,538.8l-5.6,2.2-10.5-1.4-41.3-9.4v57.6c-.1,0,41,66.8,41,66.8l11.1,1.4,5.3-2.1"
- />
- <path
- class="vent"
- d="M726.9,556.8c0,19.7-11,25.2-24.7,12.3l-13.6-14.6"
- />
- <line class="vent" x1="693.6" y1="430.6" x2="693.6" y2="474.6" />
- <line class="vent" x1="698.5" y1="434.9" x2="698.5" y2="479.2" />
- {/* Three inset LED indicators (top → bottom in source order).
- Each is a ring (arc/vent arcs) around an inset dot
- (dot.led-inset); the illuminate pass lights the dot, fades
- in the white specular spark, and pulses the halo ring. The
- halo/spark circles are positioned onto the inset at mount
- (getBBox), so their placeholder geometry here is unused. */}
- <g class="led">
- <circle class="led-halo" />
- <path
- class="arc"
- d="M812.7,572.7c-2-.5-3.2-2-3.2-4.4,0-3.8,3.3-8.2,7.3-9.8s4.8-.7,6.1.6"
- />
- <path
- class="vent"
- d="M824.2,562.4c0,3.8-3.3,8.2-7.3,9.8s-1,.4-1.5.5"
- />
- <path
- class="dot led-inset"
- d="M819.2,562c0,2-1.8,4.4-3.9,5.3s-3.9,0-3.9-2.1,1.8-4.4,3.9-5.3,3.9,0,3.9,2.1Z"
- />
- <circle class="led-spark" />
- </g>
- <g class="led">
- <circle class="led-halo" />
- <path
- class="arc"
- d="M812.7,597.7c-2-.5-3.2-2-3.2-4.4,0-3.8,3.3-8.2,7.3-9.8s4.8-.7,6.1.6"
- />
- <path
- class="vent"
- d="M824.2,587.4c0,3.8-3.3,8.2-7.3,9.8s-1,.4-1.5.5"
- />
- <path
- class="dot led-inset"
- d="M819.2,587c0,2-1.8,4.4-3.9,5.3s-3.9,0-3.9-2.1,1.8-4.4,3.9-5.3,3.9,0,3.9,2.1Z"
- />
- <circle class="led-spark" />
- </g>
- <g class="led">
- <circle class="led-halo" />
- <path
- class="arc"
- d="M812.7,622.7c-2-.5-3.2-2-3.2-4.4,0-3.8,3.3-8.2,7.3-9.8s4.8-.7,6.1.6"
- />
- <path
- class="vent"
- d="M824.2,612.4c0,3.8-3.3,8.2-7.3,9.8s-1,.4-1.5.5"
- />
- <path
- class="dot led-inset"
- d="M819.2,612c0,2-1.8,4.4-3.9,5.3s-3.9,0-3.9-2.1,1.8-4.4,3.9-5.3,3.9,0,3.9,2.1Z"
- />
- <circle class="led-spark" />
- </g>
- {/* Moving half of the back card's left-face shading — lives in
- this group so it slides with the piece. */}
- <path
- class="shade"
- d="M685.5,396 L773,479.2 L773,718.3 L685.7,635.5 L685.7,551.5 L692.6,548.8 L704.9,539.7 L706.7,537.8 L726.9,557 C726.9,535.3 715.8,508.8 702.2,495.9 L685.5,480 Z"
- />
- </g>
- </g>
- {/* Tethers behind the middle card but in front of the back card.
- Counter-transformed so their absolute coords survive being
- nested in the scaled blocks group. */}
- <g class="connectors" transform={INVERSE_BLOCKS_TRANSFORM}>
- <For each={connectorsIn('mid')}>
- {(connector) => (
- <>
- <path class="connector" d={connector.d} />
- <Show when={connector.downloading}>
- <DownloadPulse d={connector.d} />
- </Show>
- </>
- )}
- </For>
- </g>
- <g id="middle_card">
- <path
- class="card-mid"
- d="M204.8,268.2l-14.7,5.9-2.4,6.8v180.9h0s110.7,105,110.7,105l3.1,1.7v1.3l43.4,41.2,2.9,1.6v1.3c0,0,110,104.2,110,104.2l6.7,3.6,53.7-21.5,4.4-2.2,2.4-6.8v-239.6l-214.8-203.6-6.7-3.6-15.1,6-14.1-13.4-2.4-2.1-3.6-2.5-2.4-1.3-2.4-1-3.7-1-2.6-.3h-2.2s-2.5.4-2.5.4l-2.4.7-3.2,1.6-2.8,2.3-1.4,1.6-2.6-.2-2.6.2-3.5.9-2.3,1.1-1.8,1.1-2,1.7-1.4,1.6-2.6-.2-3.6.4-2.4.7-3.2,1.6-2.8,2.3-1.7,2-1.3,1.9-1.8,3.5-1.5,5.3-.5,3-.2,2.7v3.3c-.1,0-.1,0-.1,0Z"
- />
- <path class="edge" d="M347.6,494.2l-1.5-3.9-44-41.7-.7,3.8v112.6" />
- <path class="guide" d="M347.6,608.6v-112" />
- <path class="guide" d="M510,693l-28.1,11.2" />
- <path class="guide" d="M500.7,680.8l9.3,8.8" />
- <path
- class="edge"
- d="M477.9,685.3l2.5.2,5.2-.6,3.8-1.1,1.1-.5,3.5-1.9,1-.7,3.1-2.5,3.4-4.1,2.6-4.7,1.1-2.8.7-2.4,1.1-4.7.4-3.5.2-3.9v-134.3s-.3-5.8-.3-5.8l-.5-4.2-.8-4.3-1-4.4-1.2-4.5-1.4-4.5-1.6-4.5-3.3-7.6"
- />
- <path
- class="edge"
- d="M272.3,256.8l-14.1-13.4-3.6-3-2.4-1.6-3.6-1.9-3.7-1.2-2.2-.4"
- />
- <path
- class="edge"
- d="M256.2,263.3l-14.1-13.4-2.4-2.1-1.9-1.4-2.9-1.8-2.4-1.2-3.7-1.2-2.2-.4"
- />
- <path class="guide" d="M239.8,330.2l-48.5-46" />
- <path class="edge" d="M288.4,250.4l-38.6,15.4-6.7,9v58.6" />
- <path class="guide" d="M253.4,269.2l211.2,200.2,51.1-20.4" />
- <path
- class="hairline"
- d="M242.7,275.9l-14.7-12.9-2.3-1.6-1,.5-.7,4.3v1.5s0,16.9,0,16.9c0,1.9-1.5,3.6-4.3,4.7-4.5,1.8-10.4,1-13.3-1.7s-1.5-2-1.5-3v-16.3"
- />
- <path
- class="hairline"
- d="M224.3,282.7c2.8.7,6.2.6,9-.5s4.3-2.8,4.3-4.7v-6.1"
- />
- <path class="guide" d="M512.6,476.4v210.8" />
- <path class="edge" d="M477.9,705.8v-219.6l34.6-13.8" />
- <g class="dot">
- <path d="M325.5,566.8c0,2.2-1.2,2.8-2.7,1.4s-2.7-4.3-2.7-6.5,1.2-2.8,2.7-1.4,2.7,4.3,2.7,6.5Z" />
- <path d="M331.3,587.1c0,2.2-1.2,2.8-2.7,1.4s-2.7-4.3-2.7-6.5,1.2-2.8,2.7-1.4,2.7,4.3,2.7,6.5Z" />
- <path d="M319.6,576.1c0,2.2-1.2,2.8-2.7,1.4s-2.7-4.3-2.7-6.5,1.2-2.8,2.7-1.4,2.7,4.3,2.7,6.5Z" />
- </g>
- <path
- class="guide"
- d="M436.5,618.3l12.5,11.8v68l-92.8-88h0s-.5-121.5-.5-121.5l-61.3-58.1v121h0s-92.4-87.6-92.4-87.6"
- />
- <path
- class="vent"
- d="M427.9,624.2c-1.4-.3-3-1.3-4.7-2.9-5.9-5.6-10.7-17.1-10.7-25.6s.2-3,.5-4.1"
- />
- <path
- class="arc"
- d="M414.4,588.7c1.9-2.3,5.2-1.9,8.9,1.6,5.9,5.6,10.7,17.1,10.7,25.6,0,4.3-1.2,7-3.1,8"
- />
- <polygon
- class="shade"
- points="187.7 280.9 187.7 461.9 457.9 718 457.9 477.7 243.1 274.8 242.7 332.9 187.7 280.9"
- />
- </g>
- <g id="front_card">
- <path
- class="card-front"
- d="M167.8,699.5l8.4-1.1h3.9c0,.1,6.9,1.2,6.9,1.2l3.1.8,7.2,2.9,6.8-2.7,4.4-2.2,2.4-6.8v-239.6l-95.9-90.9-6.7-3.6-53.7,21.5-4.4,2.2-2.4,6.8v116.4l1.6,1.9-1.6,4.7v116.5l46.2,43.8,3.4,1.9v1.4l46.3,43.9,6.7,3.6,4.5-1.8,3.1-1.7.8-6.2,1.9-7,1.7-3.8"
- />
- <path
- class="edge"
- d="M162.4,701.7l1.5-3.5,4.1-6.1,2.4-3.3,4.9-4.1,1.8-1.5,6.7-2.7,6.7.3,6.3,4,.4.5,2.9,4.5,1.9,5.5.8,5.5"
- />
- <path class="card-front" d="M162.3,701.7l5.4-2.2" />
- <path class="guide" d="M153.7,468.6l-3.4,1.3-93.5-88.7" />
- <path class="guide" d="M156.1,410.4l42.5,40.3,4.4,10.4v69.6" />
- <path class="guide" d="M52.7,510.1l43.4,41.2,1.3,3.6v114.1" />
- <path
- class="edge"
- d="M163.9,698.2l2.1-1,1.8-1.1,2-1.7,1.4-1.6,1.6-2.3,1.3-2.3,1.3-3.5"
- />
- <path
- class="edge"
- d="M171.1,692.7l2.6.2,3.6-.4,2.4-.7,3.2-1.6,2.8-2.3,1.7-2,1.3-1.9,1.7-3.4"
- />
- <path class="guide" d="M154.2,413.7v11.7" />
- <path
- class="guide"
- d="M115.4,424.1l9.5-3.8.8-.3,15.3-6.1.8-.3,9.3-3.7"
- />
- <path class="edge" d="M160.8,552v-74l-4.4-10.4-37.8-35.8-6.6-6.3" />
- <path class="guide" d="M199.9,536.3l-35.3,14.1" />
- <path class="guide" d="M191.2,523.9l8.7,8.3" />
- <path
- class="hairline"
- d="M133,427.2c1.2-3.5,4.3-6.9,8-8.4s5.5-.8,7,.7l.6.6,18.5,17.5s22,20.6,24.2,57.8v37.7c0,2.1-1.7,3.9-4.8,5.1s-8,1.3-11.3,0"
- />
- <path
- class="hairline"
- d="M118.5,431.6c1.6-2.6,4-4.8,6.8-5.9s5.5-.8,7,.7h0s19.7,18.7,19.7,18.7c0,0,19.2,18.7,23,56.8v37.4h0c0,2-1.7,4-4.7,5.2-3,1.2-6.5,1.3-9.5.5"
- />
- <path
- class="vent"
- d="M129.6,559.3c-.6-.5-1.3-1-1.9-1.6-8-7.6-14.6-23.2-14.6-34.9h0v-48l.3-3.9.3-1.7.5-1.5.8-1.5"
- />
- <path
- class="hairline"
- d="M135.8,553.7c0,11.6-6.5,14.9-14.6,7.3-8-7.6-14.6-23.2-14.6-34.9v-50.7c0-11.7,6.6-14.9,14.7-7.3s14.5,23.3,14.5,34.9v50.7h0Z"
- />
- <line class="vent" x1="56.8" y1="454.9" x2="56.8" y2="498.9" />
- <line class="vent" x1="61.7" y1="459.2" x2="61.7" y2="503.6" />
- {/* The front card's single LED — same treatment as the back
- card's three (ring arcs, inset dot, halo, spark). */}
- <g class="led">
- <circle class="led-halo" />
- <path
- class="arc"
- d="M175.6,574.4c-1.8-1-2.9-2.8-2.9-5.4,0-5.1,4.4-11,9.9-13.2s5.2-1,7,0"
- />
- <path
- class="vent"
- d="M191.5,557.6c.6,1,1,2.2,1,3.6,0,5.1-4.4,11-9.9,13.2s-3.3.9-4.6.8"
- />
- <path
- class="dot led-inset"
- d="M184.8,560.4c0,2.6-2.2,5.6-5,6.7s-5-.1-5-2.7,2.2-5.6,5-6.7,5,.1,5,2.7Z"
- />
- <circle class="led-spark" />
- </g>
- <g class="dot">
- <path d="M72.7,624.6c0,2.2-1.2,2.8-2.7,1.4s-2.7-4.3-2.7-6.5,1.2-2.8,2.7-1.4,2.7,4.3,2.7,6.5Z" />
- <path d="M78.5,644.9c0,2.2-1.2,2.8-2.7,1.4s-2.7-4.3-2.7-6.5,1.2-2.8,2.7-1.4,2.7,4.3,2.7,6.5Z" />
- <path d="M66.9,633.8c0,2.2-1.2,2.8-2.7,1.4s-2.7-4.3-2.7-6.5,1.2-2.8,2.7-1.4,2.7,4.3,2.7,6.5Z" />
- </g>
- <polyline
- class="shade"
- points="47.8 388.1 47.8 627.6 143.7 718.5 143.7 480.4"
- />
- </g>
- {/* Invisible geometry reference: the Macro logo at the exact spot
- the designer superimposed it over these blocks (authored in the
- source artwork with no transform, so its coords are in the same
- space as the card paths above — hence its place here, inside
- `.blocks`). Never painted; it exists so a brand handoff can
- measure where the real logo belongs via
- `getBoundingClientRect()` and let the browser resolve the
- viewBox + transform math, instead of hardcoding pixel offsets
- that would drift with the scene's size. */}
- <g class="logo-ref" aria-hidden="true">
- <path d="M47.8,389.1v224.9c.2,6.4,2.9,12.5,7.4,17l90.7,87.4,66.2-26.5v-234.7l-98.2-94.5-66.1,26.5Z" />
- <path d="M182.7,216.7v191.3l45,43.3v43.4l232.9,224.6,66.2-26.5v-234.8S248.8,190.2,248.8,190.2l-66.1,26.5Z" />
- <path d="M497.3,216.7v191.3l45,43.4-.4,43,233.4,225,66.1-26.5v-224.2c0-6.6-2.7-13-7.4-17.6l-270.5-260.8-66.2,26.5Z" />
- </g>
- </g>
- {/* Tethers to front features draw over the cards. */}
- <g class="connectors">
- <For each={connectorsIn('front')}>
- {(connector) => (
- <>
- <path class="connector" d={connector.d} />
- <Show when={connector.downloading}>
- <DownloadPulse d={connector.d} />
- </Show>
- </>
- )}
- </For>
- </g>
- {/* Modules: the configured slots, phase-offset so they don't bob in
- unison. */}
- <g class="modules">
- <For each={modules()}>
- {(module, index) => (
- <Module
- place={SLOTS[module.slot].place}
- logo={module.logo}
- state={module.state}
- phaseMs={-index() * MOTION.modulePhaseMs}
- />
- )}
- </For>
- </g>
- </g>
- </svg>
- );
-}
diff --git a/apps/web/src/features/setup/flow/BrandHandoff.tsx b/apps/web/src/features/setup/flow/BrandHandoff.tsx
deleted file mode 100644
index 304f12fe02..0000000000
--- a/apps/web/src/features/setup/flow/BrandHandoff.tsx
+++ /dev/null
@@ -1,219 +0,0 @@
-import LogoIcon from '@icon/macro-logo.svg';
-import { onCleanup, onMount } from 'solid-js';
-import { Portal } from 'solid-js/web';
-
-/** A viewport rect (getBoundingClientRect-style). */
-export type HandoffRect = {
- x: number;
- y: number;
- width: number;
- height: number;
-};
-
-/** The exact rendered loading scene captured just before it leaves the page. */
-export type BrandHandoffSource = {
- /** Viewport bounds of the powered loading SVG. */
- scene: HandoffRect;
- /** Square Macro-logo box inside {@link scene}, in scene-relative pixels. */
- logo: HandoffRect;
- /** Serialized powered loading SVG, used by the transient overlay. */
- snapshot: string;
-};
-
-/**
- * `macro-logo.svg` is a *square* 24×24 viewBox, but its mark only occupies
- * y 4→20 — the full width, two thirds of the height. So rendering it in a
- * square box of side S paints the mark at width S, height S·2/3, inset S/6
- * from the box's top. Sizing the box to the mark's rect (the obvious thing)
- * therefore draws the mark a third too small.
- */
-const LOGO_VIEWBOX = 24;
-const LOGO_MARK_TOP = 4;
-
-/**
- * The square box to render {@link LogoIcon} in so its *mark* lands exactly on
- * `mark`. Anchored on width, which the mark spans edge to edge.
- */
-export function logoBoxForMark(mark: HandoffRect): HandoffRect {
- const side = mark.width;
- return {
- x: mark.x,
- y: mark.y - side * (LOGO_MARK_TOP / LOGO_VIEWBOX),
- width: side,
- height: side,
- };
-}
-
-/** The travel from the loading scene to the summary header's logo slot. */
-const MOVE_MS = 780;
-/** The graphic → logo dissolve deliberately waits until the latter half of
- * the travel, when the scene is already compact and near its header slot.
- * The logo leads slightly so the pair never dips dark mid-crossfade. */
-const GRAPHIC_FADE_START = 0.58;
-const GRAPHIC_FADE_END = 0.92;
-const LOGO_FADE_START = 0.52;
-const LOGO_FADE_END = 0.84;
-/** Give the newly-rendered summary logo up to roughly one second to mount. */
-const TARGET_RETRY_LIMIT = 60;
-
-/**
- * Building → summary brand handoff: the powered-up loading scene shrinks to
- * the summary header's logo slot, dissolving into the real Macro logo *as* it
- * travels — the movement covers the fact that the isometric mark and the flat
- * logo aren't quite the same geometry.
- *
- * The overlay is the scene's own frame (a clone of the powered graphic filling
- * it, with the logo laid over the mark inside it), so scaling the frame moves
- * graphic and logo in lockstep and the two marks stay aligned for the whole
- * crossfade. The transform is solved so the *logo* lands on the target: both
- * it and the header slot are square boxes rendering the same square viewBox,
- * so matching them centre-to-centre with a uniform scale necessarily matches
- * the marks inside.
- *
- * Rendered through a Portal to `document.body` so `position: fixed` resolves
- * against the viewport regardless of any transformed ancestor in the flow
- * (the flow's own card mount animation ends on a non-`none` `transform`,
- * which — per spec — establishes a containing block for `fixed` descendants;
- * without the Portal this silently breaks the positioning).
- *
- * The building step's `Stepper.Step` is marked `noTransition` so it's torn
- * down the instant we advance: a fading exit would leave the original graphic
- * visible right where this clone appears, i.e. two overlapping copies.
- *
- * `onDone` fires when the move lands, so the flow can reveal the real summary
- * logo (pixel-identical to where this settled) in the same tick this is
- * dropped.
- */
-export function BrandHandoff(props: {
- /** The loading scene's `.setup-graphic` rect, in viewport coords. */
- scene: HandoffRect;
- /** The logo's square box *relative to `scene`* — where the flat logo sits
- * over the isometric mark (see {@link logoBoxForMark}). */
- logo: HandoffRect;
- /** outerHTML of the powered `.setup-graphic`, cloned to fill the frame. */
- snapshot: string;
- /** Selector for the destination logo (rendered on the summary step). */
- targetSelector: string;
- onDone: () => void;
-}) {
- let frame: HTMLDivElement | undefined;
- let graphicEl: HTMLDivElement | undefined;
- let logoEl: HTMLDivElement | undefined;
- let raf1 = 0;
- let raf2 = 0;
- let targetRetries = 0;
- const anims: Animation[] = [];
- onCleanup(() => {
- cancelAnimationFrame(raf1);
- cancelAnimationFrame(raf2);
- for (const anim of anims) anim.cancel();
- });
-
- onMount(() => {
- const run = () => {
- const target = document.querySelector(props.targetSelector);
- if (!target || !frame) {
- targetRetries += 1;
- if (targetRetries >= TARGET_RETRY_LIMIT) {
- props.onDone();
- return;
- }
- raf1 = requestAnimationFrame(run);
- return;
- }
- const to = target.getBoundingClientRect();
- // `transform-origin` is the frame's top-left, so a point (lx, ly) local
- // to the frame lands at (scene.x + lx·scale + dx, …). Solve for the
- // logo's local box to land on the target.
- const scale = to.width / props.logo.width;
- const dx = to.x - props.scene.x - props.logo.x * scale;
- const dy = to.y - props.scene.y - props.logo.y * scale;
-
- const timing = {
- duration: MOVE_MS,
- easing: 'cubic-bezier(0.6, 0, 0.2, 1)',
- fill: 'forwards' as const,
- };
- const move = frame.animate(
- [
- { transform: 'translate(0px, 0px) scale(1)' },
- { transform: `translate(${dx}px, ${dy}px) scale(${scale})` },
- ],
- timing
- );
- anims.push(move);
- // Dissolve during the travel. Linear so the two halves cross evenly
- // (the move's own easing already carries the motion's character).
- if (graphicEl) {
- anims.push(
- graphicEl.animate(
- [
- { opacity: 1, offset: 0 },
- { opacity: 1, offset: GRAPHIC_FADE_START },
- { opacity: 0, offset: GRAPHIC_FADE_END },
- { opacity: 0, offset: 1 },
- ],
- { duration: MOVE_MS, easing: 'linear', fill: 'forwards' }
- )
- );
- }
- if (logoEl) {
- anims.push(
- logoEl.animate(
- [
- { opacity: 0, offset: 0 },
- { opacity: 0, offset: LOGO_FADE_START },
- { opacity: 1, offset: LOGO_FADE_END },
- { opacity: 1, offset: 1 },
- ],
- { duration: MOVE_MS, easing: 'linear', fill: 'forwards' }
- )
- );
- }
- move.finished.then(props.onDone).catch(() => {});
- };
- // Two rAFs: the summary step's DOM has just swapped in; this lets layout
- // settle before measuring its logo slot, without a guessed timeout.
- raf1 = requestAnimationFrame(() => {
- raf2 = requestAnimationFrame(run);
- });
- });
-
- return (
- <Portal>
- <div
- ref={frame}
- aria-hidden="true"
- class="pointer-events-none fixed z-[60]"
- style={{
- left: `${props.scene.x}px`,
- top: `${props.scene.y}px`,
- width: `${props.scene.width}px`,
- height: `${props.scene.height}px`,
- 'transform-origin': 'top left',
- }}
- >
- {/* The powered scene, filling the frame exactly as it did in place. */}
- <div
- ref={graphicEl}
- class="absolute inset-0 [&_svg]:size-full [&_svg]:overflow-visible"
- innerHTML={props.snapshot}
- />
- {/* The flat logo, laid over the scene's mark inside the same frame. */}
- <div
- ref={logoEl}
- class="absolute text-accent"
- style={{
- left: `${props.logo.x}px`,
- top: `${props.logo.y}px`,
- width: `${props.logo.width}px`,
- height: `${props.logo.height}px`,
- opacity: 0,
- }}
- >
- <LogoIcon class="size-full" />
- </div>
- </div>
- </Portal>
- );
-}
diff --git a/apps/web/src/features/setup/flow/BuildingStep.tsx b/apps/web/src/features/setup/flow/BuildingStep.tsx
deleted file mode 100644
index 9ca9680702..0000000000
--- a/apps/web/src/features/setup/flow/BuildingStep.tsx
+++ /dev/null
@@ -1,239 +0,0 @@
-import { createSignal, onCleanup, onMount } from 'solid-js';
-import { createStore } from 'solid-js/store';
-import type { ModuleLogo } from '../Module';
-import { MODULE_LOGOS } from '../moduleLogos';
-import { type ModuleConfig, SetupGraphic } from '../SetupGraphic';
-import { type BrandHandoffSource, logoBoxForMark } from './BrandHandoff';
-
-/** Which tools the user connected during the flow — decides which modules
- * appear in the loading scene. */
-export type ConnectedTools = {
- google: boolean;
- linear: boolean;
- notion: boolean;
- slack: boolean;
- github: boolean;
-};
-
-/** The theatrical hold scales with how many accounts connected: a quick 5s
- * when there's nothing to show, up to the full 15s once more than two are
- * connected. The rest of the timeline compresses to fit. */
-const MIN_HOLD_MS = 5_000;
-const MAX_HOLD_MS = 15_000;
-
-/** A scripted, purely-theatrical fill for the progress bar: bursts of varying
- * speed with a couple of stalls between them (including a long one near the
- * end before the finish). `fill` eases the bar to `to`% over that many ms; a
- * `pause` just holds. Offsets accumulate and land ~100% just before the hold
- * ends. */
-type BarSegment = { to: number; fill: number } | { pause: number };
-const BAR_TIMELINE: BarSegment[] = [
- { to: 22, fill: 900 }, // initial climb
- { pause: 1600 },
- { to: 40, fill: 650 }, // quick surge
- { pause: 2800 }, // stall
- { to: 68, fill: 1100 },
- { pause: 1900 },
- { to: 86, fill: 550 }, // quick surge
- { pause: 3000 }, // long stall right before the finish
- { to: 100, fill: 1600 }, // final climb
-];
-/** A short beat before the first burst — also lets the 0% paint before the
- * first width change so its transition triggers (no mount-frame jump). */
-const BAR_START_DELAY_MS = 200;
-/** Easing per burst: fast off the mark, easing into each hold. */
-const BAR_EASING = 'cubic-bezier(0.22, 1, 0.36, 1)';
-
-/** Slots the connected accounts fill, in populate order. */
-const SLOT_ORDER = [
- 'frontPill',
- 'midBack',
- 'backFar',
- 'midFar',
- 'midPort',
-] as const;
-
-/** Tools in the order they're assigned to {@link SLOT_ORDER}, each with its
- * module logo. Filtered to the ones the user connected. */
-const TOOL_LOGOS: { key: keyof ConnectedTools; logo: ModuleLogo }[] = [
- { key: 'google', logo: MODULE_LOGOS.Google },
- { key: 'linear', logo: MODULE_LOGOS.Linear },
- { key: 'notion', logo: MODULE_LOGOS.Notion },
- { key: 'slack', logo: MODULE_LOGOS.Slack },
- { key: 'github', logo: MODULE_LOGOS.GitHub },
-];
-
-/** A beat of all-idle before the first module starts downloading. */
-const MODULE_IDLE_LEAD_MS = 700;
-/** After the last module links, a short buffer before powering up. */
-const POST_LINK_BUFFER_MS = 300;
-/** Hold on the fully powered graphic before handing off. The graphic → logo
- * dissolve runs during the handoff's travel (see BrandHandoff), so the
- * motion covers the geometry mismatch between the isometric mark and the
- * flat logo. */
-const POWERED_HOLD_MS = 700;
-/** Total time reserved after the last module links: buffer + hold. `onDone`
- * fires once this has played out. */
-const POWERED_TAIL_MS = POST_LINK_BUFFER_MS + POWERED_HOLD_MS;
-
-export function BuildingStep(props: {
- connected: ConnectedTools;
- onDone: (source: BrandHandoffSource | null) => void;
-}) {
- // Bar fill % and the transition duration for the current burst — set
- // together per segment so each burst eases over its own `fill` time.
- const [progress, setProgress] = createSignal(0);
- const [burstMs, setBurstMs] = createSignal(0);
-
- // The scene's modules: one per connected account, filling SLOT_ORDER. A
- // store (not a fresh array per change) so toggling a module's state updates
- // it in place — the For in SetupGraphic keeps each Module mounted, so its
- // ambient motion doesn't restart. Empty when nothing was connected: the
- // three cards still render on their own.
- const [modules, setModules] = createStore<ModuleConfig[]>(
- TOOL_LOGOS.filter((tool) => props.connected[tool.key]).map((tool, i) => ({
- slot: SLOT_ORDER[i],
- logo: tool.logo,
- state: 'idle',
- }))
- );
- const [poweredUp, setPoweredUp] = createSignal(false);
-
- // This holds the rendered SVG, not the outer scene wrapper: its viewport
- // rect and serialized markup are exactly what the portal overlay needs to
- // continue the scene without a visual jump.
- let sceneEl: HTMLDivElement | undefined;
-
- onMount(() => {
- // The hold scales 5s → 15s with the connected count (maxing out past two
- // accounts); the whole theatrical timeline compresses by `scale` to fit.
- const n = modules.length;
- const holdMs =
- MIN_HOLD_MS + (MAX_HOLD_MS - MIN_HOLD_MS) * (Math.min(n, 3) / 3);
- const scale = holdMs / MAX_HOLD_MS;
-
- // Cycle each module idle → downloading → linked, evenly spaced across the
- // hold and reserving a tail for the powered-up finale. Each module
- // downloads for its whole slice, then flips to linked as the next begins.
- const moduleTimers: ReturnType<typeof setTimeout>[] = [];
- const idleLead = MODULE_IDLE_LEAD_MS * scale;
- const tail = POWERED_TAIL_MS * scale;
- if (n > 0) {
- const window = holdMs - idleLead - tail;
- const slice = window / n;
- for (let i = 0; i < n; i++) {
- moduleTimers.push(
- setTimeout(
- () => setModules(i, 'state', 'downloading'),
- idleLead + i * slice
- )
- );
- moduleTimers.push(
- setTimeout(
- () => setModules(i, 'state', 'linked'),
- idleLead + (i + 1) * slice
- )
- );
- }
- }
- // Power up once everything's linked (or, with nothing connected, just
- // before the end). Modules are cleared in the same tick: SetupGraphic
- // fades `.modules` out over 700ms on `.powered`, and since they're
- // already `linked` (steady accent) by now, that lingering fade reads as
- // a stray offset logo hanging next to the cards as they fill in.
- // Clearing the array unmounts them outright — no separate exit
- // transition is wired up for the `<For>` — so power-up is a clean cut
- // straight to the cards.
- const powerAt = holdMs - tail + (n > 0 ? POST_LINK_BUFFER_MS * scale : 0);
- const powerTimer = setTimeout(() => {
- setModules([]);
- setPoweredUp(true);
- }, powerAt);
-
- // Capture the powered SVG after a beat, then let the parent mount a
- // portal overlay which moves this exact scene while dissolving it into the
- // flat Macro logo. Capturing rather than re-rendering avoids a one-frame
- // reset of the SVG's CSS/WAAPI state at the handoff boundary.
- const handoffAt = powerAt + POWERED_HOLD_MS * scale;
- const handoffTimer = setTimeout(() => {
- const graphic = sceneEl?.querySelector<SVGSVGElement>('.setup-graphic');
- const scene = graphic?.getBoundingClientRect();
- const mark = graphic?.querySelector('.logo-ref')?.getBoundingClientRect();
- if (!graphic || !scene || !mark) {
- props.onDone(null);
- return;
- }
- props.onDone({
- scene: {
- x: scene.x,
- y: scene.y,
- width: scene.width,
- height: scene.height,
- },
- // This is relative to the SVG's box because the portal frame starts
- // at that same box. `logoBoxForMark` accounts for the SVG icon's
- // vertical viewBox padding, so the *painted* logo aligns to the mark.
- logo: logoBoxForMark({
- x: mark.x - scene.x,
- y: mark.y - scene.y,
- width: mark.width,
- height: mark.height,
- }),
- snapshot: graphic.outerHTML,
- });
- }, handoffAt);
-
- // Progress bar: the same scripted bursts/stalls, compressed by `scale`.
- const timers: ReturnType<typeof setTimeout>[] = [];
- let offset = BAR_START_DELAY_MS * scale;
- for (const segment of BAR_TIMELINE) {
- if ('pause' in segment) {
- offset += segment.pause * scale;
- continue;
- }
- const { to, fill } = segment;
- const dur = fill * scale;
- timers.push(
- setTimeout(() => {
- setBurstMs(dur);
- setProgress(to);
- }, offset)
- );
- offset += dur;
- }
-
- onCleanup(() => {
- for (const timer of timers) clearTimeout(timer);
- for (const timer of moduleTimers) clearTimeout(timer);
- clearTimeout(powerTimer);
- clearTimeout(handoffTimer);
- });
- });
-
- return (
- <div class="flex flex-col items-center gap-8 py-16">
- {/* The isometric scene: three cards always present, with connected
- accounts cycling in before resolving into the powered Macro mark.
- Its exact final SVG is captured and carried by the parent handoff. */}
- <div ref={sceneEl} class="relative h-[28rem] w-full">
- <div class="absolute inset-0">
- <SetupGraphic
- class="size-full"
- modules={modules}
- poweredUp={poweredUp()}
- />
- </div>
- </div>
-
- <div class="h-1 w-48 overflow-hidden rounded-full bg-ink/10">
- <div
- class="h-full rounded-full bg-accent"
- style={{
- width: `${progress()}%`,
- transition: `width ${burstMs()}ms ${BAR_EASING}`,
- }}
- />
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/features/setup/flow/ConnectorStep.tsx b/apps/web/src/features/setup/flow/ConnectorStep.tsx
deleted file mode 100644
index b15cc58193..0000000000
--- a/apps/web/src/features/setup/flow/ConnectorStep.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import type { FeaturedMcpServer } from '@core/component/AI/constant/mcpServers';
-import { usePipedreamMcpFlag } from '@core/pipedream/flag';
-import { pipedreamSlugsMatch } from '@core/pipedream/slugs';
-import SpinnerIcon from '@phosphor/spinner-gap.svg';
-import { useMcpServersQuery } from '@queries/mcp-servers';
-import { usePipedreamConnectionsQuery } from '@queries/pipedream-connectors';
-import { Layer } from '@ui';
-import { createEffect, createMemo, Show } from 'solid-js';
-import { ConnectorRow } from '../ConnectorRow';
-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 pipedreamMcp = usePipedreamMcpFlag();
- const serversQuery = useMcpServersQuery({
- refetchInterval: 4_000,
- neverSuspend: true,
- });
- const pipedreamQuery = usePipedreamConnectionsQuery({
- refetchInterval: 4_000,
- neverSuspend: true,
- });
- const record = createMemo(() =>
- serversQuery.data?.find((server) => server.url === props.server.url)
- );
- const pipedreamRecord = createMemo(() =>
- pipedreamQuery.data?.find((connection) =>
- pipedreamSlugsMatch(connection.app_slug, props.server.app_slug)
- )
- );
- const authenticated = () =>
- pipedreamMcp()
- ? pipedreamRecord() !== undefined
- : (record()?.authenticated ?? false);
-
- const analytics = useAnalytics();
- let wasAuthenticated: boolean | undefined;
- createEffect(() => {
- if (
- pipedreamMcp()
- ? pipedreamQuery.isPlaceholderData
- : 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={
- pipedreamMcp()
- ? !pipedreamQuery.isPlaceholderData
- : !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={
- pipedreamMcp()
- ? pipedreamRecord() !== undefined
- : 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.tsx
deleted file mode 100644
index f7069bf264..0000000000
--- a/apps/web/src/features/setup/flow/EmailStep.tsx
+++ /dev/null
@@ -1,190 +0,0 @@
-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)
- );
- });
-
- // Connecting more than two accounts is a premium feature, and the plan
- // step hasn't happened yet — past two, stop offering connect slots.
- const connectSlots = createMemo(() => {
- const connected = links().length;
- if (connected >= 2) return [];
- return connected === 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.tsx
deleted file mode 100644
index 723c06186e..0000000000
--- a/apps/web/src/features/setup/flow/OnboardingFlow.tsx
+++ /dev/null
@@ -1,665 +0,0 @@
-import type { PaidPlanTier } from '@app/features/paywall/plans';
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { useFeatureFlag } from '@app/lib/analytics/posthog';
-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 { useGtmInviteOfferQuery } from '@queries/gtm-invite/links';
-import { useImportQuery } from '@queries/import';
-import { useMcpServersQuery } from '@queries/mcp-servers';
-import { useOnboardingQuery } from '@queries/onboarding';
-import { usePipedreamConnectionsQuery } from '@queries/pipedream-connectors';
-import type { GtmInviteOffer } from '@service-auth/generated/schemas/gtmInviteOffer';
-import { useNavigate } from '@solidjs/router';
-import { Button, cn } from '@ui';
-import { Stepper } from '@ui/components/Stepper';
-import {
- createEffect,
- createMemo,
- createSignal,
- For,
- Index,
- type JSX,
- Show,
- Suspense,
-} from 'solid-js';
-import { isMcpToolConnected } from '../core/connectedTools';
-import type { ModuleLogo, ModuleState } from '../Module';
-import { MODULE_LOGOS } from '../moduleLogos';
-import { BrandHandoff, type BrandHandoffSource } from './BrandHandoff';
-import { BuildingStep, type ConnectedTools } from './BuildingStep';
-import { ConnectorStep } from './ConnectorStep';
-import { createFlowFinish } from './createFlowFinish';
-import { EmailStep } from './EmailStep';
-import {
- ONBOARDING_CONNECTORS_FEATURE_FLAG,
- type OnboardingConnectorServerName,
- resolveOnboardingConnectorNames,
- resolveOnboardingStepIndex,
-} from './onboardingConnectorConfig';
-import { PlanStep } from './PlanStep';
-import { connectorLogo, StepModule } from './StepModule';
-import { SummaryStep } from './SummaryStep';
-import {
- canBypassOnboarding,
- 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.
- */
-
-/** The left-of-title hero module for a connection step (desktop only). Its
- * `linked` state is resolved from the flow's live queries by key: `email`
- * from the email links, `connector` from the named MCP server's auth. */
-type StepModuleDef =
- | { kind: 'email'; logo: ModuleLogo }
- | { kind: 'connector'; serverName: string; logo: ModuleLogo };
-
-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;
- /** Skip the Stepper's enter/exit fade+scale for this step. The building
- * step needs this: the brand-handoff overlay it mounts is measured
- * against its own logo's exact rect, and a fading exit would leave the
- * original visible (transitioning) at the same time as the overlay. */
- noTransition?: boolean;
- /** Hero module shown left of the title on connection steps. */
- module?: StepModuleDef;
- 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;
- /** Redirect to Stripe checkout without completing the flow. */
- startPremiumCheckout: (tier: PaidPlanTier) => void;
- /** Finish after checkout confirmed payment (or an existing license). */
- finishPremium: () => void;
- /** The free-month promotion an invite-link signup holds, once known. */
- inviteOffer: () => GtmInviteOffer | null;
-}
-
-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 tags as Macro tasks, ready to work on.',
- 'Macro AI can create, read, 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 pages as Macro docs.',
- 'Macro AI can search your pages and wikis.',
- ],
- gatherHint:
- "We're already looking through your Notion — you'll see what we found before you finish.",
- },
- Slack: {
- subtitle: 'Bring your conversations into your unified workspace.',
- features: [
- 'Macro creates channels based on your existing Slack channels, with the right participants.',
- '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: 'Bring your repos into your unified workspace.',
- features: [
- 'Pull requests show up in Macro.',
- 'Tasks get auto-updating branch names.',
- 'Macro AI can answer questions about your repos, pull requests, and issues.',
- ],
- },
-};
-
-function buildSteps(
- connectorNames: readonly OnboardingConnectorServerName[],
- connectedTools: () => ConnectedTools,
- onBuildingDone: (source: BrandHandoffSource | null) => void
-): StepDef[] {
- const connectorSteps: StepDef[] = connectorNames.flatMap((name) => {
- const server = FEATURED_MCP_SERVERS.find(
- (candidate) => candidate.server_name === name
- );
- const copy = CONNECTOR_COPY[name];
- if (!server || !copy) return [];
- const logo = connectorLogo(name);
- return [
- {
- key: `connect-${name.toLowerCase()}`,
- title: `Connect ${name}`,
- subtitle: copy.subtitle,
- ...(logo && {
- module: { kind: 'connector', serverName: name, logo },
- }),
- 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 multiple email accounts brings your email, docs, and calendar together, so nothing lives in a silo.',
- module: { kind: 'email', logo: MODULE_LOGOS.Google },
- render: (controls) => (
- <EmailStep onContinue={controls.next} onSkip={controls.skip} />
- ),
- },
- ...connectorSteps,
- {
- key: 'team',
- title: 'Macro is meant for teams',
- subtitle:
- 'Macro is built to be used with others. Invite your team to share docs, channels, and context from day one.',
- render: (controls) => (
- <TeamStep onContinue={controls.next} onSkip={controls.skip} />
- ),
- },
- {
- // Pure theater while gathers land; auto-advances into the summary via
- // the brand handoff (not a plain step advance).
- key: 'building',
- noDot: true,
- // Room for the isometric scene.
- wide: true,
- // See StepDef.noTransition.
- noTransition: true,
- render: () => (
- <BuildingStep connected={connectedTools()} onDone={onBuildingDone} />
- ),
- },
- {
- 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 pick a paid plan. You can change this anytime.',
- wide: true,
- render: (controls) => (
- <PlanStep
- finishing={controls.finishing()}
- inviteOffer={controls.inviteOffer()}
- onFree={controls.finishFree}
- onStartCheckout={controls.startPremiumCheckout}
- onPremiumPaid={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();
- // An account that signed up through a GTM invite link holds a free-month
- // promotion; the plan step shows it in place of the picker. Guarded read so
- // a pending fetch never suspends the flow.
- const inviteOfferQuery = useGtmInviteOfferQuery({ enabled: needsOnboarding });
- const inviteOffer = () =>
- inviteOfferQuery.isSuccess ? inviteOfferQuery.data : null;
- const serversQuery = useMcpServersQuery({ neverSuspend: true });
- const pipedreamQuery = usePipedreamConnectionsQuery({ neverSuspend: true });
- const analytics = useAnalytics();
-
- // Live connection state, derived from the flow's queries (no standing
- // bookkeeping): whether an MCP server authenticated, and which tools the
- // user connected. Drives the hero-module states and the build phrases.
- const serverAuthed = (name: string) =>
- isMcpToolConnected(name, {
- pipedream: pipedreamQuery.data ?? [],
- native: serversQuery.data ?? [],
- });
- const connectedTools = (): ConnectedTools => ({
- google: (linksQuery.data?.links.length ?? 0) > 0,
- linear: serverAuthed('Linear'),
- notion: serverAuthed('Notion'),
- slack: serverAuthed('Slack'),
- github: serverAuthed('GitHub'),
- });
-
- // The building → summary brand handoff. BuildingStep provides the exact
- // powered SVG plus its logo geometry; the overlay carries that scene into
- // the summary header while dissolving it into the flat Macro logo.
- const [handoff, setHandoff] = createSignal<BrandHandoffSource | null>(null);
- // Summary reveal gates: the logo slot + rest of the content appear once the
- // handoff lands. Default shown, for a summary reached without a handoff
- // (e.g. a restored step).
- const [logoShown, setLogoShown] = createSignal(true);
- const [contentShown, setContentShown] = createSignal(true);
- const summaryContentHidden = () =>
- currentStep().key === 'summary' && !contentShown();
- // Hiding must be instant, revealing eased. The header/body wrappers are
- // shared across steps, so a symmetric transition would animate 1 → 0 as we
- // enter the summary — the content visibly flashing in and fading out behind
- // the travelling logo.
- const contentFadeMs = () => (summaryContentHidden() ? 0 : 300);
- const startBrandHandoff = (source: BrandHandoffSource | null) => {
- if (!source) {
- advance('completed');
- return;
- }
- setHandoff(source);
- // Hide the summary's own content so only the settling logo shows.
- setLogoShown(false);
- setContentShown(false);
- advance('completed');
- };
-
- const connectorConfig = useFeatureFlag(ONBOARDING_CONNECTORS_FEATURE_FLAG);
- const steps = createMemo(() => {
- const config = connectorConfig();
- return buildSteps(
- resolveOnboardingConnectorNames(config.enabled, config.payload),
- connectedTools,
- startBrandHandoff
- );
- });
-
- const [activeStepKey, setActiveStepKey] = createSignal('email');
- const stepIndex = createMemo(() =>
- resolveOnboardingStepIndex(
- steps().map((step) => step.key),
- activeStepKey()
- )
- );
- const currentStep = createMemo(() => steps()[stepIndex()]);
- const currentStepKey = createMemo(() => currentStep().key);
- // The plan step's header follows the offer without rebuilding the steps
- // (which would remount the step mid-flow).
- const stepTitle = () =>
- currentStep().key === 'plan' && inviteOffer()
- ? 'Your first month is on us'
- : currentStep().title;
- const stepSubtitle = () =>
- currentStep().key === 'plan' && inviteOffer()
- ? 'Your invite comes with Macro Premium free for the first month. You can change plans anytime.'
- : currentStep().subtitle;
- const userId = () => userInfoQuery.data?.userId;
-
- // The current step's hero-module state: the email module lights once any
- // inbox is linked, a connector's once its server authenticates.
- const heroState = (): ModuleState => {
- const mod = currentStep().module;
- if (!mod) return 'idle';
- if (mod.kind === 'email') {
- return (linksQuery.data?.links.length ?? 0) > 0 ? 'linked' : 'idle';
- }
- return serverAuthed(mod.serverName) ? 'linked' : 'idle';
- };
-
- // 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;
- }
- setActiveStepKey(saved.step ?? 'email');
- } 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: currentStepKey(),
- });
- });
-
- createEffect(() => {
- if (!needsOnboarding()) return;
- analytics.track('onboarding_v4_step', {
- step: currentStepKey(),
- index: stepIndex(),
- state: 'viewed',
- });
- });
-
- // Forward-only: there is no back.
- const advance = (state: 'completed' | 'skipped') => {
- analytics.track('onboarding_v4_step', {
- step: currentStepKey(),
- index: stepIndex(),
- state,
- });
- const index = Math.min(stepIndex() + 1, steps().length - 1);
- const nextStep = steps()[index];
- setActiveStepKey(nextStep.key);
- sessionStorage.setItem(
- FLOW_STEP_STORAGE_KEY,
- JSON.stringify({ user: userId(), step: nextStep.key })
- );
- };
-
- const finish = createFlowFinish({
- completionRollup: () => ({
- emails_connected: linksQuery.data?.links.length ?? 0,
- connectors_connected: (pipedreamQuery.data ?? []).length
- ? (pipedreamQuery.data ?? []).map((connection) =>
- connection.server_name.toLowerCase()
- )
- : (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),
- startPremiumCheckout: (tier) => void finish.startPremiumCheckout(tier),
- finishPremium: () => void finish.finishPremium(),
- inviteOffer,
- };
-
- // Gated read: `data` suspends while the user-info query is pending.
- const staffEmail = () => {
- if (!userInfoQuery.isSuccess) return undefined;
- const info = userInfoQuery.data;
- if (info?.authenticated !== true) return undefined;
- return info.email;
- };
-
- // 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-hidden 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 />
-
- <Show when={canBypassOnboarding(staffEmail())}>
- <div class="absolute top-4 right-4 z-30">
- <Button
- variant="ghost"
- size="sm"
- class="text-ink-muted"
- disabled={finish.finishing()}
- onClick={() => void finish.bypass(currentStepKey())}
- >
- Bypass
- </Button>
- </div>
- </Show>
-
- {/* The backdrop layers are viewport-sized absolutes, so scrolling has
- to happen inside them — a tall step (the summary's pill cloud)
- would otherwise scroll the wash and grain away with the content,
- and the grain's 100vw width would add a horizontal scrollbar. */}
- <div class="relative z-10 size-full overflow-y-auto overscroll-contain">
- <div class="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">
- {/* Hero module above the title — desktop only. Nudged left by
- the module's built-in viewBox padding (reserved for the
- click-burst trail) so its at-rest artwork left-aligns with
- the title text. */}
- <Show when={currentStep().module}>
- {(mod) => (
- <StepModule
- logo={mod().logo}
- state={heroState()}
- class="mb-1 hidden size-32 -ml-8 sm:block"
- />
- )}
- </Show>
- {/* Landing slot for the loading-graphic → logo handoff. Kept
- hidden while the overlay is mid-flight; the overlay lands
- exactly here, then this static logo takes over. */}
- <Show when={currentStep().key === 'summary'}>
- <LogoIcon
- id="summary-brand-logo"
- class="mb-1 size-16 text-accent"
- style={{ opacity: logoShown() ? 1 : 0 }}
- />
- </Show>
- <div
- class="flex flex-col gap-1.5 transition-opacity"
- style={{
- opacity: summaryContentHidden() ? 0 : 1,
- 'transition-duration': `${contentFadeMs()}ms`,
- }}
- >
- <h1 class="text-2xl font-semibold tracking-tight text-ink">
- {stepTitle()}
- </h1>
- <Show when={stepSubtitle()}>
- <p class="max-w-md text-sm leading-relaxed text-ink-muted">
- {stepSubtitle()}
- </p>
- </Show>
- </div>
- </div>
- </Show>
-
- <div
- class="flex flex-col gap-8 transition-opacity"
- style={{
- opacity: summaryContentHidden() ? 0 : 1,
- 'transition-duration': `${contentFadeMs()}ms`,
- }}
- >
- <Stepper
- step={stepIndex()}
- transition={Stepper.transitions.scale}
- >
- <For each={steps()}>
- {(step) => (
- <Stepper.Step noTransition={step.noTransition}>
- <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>
- </div>
-
- {/* Brand handoff overlay — rendered outside the animated card (a
- transformed ancestor would break its fixed positioning). */}
- <Show when={handoff()}>
- {(active) => (
- <BrandHandoff
- scene={active().scene}
- logo={active().logo}
- snapshot={active().snapshot}
- targetSelector="#summary-brand-logo"
- onDone={() => {
- setLogoShown(true);
- setContentShown(true);
- setHandoff(null);
- }}
- />
- )}
- </Show>
- </div>
- );
-}
diff --git a/apps/web/src/features/setup/flow/PlanStep.tsx b/apps/web/src/features/setup/flow/PlanStep.tsx
deleted file mode 100644
index f9a8e0bc47..0000000000
--- a/apps/web/src/features/setup/flow/PlanStep.tsx
+++ /dev/null
@@ -1,235 +0,0 @@
-import { InviteOfferPanel } from '@app/features/gtm-invite/InviteOfferPanel';
-import {
- type PaidPlanTier,
- PLAN_BY_TIER,
- PLANS,
- type PlanTier,
- planFeatures,
-} from '@app/features/paywall/plans';
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { enableAiUsageBilling } from '@core/constant/featureFlags';
-import ArrowRight from '@phosphor/arrow-right.svg';
-import Check from '@phosphor/check.svg';
-import { useIncludedAiCentsByTier } from '@queries/auth';
-import { useUserInfoQuery } from '@queries/auth/user-info';
-import type { GtmInviteOffer } from '@service-auth/generated/schemas/gtmInviteOffer';
-import { useSearchParams } from '@solidjs/router';
-import { Button, cn } from '@ui';
-import { createSignal, Index, onCleanup, onMount, Show } from 'solid-js';
-import { SkipButton } from './shared';
-
-// The license flips via Stripe webhook after checkout; poll briefly so the
-// app already reflects Premium when the user continues in.
-const LICENSE_POLL_ATTEMPTS = 10;
-const LICENSE_POLL_INTERVAL_MS = 1_000;
-
-/** Free vs paid. The last step: free/skip finishes immediately; premium
- * round-trips through Stripe checkout (the flow stays incomplete, so both
- * checkout legs land back here) and finishes once payment is confirmed.
- * An account that signed up through a GTM invite link sees its free-month
- * offer in place of the picker; checkout applies the promotion server-side. */
-export function PlanStep(props: {
- finishing: boolean;
- /** The promotion an invite-link signup holds, once known. */
- inviteOffer?: GtmInviteOffer | null;
- onFree: (planSkipped: boolean) => void;
- onStartCheckout: (tier: PaidPlanTier) => void;
- /** Payment confirmed (or a license already active) for `tier`. */
- onPremiumPaid: (tier: PaidPlanTier) => void;
-}) {
- const [searchParams] = useSearchParams();
- const userInfoQuery = useUserInfoQuery();
- const analytics = useAnalytics();
- const [selected, setSelected] = createSignal<PlanTier>('free');
-
- const returnedFromCheckout = searchParams.subscriptionSuccess === 'true';
- // The success leg carries `type=<tier>` so the confirmation names the plan
- // that was actually bought; anything else reads as Premium.
- const paidTier = (): PaidPlanTier =>
- searchParams.type === 'max' ? 'max' : 'premium';
- const paidPlanName = () => PLAN_BY_TIER[paidTier()].name;
- const hasPaidAccess = () =>
- userInfoQuery.data?.licenseStatus === 'active' ||
- userInfoQuery.data?.licenseStatus === 'trialing';
- // Back from a successful checkout, or the license is already active (an
- // abandoned checkout return, or a team/enterprise license) — creating
- // another checkout session for these users would just be rejected.
- const premiumActive = () => returnedFromCheckout || hasPaidAccess();
-
- onMount(() => {
- if (!returnedFromCheckout) return;
- analytics.track('subscription_success', { type: paidTier() });
- let cancelled = false;
- onCleanup(() => {
- cancelled = true;
- });
- void (async () => {
- for (let attempt = 0; attempt < LICENSE_POLL_ATTEMPTS; attempt++) {
- if (cancelled || hasPaidAccess()) return;
- await new Promise((resolve) =>
- setTimeout(resolve, LICENSE_POLL_INTERVAL_MS)
- );
- if (cancelled) return;
- await userInfoQuery.refetch().catch(() => {});
- }
- })();
- });
-
- const finish = () => {
- const tier = selected();
- if (tier === 'free') props.onFree(false);
- else props.onStartCheckout(tier);
- };
-
- return (
- <Show
- when={!premiumActive()}
- fallback={
- <div class="flex flex-col gap-6">
- <div class="flex flex-col items-start gap-3 rounded-xl border border-edge p-5">
- <span class="flex size-8 items-center justify-center rounded-full bg-accent/15 text-accent">
- <Check class="size-4" />
- </span>
- <div class="flex flex-col gap-1">
- <span class="text-sm font-semibold text-ink">
- {returnedFromCheckout
- ? 'Payment successful'
- : `${paidPlanName()} is already active`}
- </span>
- <p class="text-sm leading-relaxed text-ink-muted">
- {returnedFromCheckout
- ? `${paidPlanName()} is now active on your account.`
- : `Your account already has ${paidPlanName()} access — no payment needed.`}
- </p>
- </div>
- </div>
- <Button
- variant="cta"
- size="xl"
- disabled={props.finishing}
- onClick={() => props.onPremiumPaid(paidTier())}
- >
- {props.finishing ? 'Setting up your workspace…' : 'Continue'}
- <ArrowRight class="size-5" />
- </Button>
- </div>
- }
- >
- <Show
- when={props.inviteOffer}
- fallback={
- <PlanPicker
- finishing={props.finishing}
- selected={selected()}
- onSelect={setSelected}
- onFinish={finish}
- onDecideLater={() => props.onFree(true)}
- />
- }
- >
- {(offer) => (
- <InviteOfferPanel
- offer={offer()}
- finishing={props.finishing}
- onStartCheckout={() => props.onStartCheckout('premium')}
- onContinueFree={() => props.onFree(false)}
- />
- )}
- </Show>
- </Show>
- );
-}
-
-function PlanPicker(props: {
- finishing: boolean;
- selected: PlanTier;
- onSelect: (tier: PlanTier) => void;
- onFinish: () => void;
- onDecideLater: () => void;
-}) {
- const selected = () => props.selected;
- const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);
- const includedAi = useIncludedAiCentsByTier();
- 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={() => props.onSelect(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={planFeatures(aiUsageBilling().enabled, includedAi())}
- >
- {(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"
- size="xl"
- disabled={props.finishing}
- onClick={() => props.onFinish()}
- >
- {props.finishing
- ? selected() === 'free'
- ? 'Setting up your workspace…'
- : 'Heading to checkout…'
- : `Continue with ${PLAN_BY_TIER[selected()].name}`}
- <ArrowRight class="size-5" />
- </Button>
- <SkipButton
- label="Decide later"
- disabled={props.finishing}
- onClick={() => props.onDecideLater()}
- />
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/features/setup/flow/StepModule.tsx b/apps/web/src/features/setup/flow/StepModule.tsx
deleted file mode 100644
index 31b4905024..0000000000
--- a/apps/web/src/features/setup/flow/StepModule.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { Module, type ModuleLogo, type ModuleState } from '../Module';
-import { MODULE_LOGOS } from '../moduleLogos';
-import '../SetupGraphic.css';
-
-/**
- * Frames a single {@link Module} with room for its click-burst (the body
- * thrust down-right and the jet trail streaking up-left).
- */
-const MODULE_VIEWBOX = '210 -40 310 310';
-
-/**
- * A single hovering module as a connection step's hero: the isometric tile
- * carrying a brand logo, dropped into a bare SVG host (the root just needs the
- * `setup-graphic` class for styling and `currentColor` for the ink linework).
- *
- * `state` reflects the connection: `idle` before, `linked` (logo held accent)
- * once connected. Clicking the module plays its acceleration burst.
- */
-export function StepModule(props: {
- logo: ModuleLogo;
- state?: ModuleState;
- class?: string;
-}) {
- return (
- <svg
- viewBox={MODULE_VIEWBOX}
- fill="currentColor"
- class={`setup-graphic text-ink ${props.class ?? ''}`}
- aria-hidden="true"
- >
- <Module logo={props.logo} state={props.state} />
- </svg>
- );
-}
-
-/**
- * The module logo for a featured connector, keyed by its `server_name`
- * (`Linear` / `Notion` / `Slack` / `GitHub`). Returns undefined for a name
- * without a brand mark.
- */
-export function connectorLogo(serverName: string): ModuleLogo | undefined {
- return (MODULE_LOGOS as Record<string, ModuleLogo>)[serverName];
-}
diff --git a/apps/web/src/features/setup/flow/SummaryStep.tsx b/apps/web/src/features/setup/flow/SummaryStep.tsx
deleted file mode 100644
index 93747bcbe7..0000000000
--- a/apps/web/src/features/setup/flow/SummaryStep.tsx
+++ /dev/null
@@ -1,217 +0,0 @@
-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()} threads
- </>
- )}
- </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-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.tsx
deleted file mode 100644
index ed85adc407..0000000000
--- a/apps/web/src/features/setup/flow/TeamStep.tsx
+++ /dev/null
@@ -1,327 +0,0 @@
-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 XIcon from '@phosphor/x.svg';
-import { useContacts, useContactsQuery } 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,
- FormInput,
- SkipButton,
-} from './shared';
-import {
- prefillableTeammates,
- removeInviteSlot,
- validInviteEmails,
-} from './teamInvites';
-
-/** Set up your team: already a member → confirmation, pending invites →
- * join, otherwise create (with a domain-derived name and same-domain
- * teammates pre-added to the invite list). */
-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-bg 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>
- );
-}
-
-/** Create a team: same-domain teammates arrive pre-added to the invite list
- * (remove to opt them out) when the user has a custom domain; the plain form
- * otherwise. Waits for contacts and the domain suggestion so the form mounts
- * once, fully formed — nothing rewrites the user's rows afterwards. */
-function CreateTeamForm(props: { onContinue: () => void; onSkip: () => void }) {
- const email = useEmail();
- const contacts = useContacts();
- const contactsQuery = useContactsQuery();
- 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;
-
- // Settled, not succeeded: an errored query opens the plain form.
- const ready = () =>
- !contactsQuery.isPending && !onboardingQuery.isPlaceholderData;
-
- return (
- <Show when={ready()}>
- <TeamForm
- domain={customDomain()}
- prefilledTeammates={prefillableTeammates({
- contacts: contacts(),
- domain: customDomain(),
- ownEmail: email(),
- })}
- onContinue={props.onContinue}
- onSkip={props.onSkip}
- />
- </Show>
- );
-}
-
-/** The create-team form proper — mounted with its prefill inputs resolved,
- * so the name and invite slots initialize once and stay user-owned. */
-function TeamForm(props: {
- domain: string | undefined;
- prefilledTeammates: string[];
- onContinue: () => void;
- onSkip: () => void;
-}) {
- const analytics = useAnalytics();
- const email = useEmail();
- const createTeam = useCreateTeamWithInvitesMutation();
-
- const [name, setName] = createSignal(
- props.domain ? deriveTeamName(props.domain) : ''
- );
- // Same-domain teammates are pre-added rather than offered: the default is
- // "invite them", and removing a row is how you opt one out.
- const prefilled = props.prefilledTeammates;
- const [inviteSlots, setInviteSlots] = createSignal<string[]>(
- prefilled.length > 0 ? [...prefilled, ''] : ['', '']
- );
- let inviteListEl: HTMLDivElement | undefined;
-
- const validInvites = () => validInviteEmails(inviteSlots(), email());
-
- // The X means "don't invite this person", so it belongs on rows that name
- // one. Blank rows need no removing — they're dropped on submit anyway.
- const canRemoveSlot = (value: string) => value.trim() !== '';
-
- const addEmptyInvite = () => {
- setInviteSlots((slots) => [...slots, '']);
- requestAnimationFrame(() => {
- inviteListEl?.lastElementChild?.scrollIntoView({
- behavior: 'smooth',
- block: 'nearest',
- });
- });
- };
-
- const create = async () => {
- if (createTeam.isPending || name().trim().length === 0) return;
- // The mutation owns its toasts; stay put (form intact) on failure.
- const invites = validInvites();
- try {
- await createTeam.mutateAsync({
- name: name().trim(),
- invites: invites.map((address) => ({ email: address })),
- });
- } catch {
- return;
- }
- const kept = new Set(invites);
- analytics.track('onboarding_v4_team', {
- action: 'created',
- invites_sent: invites.length,
- invites_prefilled: prefilled.length,
- invites_removed: prefilled.filter((address) => !kept.has(address)).length,
- used_domain_suggestion: props.domain !== undefined,
- });
- props.onContinue();
- };
-
- return (
- <div class="flex flex-col gap-3">
- {/* Same row shape as an invite, with the remove gutter left empty, so
- every input in the form shares one width. Labelled, because the
- name arrives pre-filled — a placeholder alone would be invisible
- exactly when the field needs explaining. */}
- <div class="flex items-center gap-1.5">
- <div class="flex min-w-0 flex-1 flex-col gap-1.5">
- <label for="team-name" class="text-xs text-ink-muted">
- Team name
- </label>
- <FormInput
- id="team-name"
- // An example, not "Team name" again — the label says that.
- placeholder="Acme Inc."
- value={name()}
- autoFocus={!props.domain}
- onInput={setName}
- />
- </div>
- <div class="size-7 shrink-0" />
- </div>
-
- {/* Index, not For: slots are edited strings, and For keys by value —
- each keystroke would recreate the input node and drop focus.
- No inner scroller: the list opens pre-filled now, and a capped box
- left a row sliced in half above the buttons — the flow's own
- scroll container takes the height instead. */}
- <div ref={(el) => (inviteListEl = el)} class="flex flex-col gap-3">
- <Index each={inviteSlots()}>
- {(slot, i) => (
- <div class="flex items-center gap-1.5">
- <div class="min-w-0 flex-1">
- <FormInput
- id={`invite-${i}`}
- type="email"
- placeholder="[email protected]"
- value={slot()}
- onInput={(value) =>
- setInviteSlots((slots) =>
- slots.map((v, j) => (j === i ? value : v))
- )
- }
- />
- </div>
- {/* Gutter is always reserved, so a blank row's input still lines
- up with the ones carrying a remove button. */}
- <div class="flex size-7 shrink-0 items-center justify-center">
- <Show when={canRemoveSlot(slot())}>
- <button
- type="button"
- aria-label={`Don't invite ${slot().trim()}`}
- title={`Don't invite ${slot().trim()}`}
- onClick={() =>
- setInviteSlots((slots) => removeInviteSlot(slots, i))
- }
- class="rounded-md p-1.5 text-ink-extra-muted transition-colors hover:bg-ink/5 hover:text-ink"
- >
- <XIcon class="size-4" />
- </button>
- </Show>
- </div>
- </div>
- )}
- </Index>
- </div>
-
- <Button
- variant="ghost"
- size="sm"
- class="self-center text-ink-muted"
- onClick={addEmptyInvite}
- >
- <Plus class="size-4" />
- Add another teammate
- </Button>
-
- <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.ts
deleted file mode 100644
index d08875dfdb..0000000000
--- a/apps/web/src/features/setup/flow/createFlowFinish.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-import { AFTER_SETUP_ROUTE, DEFAULT_ROUTE } from '@app/constants/defaultRoute';
-import { onboardingCheckoutArgs } from '@app/features/onboarding/use-onboarding-checkout';
-import type { PaidPlanTier, PlanTier } from '@app/features/paywall/plans';
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { toast } from '@core/component/Toast/Toast';
-import { useCreateCheckoutSessionMutation } from '@queries/auth';
-import { authKeys } from '@queries/auth/keys';
-import { useCompleteTutorialMutation } from '@queries/auth/tutorial';
-import type { UserInfoData } from '@queries/auth/user-info';
-import { queryClient } from '@queries/client';
-import { useCompleteOnboardingMutation } from '@queries/onboarding';
-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
- * the Getting Started checklist). 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 completeOnboarding = useCompleteOnboardingMutation();
- const completeTutorial = useCompleteTutorialMutation();
- const checkout = useCreateCheckoutSessionMutation();
- const analytics = useAnalytics();
- const [finishing, setFinishing] = createSignal(false);
-
- const trackCompleted = (plan: PlanTier, planSkipped: boolean) => {
- analytics.track('onboarding_v4_completed', {
- plan,
- plan_skipped: planSkipped,
- emails_connected: 0,
- connectors_connected: [],
- ...options?.completionRollup?.(),
- });
- };
-
- // Same-app relative paths only. A `next` at the default route is not a
- // real deep link — fall through to the Getting Started checklist.
- const sanitizeNext = (value: unknown): string | undefined =>
- typeof value === 'string' &&
- value.startsWith('/') &&
- !value.startsWith('//') &&
- !value.includes('\\') &&
- !value.startsWith(DEFAULT_ROUTE)
- ? 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)) ??
- AFTER_SETUP_ROUTE;
-
- /**
- * 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 (skipped = false): Promise<boolean> => {
- const [onboardingResult] = await Promise.allSettled([
- completeOnboarding.mutateAsync({ skipped }),
- 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(() => {});
- // Read the cache, not the query observer: observer stores flush on a
- // scheduled task, so right after the await they still hold the
- // pre-PATCH value and the guard would fail on a fresh success.
- const userInfo = queryClient.getQueryData<UserInfoData>(
- authKeys.userInfo.queryKey
- );
- if (userInfo?.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);
- }
- };
-
- /**
- * Hand the page to Stripe WITHOUT completing the flow: the onboarding
- * redirect plus the persisted step bring both checkout legs (success and
- * cancel) back to the plan step, which finishes only once payment is
- * confirmed. On failure the user stays on the plan step and can retry or
- * pick free.
- */
- const startPremiumCheckout = async (tier: PaidPlanTier) => {
- if (finishing()) return;
- setFinishing(true);
- try {
- const checkoutUrl = await checkout.mutateAsync(
- onboardingCheckoutArgs(tier)
- );
- // Deliberately leave `finishing` set: the page is navigating away,
- // and re-enabling the buttons mid-unload invites a double checkout.
- window.location.href = checkoutUrl;
- } catch {
- toast.failure("Couldn't start checkout — please try again");
- setFinishing(false);
- }
- };
-
- /** Finish after checkout confirmed payment (or an existing license),
- * recording the tier Stripe returned with rather than assuming Premium. */
- const finishPremium = async (tier: PaidPlanTier = 'premium') => {
- if (finishing()) return;
- setFinishing(true);
- try {
- if (await completeFlow()) {
- trackCompleted(tier, false);
- navigate(afterTarget(), { replace: true });
- }
- } finally {
- setFinishing(false);
- }
- };
-
- /**
- * Staff escape hatch: close the flow without touching any step, recorded
- * server-side as skipped. Lands on the preserved deep link or straight in
- * the app — the Getting Started checklist is onboarding too.
- */
- const bypass = async (stepKey: string) => {
- if (finishing()) return;
- setFinishing(true);
- // Resolved up front: completing the flow clears the persisted deep link.
- const target =
- sanitizeNext(searchParams.next) ??
- sanitizeNext(sessionStorage.getItem(FLOW_NEXT_STORAGE_KEY)) ??
- DEFAULT_ROUTE;
- try {
- if (await completeFlow(true)) {
- analytics.track('onboarding_v4_bypassed', { step: stepKey });
- navigate(target, { replace: true });
- }
- } finally {
- setFinishing(false);
- }
- };
-
- return {
- finishing,
- finishFree,
- startPremiumCheckout,
- finishPremium,
- bypass,
- afterTarget,
- };
-}
diff --git a/apps/web/src/features/setup/flow/onboardingConnectorConfig.test.ts b/apps/web/src/features/setup/flow/onboardingConnectorConfig.test.ts
deleted file mode 100644
index 1f5f6d63ec..0000000000
--- a/apps/web/src/features/setup/flow/onboardingConnectorConfig.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- ONBOARDING_CONNECTORS,
- resolveOnboardingConnectorNames,
- resolveOnboardingStepIndex,
-} from './onboardingConnectorConfig';
-
-const allConnectors = ONBOARDING_CONNECTORS.map(({ serverName }) => serverName);
-
-describe('resolveOnboardingConnectorNames', () => {
- it('shows every connector when the feature flag is disabled', () => {
- expect(
- resolveOnboardingConnectorNames(false, {
- linear: false,
- notion: false,
- slack: false,
- github: false,
- })
- ).toEqual(allConnectors);
- });
-
- it('hides connectors explicitly disabled in the payload', () => {
- expect(
- resolveOnboardingConnectorNames(true, {
- linear: false,
- slack: false,
- })
- ).toEqual(['Notion', 'GitHub']);
- });
-
- it('can hide every connector', () => {
- expect(
- resolveOnboardingConnectorNames(true, {
- linear: false,
- notion: false,
- slack: false,
- github: false,
- })
- ).toEqual([]);
- });
-
- it('keeps connectors visible for missing or invalid values', () => {
- expect(
- resolveOnboardingConnectorNames(true, {
- linear: 'false',
- notion: null,
- slack: 0,
- })
- ).toEqual(allConnectors);
- });
-
- it('shows every connector for malformed payloads', () => {
- for (const payload of [undefined, null, [], 'invalid']) {
- expect(resolveOnboardingConnectorNames(true, payload)).toEqual(
- allConnectors
- );
- }
- });
-});
-
-describe('resolveOnboardingStepIndex', () => {
- const fullStepList = [
- 'email',
- 'connect-linear',
- 'connect-notion',
- 'connect-slack',
- 'connect-github',
- 'team',
- 'building',
- 'summary',
- 'plan',
- ];
-
- it('preserves the active step when an earlier connector is hidden', () => {
- const reducedStepList = fullStepList.filter(
- (key) => key !== 'connect-notion'
- );
-
- expect(resolveOnboardingStepIndex(fullStepList, 'connect-slack')).toBe(3);
- expect(resolveOnboardingStepIndex(reducedStepList, 'connect-slack')).toBe(
- 2
- );
- });
-
- it('falls forward when the active connector is hidden', () => {
- const reducedStepList = fullStepList.filter(
- (key) => key !== 'connect-notion'
- );
-
- expect(resolveOnboardingStepIndex(reducedStepList, 'connect-notion')).toBe(
- 2
- );
- expect(reducedStepList[2]).toBe('connect-slack');
- });
-
- it('stays in bounds when several connectors disappear', () => {
- const reducedStepList = ['email', 'team', 'building', 'summary', 'plan'];
- const index = resolveOnboardingStepIndex(reducedStepList, 'connect-github');
-
- expect(index).toBe(1);
- expect(reducedStepList[index]).toBe('team');
- });
-
- it('falls back safely for an unknown saved step', () => {
- expect(resolveOnboardingStepIndex(fullStepList, 'unknown')).toBe(0);
- });
-});
diff --git a/apps/web/src/features/setup/flow/onboardingConnectorConfig.ts b/apps/web/src/features/setup/flow/onboardingConnectorConfig.ts
deleted file mode 100644
index c0c1187294..0000000000
--- a/apps/web/src/features/setup/flow/onboardingConnectorConfig.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/** PostHog feature flag used to configure the connector steps in onboarding. */
-export const ONBOARDING_CONNECTORS_FEATURE_FLAG = 'onboarding-v4-connectors';
-
-export const ONBOARDING_CONNECTORS = [
- { key: 'linear', serverName: 'Linear' },
- { key: 'notion', serverName: 'Notion' },
- { key: 'slack', serverName: 'Slack' },
- { key: 'github', serverName: 'GitHub' },
-] as const;
-
-const ONBOARDING_STEP_ORDER = [
- 'email',
- ...ONBOARDING_CONNECTORS.map(({ key }) => `connect-${key}`),
- 'team',
- 'building',
- 'summary',
- 'plan',
-];
-
-export type OnboardingConnectorServerName =
- (typeof ONBOARDING_CONNECTORS)[number]['serverName'];
-
-/**
- * Resolves the connector steps from the PostHog flag payload.
- *
- * The supported payload is a JSON object with connector keys and boolean
- * values, for example:
- *
- * `{ "linear": true, "notion": true, "slack": false, "github": true }`
- *
- * Existing behavior is fail-open: the flag must be enabled and a connector
- * must be explicitly set to `false` to hide it.
- */
-export function resolveOnboardingConnectorNames(
- flagEnabled: boolean,
- payload: unknown
-): OnboardingConnectorServerName[] {
- if (!flagEnabled || !isObject(payload)) {
- return ONBOARDING_CONNECTORS.map(({ serverName }) => serverName);
- }
-
- return ONBOARDING_CONNECTORS.filter(({ key }) => payload[key] !== false).map(
- ({ serverName }) => serverName
- );
-}
-
-/**
- * Finds the active step in a feature-flag-filtered step list. If the active
- * step was hidden, onboarding falls forward to the next visible step.
- */
-export function resolveOnboardingStepIndex(
- visibleStepKeys: readonly string[],
- activeStepKey: string
-): number {
- const activeOrder = Math.max(ONBOARDING_STEP_ORDER.indexOf(activeStepKey), 0);
- const nextVisibleIndex = visibleStepKeys.findIndex(
- (key) => ONBOARDING_STEP_ORDER.indexOf(key) >= activeOrder
- );
-
- return nextVisibleIndex === -1
- ? Math.max(visibleStepKeys.length - 1, 0)
- : nextVisibleIndex;
-}
-
-function isObject(value: unknown): value is Record<string, unknown> {
- return typeof value === 'object' && value !== null && !Array.isArray(value);
-}
diff --git a/apps/web/src/features/setup/flow/shared.tsx b/apps/web/src/features/setup/flow/shared.tsx
deleted file mode 100644
index 2cf41a886c..0000000000
--- a/apps/web/src/features/setup/flow/shared.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-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();
-}
-
-const MACRO_STAFF_DOMAIN = 'macro.com';
-
-/** Whether the address belongs to a Macro staff account (`@macro.com`). */
-export function isMacroStaffEmail(address: string | undefined): boolean {
- return emailDomain(address) === MACRO_STAFF_DOMAIN;
-}
-
-/** Whether this account gets the staff Bypass button on the onboarding flow. */
-export function canBypassOnboarding(address: string | undefined): boolean {
- return isMacroStaffEmail(address?.trim());
-}
-
-/** "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"
- size="xl"
- disabled={props.disabled}
- onClick={props.onClick}
- >
- {props.label ?? 'Continue'}
- <ArrowRight class="size-5" />
- </Button>
- );
-}
diff --git a/apps/web/src/features/setup/flow/useOnboardingV4Flag.ts b/apps/web/src/features/setup/flow/useOnboardingV4Flag.ts
deleted file mode 100644
index 40db7b8f5f..0000000000
--- a/apps/web/src/features/setup/flow/useOnboardingV4Flag.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useFeatureFlag, usePosthog } from '@app/lib/analytics/posthog';
-import { enableOnboardingV4 } from '@core/constant/featureFlags';
-import { type Accessor, createSignal, onCleanup } from 'solid-js';
-
-/**
- * How long to treat "PostHog hasn't answered yet" as loading before falling
- * back to the flag's default (off). Without this a blocked or failing PostHog
- * would leave onboarding gates spinning forever.
- */
-const FLAG_WAIT_MS = 3_000;
-
-/** Reactive result of the onboarding-v4 gate. */
-export type OnboardingV4Flag = {
- /** Whether onboarding v4 is on for this user. */
- enabled: boolean;
- /**
- * PostHog hasn't reported flags yet. Call sites that would navigate away
- * should wait on this rather than reading `enabled: false` as "off".
- */
- loading: boolean;
-};
-
-/**
- * Gate for onboarding v4, controlled by the `enable-onboarding-v4` PostHog
- * flag and overridable locally with `VITE_ENABLE_ONBOARDING_V4`.
- * `just run_local` sets that env to false unless `--enable-onboarding`.
- */
-export function useOnboardingV4Flag(): Accessor<OnboardingV4Flag> {
- const posthog = usePosthog();
- const flag = useFeatureFlag(enableOnboardingV4);
-
- const [waited, setWaited] = createSignal(false);
- const timer = setTimeout(() => setWaited(true), FLAG_WAIT_MS);
- onCleanup(() => clearTimeout(timer));
-
- return () => ({
- enabled: flag().enabled,
- loading:
- enableOnboardingV4.override === undefined &&
- !posthog.featureFlags().length &&
- !waited(),
- });
-}
diff --git a/apps/web/src/features/setup/moduleLogos.ts b/apps/web/src/features/setup/moduleLogos.ts
deleted file mode 100644
index 6a6a22002d..0000000000
--- a/apps/web/src/features/setup/moduleLogos.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { ModuleLogo } from './Module';
-
-/**
- * Brand marks for the connectable tools, ready to drop onto a module face via
- * {@link Module}. Each is one or more path `d` strings filled with
- * `currentColor` and placed with the flat-logo face transform.
- *
- * Shared by the setup scene and the connection-step modules so the paths live
- * in one place.
- */
-export const MODULE_LOGOS = {
- Linear: {
- paths: [
- 'M2.886 4.18A11.982 11.982 0 0 1 11.99 0C18.624 0 24 5.376 24 12.009c0 3.64-1.62 6.903-4.18 9.105L2.887 4.18ZM1.817 5.626l16.556 16.556c-.524.33-1.075.62-1.65.866L.951 7.277c.247-.575.537-1.126.866-1.65ZM.322 9.163l14.515 14.515c-.71.172-1.443.282-2.195.322L0 11.358a12 12 0 0 1 .322-2.195Zm-.17 4.862 9.823 9.824a12.02 12.02 0 0 1-9.824-9.824Z',
- ],
- },
- // Four closed segments; filled with currentColor they read as a solid
- // monochrome G like the other logos.
- Google: {
- paths: [
- 'm12.361 10.57v3.9663h4.6219c-0.4078 0.80304-1.004 1.4955-1.7375 2.0182l3.1612 2.5282c2.0047-1.8044 3.1501-4.3737 3.1519-7.0704v-0.72113c0-0.39827-0.32296-0.72113-0.72138-0.72113z',
- 'm6.4089 12.012a5.5531 5.5512 0 0 1 0.33738-1.8936l-3.1977-2.5572a9.505 9.5024 0 0 0 0 8.9014l3.1977-2.5572a5.5531 5.5512 0 0 1-0.33738-1.8936z',
- 'm12 6.4232a5.5538 5.5519 0 0 1 3.2881 1.0786l2.9289-2.7325a9.5329 9.5294 0 0 0-14.668 2.7918l3.1977 2.5572a5.595 5.5932 0 0 1 5.2532-3.6952z',
- 'm18.399 19.077-3.1528-2.5214a5.5868 5.585 0 0 1-8.5006-2.6502l-3.1977 2.5572a9.5539 9.5504 0 0 0 14.851 2.6144z',
- ],
- },
- GitHub: {
- paths: [
- 'M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12',
- ],
- },
- Notion: {
- paths: [
- 'M4.459 4.208c.746.606 1.026.56 2.428.466l13.215-.793c.28 0 .047-.28-.046-.326L17.86 1.968c-.42-.326-.981-.7-2.055-.607L3.01 2.295c-.466.046-.56.28-.374.466zm.793 3.08v13.904c0 .747.373 1.027 1.214.98l14.523-.84c.841-.046.935-.56.935-1.167V6.354c0-.606-.233-.933-.748-.887l-15.177.887c-.56.047-.747.327-.747.933zm14.337.745c.093.42 0 .84-.42.888l-.7.14v10.264c-.608.327-1.168.514-1.635.514-.748 0-.935-.234-1.495-.933l-4.577-7.186v6.952L12.21 19s0 .84-1.168.84l-3.222.186c-.093-.186 0-.653.327-.746l.84-.233V9.854L7.822 9.76c-.094-.42.14-1.026.793-1.073l3.456-.233 4.764 7.279v-6.44l-1.215-.139c-.093-.514.28-.887.747-.933zM1.936 1.035l13.31-.98c1.634-.14 2.055-.047 3.082.7l4.249 2.986c.7.513.934.653.934 1.213v16.378c0 1.026-.373 1.634-1.68 1.726l-15.458.934c-.98.047-1.448-.093-1.962-.747l-3.129-4.06c-.56-.747-.793-1.306-.793-1.96V2.667c0-.839.374-1.54 1.447-1.632z',
- ],
- },
- Slack: {
- paths: [
- 'M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313zM8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zm0 1.271a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312zm10.122 2.521a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zm-1.268 0a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312zm-2.523 10.122a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zm0-1.268a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z',
- ],
- },
-} satisfies Record<string, ModuleLogo>;
diff --git a/apps/web/src/features/setup/primitives.tsx b/apps/web/src/features/setup/primitives.tsx
deleted file mode 100644
index f3ecaf9125..0000000000
--- a/apps/web/src/features/setup/primitives.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-import CheckIcon from '@phosphor-icons/core/regular/check.svg?component-solid';
-import { cn, Layer } from '@ui';
-import { For, type JSX, Show } from 'solid-js';
-import { StatusDot } from '../settings/integration-ui';
-
-/*
- * Building blocks for the onboarding summary: one bordered card per
- * connected source, whose body is a cloud of narrow, content-fit pills.
- */
-
-/**
- * One source's card: a connector-first header (icon, name, count badge,
- * right-aligned actions), a recessed status well underneath — the same
- * inset treatment as the soup's active-filters bar — carrying the green
- * "Connected" dot and a blurb saying what Macro found, and the pill cloud
- * as the body.
- */
-export function ImportCard(props: {
- /** The connector's brand icon. */
- icon?: JSX.Element;
- /** The connector's name ("Notion") — the card leads with the tool. */
- title: string;
- /** Item count shown in a rounded badge beside the title. */
- count?: number;
- /** Lead the status well with the green dot + "Connected —". */
- connected?: boolean;
- /** Optional right-aligned header controls. */
- actions?: JSX.Element;
- /**
- * Status blurb rendered in the well after the "Connected —" lead-in, so
- * it should start lowercase ("here are 10 issues…").
- */
- status: JSX.Element;
- children?: JSX.Element;
-}) {
- return (
- <Layer depth={2}>
- <section class="flex flex-col gap-3 rounded-xl border border-ink/[0.05] bg-surface p-5">
- <div class="flex items-center gap-2">
- <Show when={props.icon}>
- <span class="flex size-4 shrink-0 items-center justify-center [&_svg]:size-4">
- {props.icon}
- </span>
- </Show>
- <h3 class="min-w-0 truncate text-sm font-semibold text-ink">
- {props.title}
- </h3>
- <Show when={props.count !== undefined}>
- <span class="shrink-0 rounded-full bg-ink/10 px-1.5 py-px text-xs font-medium tabular-nums text-ink-extra-muted">
- {props.count}
- </span>
- </Show>
- <Show when={props.actions}>
- <span class="ml-auto flex shrink-0 items-center gap-2">
- {props.actions}
- </span>
- </Show>
- </div>
- {/* Recessed status well (Layer depth 0 drops bg-surface to the
- darkest level, same as the soup active-filters bar). */}
- <Layer depth={0}>
- <div class="flex flex-wrap items-center gap-x-1.5 gap-y-1 rounded-lg border border-edge-muted bg-surface px-3 py-2.5 text-[13px] text-ink-muted">
- <Show when={props.connected}>
- <StatusDot state="connected" />
- <span class="font-medium text-ink">Connected</span>
- <span>—</span>
- </Show>
- {props.status}
- </div>
- </Layer>
- <Show when={props.children}>{props.children}</Show>
- </section>
- </Layer>
- );
-}
-
-/** Wrapping row of narrow pills. */
-export function PillGrid(props: { children: JSX.Element }) {
- return <div class="flex flex-wrap gap-1.5">{props.children}</div>;
-}
-
-/**
- * A narrow, content-fit pill for one importable item, whose content reads
- * like an inline @ mention: entity icon, optional muted identifier, the name
- * with the mention underline, then trailing status. Width hugs the content
- * (name truncated past a cap) so a section reads as a compact cloud instead
- * of a full-width list. Pills are display-only except imported ones, which
- * open the entity they became.
- */
-export function ItemPill(props: {
- icon?: JSX.Element;
- /** Muted shorthand before the name (e.g. a Linear identifier "MAC-42"). */
- code?: string;
- label: string;
- /** Trailing status icons (e.g. an in-flight spinner). */
- status?: JSX.Element;
- /** Hover detail (subtitle/description); falls back to the label. */
- title?: string;
- /**
- * The Macro entity this item already became (imported by the user or a
- * teammate). Renders as a quiet "already in your workspace" pill that
- * opens the existing entity.
- */
- importedHref?: string;
-}) {
- const content = (
- <>
- <Show when={props.icon}>
- <span
- class={cn(
- 'flex size-3.5 shrink-0 items-center justify-center [&_svg]:size-3.5',
- props.importedHref !== undefined ? 'opacity-50' : 'opacity-90'
- )}
- >
- {props.icon}
- </span>
- </Show>
- <Show when={props.code}>
- <span class="shrink-0 text-xs tabular-nums text-ink-extra-muted">
- {props.code}
- </span>
- </Show>
- <span class="min-w-0 truncate underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">
- {props.label}
- </span>
- <Show when={props.status}>
- <span class="flex shrink-0 items-center gap-1">{props.status}</span>
- </Show>
- </>
- );
- const base =
- 'inline-flex h-7 max-w-72 items-center gap-1.5 rounded-lg border px-2.5 text-[13px]';
-
- return (
- <Show
- when={props.importedHref}
- fallback={
- <span
- title={props.title ?? props.label}
- class={cn(base, 'border-ink/10 bg-surface text-ink')}
- >
- {content}
- </span>
- }
- >
- {(href) => (
- <button
- type="button"
- title="Already in your workspace — click to open"
- onClick={() => window.open(href(), '_blank')}
- class={cn(
- base,
- 'cursor-default border-ink/5 bg-ink/[0.03] text-ink-extra-muted outline-none',
- 'transition-colors hover:text-ink-muted focus-visible:ring-1 focus-visible:ring-accent/50'
- )}
- >
- {content}
- <span class="flex shrink-0 items-center gap-1 text-xs text-ink-extra-muted">
- <CheckIcon class="size-3 shrink-0" />
- in Macro
- </span>
- </button>
- )}
- </Show>
- );
-}
-
-const SKELETON_WIDTHS = [88, 128, 72, 148, 104, 80, 136, 96];
-
-/**
- * Shimmering placeholder pills while a gather job runs: ghost outlines of
- * the real pills (icon dot + text bar) pulsing on a slight stagger. Renders
- * bare spans so it can sit inside a `PillGrid` after the pills that already
- * landed.
- */
-export function SkeletonPills(props: { count?: number }) {
- return (
- <For each={SKELETON_WIDTHS.slice(0, props.count ?? 6)}>
- {(width, index) => (
- <span
- class="flex h-7 w-(--pill-width) animate-pulse items-center gap-1.5 rounded-lg border border-ink/5 px-2.5 [animation-delay:var(--pill-delay)]"
- style={{
- '--pill-width': `${width}px`,
- '--pill-delay': `${index() * 150}ms`,
- }}
- >
- <span class="size-3.5 shrink-0 rounded-full bg-ink/10" />
- <span class="h-2 min-w-0 flex-1 rounded-full bg-ink/10" />
- </span>
- )}
- </For>
- );
-}
-
-/** Inline failure note with a retry affordance. */
-export function FailureNote(props: { message?: string; onRetry: () => void }) {
- return (
- <span class="flex items-center gap-3">
- <span class="min-w-0 truncate">
- {props.message ?? "Something went wrong — this one's on us."}
- </span>
- <button
- type="button"
- class="shrink-0 font-medium text-ink-muted transition-colors hover:text-ink"
- onClick={() => props.onRetry()}
- >
- Retry
- </button>
- </span>
- );
-}
diff --git a/apps/web/src/features/setup/selection.ts b/apps/web/src/features/setup/selection.ts
deleted file mode 100644
index 2ba693cecb..0000000000
--- a/apps/web/src/features/setup/selection.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import type { ImportSource } from '@queries/import';
-
-/*
- * Import-source display metadata shared by onboarding summary cards.
- */
-
-/** Display order, connector identity, and item noun for one source. */
-export interface SourceSection {
- source: ImportSource;
- serverName: string;
- /** What the items are called in blurbs ("we found 16 documents…"). */
- noun: string;
-}
-
-/** All import sources, in display order. */
-export const SOURCE_SECTIONS: SourceSection[] = [
- { source: 'linear', serverName: 'Linear', noun: 'issues' },
- { source: 'notion', serverName: 'Notion', noun: 'documents' },
- { source: 'slack', serverName: 'Slack', noun: 'channels' },
-];
diff --git a/apps/web/src/features/setup/useConnectorConnect.ts b/apps/web/src/features/setup/useConnectorConnect.ts
deleted file mode 100644
index 1aafe9b1c8..0000000000
--- a/apps/web/src/features/setup/useConnectorConnect.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import type { FeaturedMcpServer } from '@core/component/AI/constant/mcpServers';
-import { toast } from '@core/component/Toast/Toast';
-import { usePipedreamMcpFlag } from '@core/pipedream/flag';
-import { isTauri } from '@core/util/platform';
-import { openExternalUrl } from '@core/util/url';
-import {
- useAddMcpServerMutation,
- useStartMcpAuthMutation,
-} from '@queries/mcp-servers';
-import { connectPipedreamApp } from '@queries/pipedream-connectors';
-import type { StartAuthResponse } from '@service-cognition/generated/schemas';
-import { type Accessor, createSignal } from 'solid-js';
-
-/**
- * The connect-a-tool workflow used by onboarding's connector steps: 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).
- *
- * Inside the Tauri shell there are no popup blockers and `_blank` opens
- * never reach the native navigation hook (on iOS they're silently dropped),
- * so the popup dance is skipped and the URL is handed to the system browser
- * via `openExternalUrl` once it's known.
- *
- * 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 pipedreamMcp = usePipedreamMcpFlag();
- const [busy, setBusy] = createSignal(false);
-
- const connect = async () => {
- if (options.authenticated() || busy()) return;
- setBusy(true);
- // Behind the PostHog flag, connectors go through Pipedream's hosted
- // Connect UI (an iframe — no popup involved) instead of the native
- // OAuth popup flow.
- if (pipedreamMcp()) {
- try {
- const outcome = await connectPipedreamApp({
- appSlug: options.server.app_slug,
- serverName: options.server.server_name,
- });
- if (outcome === 'unsupported') {
- toast.failure('Connectors are not available on this deployment');
- }
- } catch {
- toast.failure(`Failed to connect ${options.server.server_name}`);
- } finally {
- setBusy(false);
- }
- return;
- }
- const popup = isTauri() ? null : 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 {
- // Native shell, or the popup was blocked outright — openExternalUrl
- // routes through the system browser on Tauri and is a plain
- // noopener open on web (may still be blocked, but nothing else to
- // try).
- openExternalUrl(result.authorization_url);
- }
- } catch {
- popup?.close();
- toast.failure(`Failed to connect ${options.server.server_name}`);
- } finally {
- setBusy(false);
- }
- };
-
- return { connect, busy };
-}
diff --git a/apps/web/src/features/tours/ViewTour.tsx b/apps/web/src/features/tours/ViewTour.tsx
index 8060f60696..80d51a6711 100644
--- a/apps/web/src/features/tours/ViewTour.tsx
+++ b/apps/web/src/features/tours/ViewTour.tsx
@@ -1,5 +1,5 @@
import { VIEW_SHELL_TOUR } from '@app/components/view-shell/tour';
-import { isMcpToolConnected } from '@app/features/setup/core/connectedTools';
+import { isMcpToolConnected } from '@app/features/tours/core/connected-tools';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { enableInAppTours } from '@core/constant/featureFlags';
import { useSettingsState } from '@core/constant/SettingsState';
diff --git a/apps/web/src/features/setup/core/connectedTools.ts b/apps/web/src/features/tours/core/connected-tools.ts
similarity index 100%
rename from apps/web/src/features/setup/core/connectedTools.ts
rename to apps/web/src/features/tours/core/connected-tools.ts
diff --git a/apps/web/src/features/onboarding/InteractiveOnboarding.tsx b/apps/web/src/features/tutorial/InteractiveOnboarding.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/InteractiveOnboarding.tsx
rename to apps/web/src/features/tutorial/InteractiveOnboarding.tsx
diff --git a/apps/web/src/features/onboarding/InteractiveOnboardingModal.tsx b/apps/web/src/features/tutorial/InteractiveOnboardingModal.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/InteractiveOnboardingModal.tsx
rename to apps/web/src/features/tutorial/InteractiveOnboardingModal.tsx
diff --git a/apps/web/src/features/onboarding/OnboardingEntityList.tsx b/apps/web/src/features/tutorial/OnboardingEntityList.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/OnboardingEntityList.tsx
rename to apps/web/src/features/tutorial/OnboardingEntityList.tsx
diff --git a/apps/web/src/features/onboarding/OnboardingProgress.tsx b/apps/web/src/features/tutorial/OnboardingProgress.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/OnboardingProgress.tsx
rename to apps/web/src/features/tutorial/OnboardingProgress.tsx
diff --git a/apps/web/src/features/onboarding/components-lib.tsx b/apps/web/src/features/tutorial/components-lib.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/components-lib.tsx
rename to apps/web/src/features/tutorial/components-lib.tsx
diff --git a/apps/web/src/features/onboarding/components/MockAppChrome.tsx b/apps/web/src/features/tutorial/components/MockAppChrome.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/components/MockAppChrome.tsx
rename to apps/web/src/features/tutorial/components/MockAppChrome.tsx
diff --git a/apps/web/src/features/onboarding/create-onboarding-state.test.ts b/apps/web/src/features/tutorial/create-onboarding-state.test.ts
similarity index 100%
rename from apps/web/src/features/onboarding/create-onboarding-state.test.ts
rename to apps/web/src/features/tutorial/create-onboarding-state.test.ts
diff --git a/apps/web/src/features/onboarding/create-onboarding-state.ts b/apps/web/src/features/tutorial/create-onboarding-state.ts
similarity index 100%
rename from apps/web/src/features/onboarding/create-onboarding-state.ts
rename to apps/web/src/features/tutorial/create-onboarding-state.ts
diff --git a/apps/web/src/features/onboarding/lessons/command-k.tsx b/apps/web/src/features/tutorial/lessons/command-k.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/lessons/command-k.tsx
rename to apps/web/src/features/tutorial/lessons/command-k.tsx
diff --git a/apps/web/src/features/onboarding/lessons/create-entity.tsx b/apps/web/src/features/tutorial/lessons/create-entity.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/lessons/create-entity.tsx
rename to apps/web/src/features/tutorial/lessons/create-entity.tsx
diff --git a/apps/web/src/features/onboarding/lessons/index.ts b/apps/web/src/features/tutorial/lessons/index.ts
similarity index 100%
rename from apps/web/src/features/onboarding/lessons/index.ts
rename to apps/web/src/features/tutorial/lessons/index.ts
diff --git a/apps/web/src/features/onboarding/lessons/markdown-mentions.tsx b/apps/web/src/features/tutorial/lessons/markdown-mentions.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/lessons/markdown-mentions.tsx
rename to apps/web/src/features/tutorial/lessons/markdown-mentions.tsx
diff --git a/apps/web/src/features/onboarding/lessons/sidebar-nav.tsx b/apps/web/src/features/tutorial/lessons/sidebar-nav.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/lessons/sidebar-nav.tsx
rename to apps/web/src/features/tutorial/lessons/sidebar-nav.tsx
diff --git a/apps/web/src/features/onboarding/onboarding-context.tsx b/apps/web/src/features/tutorial/onboarding-context.tsx
similarity index 100%
rename from apps/web/src/features/onboarding/onboarding-context.tsx
rename to apps/web/src/features/tutorial/onboarding-context.tsx
diff --git a/apps/web/src/features/onboarding/sandbox/sandbox-store.ts b/apps/web/src/features/tutorial/sandbox/sandbox-store.ts
similarity index 100%
rename from apps/web/src/features/onboarding/sandbox/sandbox-store.ts
rename to apps/web/src/features/tutorial/sandbox/sandbox-store.ts
diff --git a/apps/web/src/features/onboarding/types.ts b/apps/web/src/features/tutorial/types.ts
similarity index 100%
rename from apps/web/src/features/onboarding/types.ts
rename to apps/web/src/features/tutorial/types.ts
diff --git a/apps/web/src/features/onboarding/use-list-navigation.ts b/apps/web/src/features/tutorial/use-list-navigation.ts
similarity index 100%
rename from apps/web/src/features/onboarding/use-list-navigation.ts
rename to apps/web/src/features/tutorial/use-list-navigation.ts
diff --git a/apps/web/src/lib/core/component/NoiseBackground.tsx b/apps/web/src/lib/core/component/NoiseBackground.tsx
new file mode 100644
index 0000000000..8f8eaeb18c
--- /dev/null
+++ b/apps/web/src/lib/core/component/NoiseBackground.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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%)`}
+ />
+ </>
+ );
+}
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 3fd70477b2..bf66d3f776 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -566,18 +566,6 @@ export const botManagement = defineFlag({
default: onInDev,
});
-// Onboarding v4: the full-screen stepper new users land in after signup
-// (unified with /login), driving the import machinery with auto-import.
-// PostHog-gated; override with VITE_ENABLE_ONBOARDING_V4. Read it through
-// `useOnboardingV4Flag()` so the gate reacts when PostHog answers (and so
-// callers can wait instead of treating "flags not loaded yet" as "off").
-// `just run_local` sets the env to false unless `--enable-onboarding`.
-export const enableOnboardingV4 = defineFlag({
- key: 'enable-onboarding-v4',
- env: 'ENABLE_ONBOARDING_V4',
- default: onInDev,
-});
-
// Calendar UI: calendar surfaces and the elevated-permissions upgrade flow
// that re-runs Google consent for inboxes connected before the calendar
// scope existed. PostHog-gated with a dev-mode default; override with
diff --git a/apps/web/src/lib/core/util/cookies.ts b/apps/web/src/lib/core/util/cookies.ts
index ffa2d9f5ed..39e300c7c0 100644
--- a/apps/web/src/lib/core/util/cookies.ts
+++ b/apps/web/src/lib/core/util/cookies.ts
@@ -92,3 +92,11 @@ export function updateCookie(
document.cookie = newCookie;
}
+
+/** Set a site-wide cookie that expires after `days`. */
+export function setCookie(name: string, value: string, days: number) {
+ const expires = days
+ ? `; expires=${new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString()}`
+ : '';
+ document.cookie = `${name}=${encodeURIComponent(value)}${expires}; path=/`;
+}
diff --git a/apps/web/src/lib/queries/github-stars.ts b/apps/web/src/lib/queries/github-stars.ts
new file mode 100644
index 0000000000..dd4bdfd1db
--- /dev/null
+++ b/apps/web/src/lib/queries/github-stars.ts
@@ -0,0 +1,14 @@
+import { useQuery } from '@tanstack/solid-query';
+import { getMacroGithubStars } from '../service-clients/service-github-public/client';
+
+/** Shared across onboarding mounts; this public request needs no sign-in. */
+export function useGithubStarsQuery() {
+ return useQuery(() => ({
+ queryKey: ['public', 'github', 'macro-inc/macro', 'stars'],
+ queryFn: ({ signal }) => getMacroGithubStars(signal),
+ staleTime: 60 * 60 * 1000,
+ gcTime: 24 * 60 * 60 * 1000,
+ retry: 1,
+ throwOnError: false,
+ }));
+}
diff --git a/apps/web/src/lib/queries/import.ts b/apps/web/src/lib/queries/import.ts
index 059324ce98..c4ced6fe50 100644
--- a/apps/web/src/lib/queries/import.ts
+++ b/apps/web/src/lib/queries/import.ts
@@ -26,16 +26,11 @@ import {
export type {
ImportEntity,
ImportEntityStatus,
- ImportInitiator,
ImportRun,
ImportRunStatus,
ImportSource,
ImportState,
- LinearIssueMeta,
- NotionDocMeta,
- RunImportOutcome,
SlackChannelMeta,
- SlackParticipant,
} from '@service-cognition/import';
const KEYS = {
@@ -83,20 +78,6 @@ function invalidateImportState() {
return queryClient.invalidateQueries({ queryKey: KEYS.state });
}
-/**
- * Imperatively fetch the import aggregate through the shared cache — for
- * non-component polling loops (the setup finish hold). Keeps every read on
- * the TanStack path so concurrent `useImportQuery` subscribers see the same
- * data.
- */
-export function fetchImportState(): Promise<ImportState> {
- return queryClient.fetchQuery({
- queryKey: KEYS.state,
- queryFn: async () => throwOnErr(() => importClient.getState()),
- staleTime: 0,
- });
-}
-
/**
* Accept and/or decline staged rows. The server flips accepted rows to
* `importing` and returns immediately; completion arrives via
@@ -128,24 +109,6 @@ export function useDiscoverMutation(): UseMutationResult<
}));
}
-/** Restart a failed gather run. */
-export function useRetryGatherMutation() {
- return useMutation(() => ({
- mutationFn: async (source: ImportSource) =>
- throwOnErr(() => importClient.retryGather(source)),
- onSuccess: () => void invalidateImportState(),
- }));
-}
-
-/** Dismiss one source's import section. */
-export function useDismissRunMutation() {
- return useMutation(() => ({
- mutationFn: async (source: ImportSource) =>
- throwOnErr(() => importClient.dismissRun(source)),
- onSuccess: () => void invalidateImportState(),
- }));
-}
-
/** Slack channel metadata, only for Slack ledger rows. */
export function slackChannelMeta(
entity: ImportEntity
@@ -153,10 +116,3 @@ export function slackChannelMeta(
if (entity.source !== 'slack') return null;
return entity.metadata as SlackChannelMeta;
}
-
-/** A human label for a ledger row, from its per-source metadata. */
-export function entityLabel(entity: ImportEntity): string {
- const field = entity.source === 'slack' ? 'name' : 'title';
- const value = entity.metadata[field];
- return typeof value === 'string' && value.length > 0 ? value : '(unnamed)';
-}
diff --git a/apps/web/src/lib/queries/onboarding.ts b/apps/web/src/lib/queries/onboarding.ts
index fc9fb9b29d..4852ecc0b4 100644
--- a/apps/web/src/lib/queries/onboarding.ts
+++ b/apps/web/src/lib/queries/onboarding.ts
@@ -13,13 +13,6 @@ import {
} from '@service-cognition/onboarding';
import { useMutation, useQuery } from '@tanstack/solid-query';
-export type {
- ConnectedServer,
- OnboardingRow,
- OnboardingState,
- OnboardingStatus,
-} from '@service-cognition/onboarding';
-
const KEYS = {
state: ['onboarding', 'state'] as const,
};
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index 8e5d7df087..5c27f296b8 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -21,6 +21,7 @@ import type {
} from './ai-billing-types';
import { fetchWithAuth as _fetchWithAuth } from './fetch';
import type {
+ CheckoutSessionV2Response,
CursorApiKeyStatus,
CursorModelsResponse,
EnrichGithubPullRequestsProxyRequest,
@@ -677,22 +678,23 @@ export const authServiceClient = {
};
/** The plan to subscribe to. The backend defaults to Premium. */
plan?: PaidPlan;
+ /** Request the server-validated first-subscription trial. */
+ onboardingTrial?: boolean;
}) {
- return (
- await fetchWithAuth<{ url: string }>(
- `${authHost}/user/stripe/checkoutv2`,
- {
- method: 'POST',
- body: JSON.stringify({
- successUrl: args.successUrl,
- cancelUrl: args.cancelUrl,
- discount: args.discount ?? undefined,
- metadata: args.metadata,
- plan: args.plan,
- }),
- }
- )
- ).map((result) => result.url);
+ return await fetchWithAuth<CheckoutSessionV2Response>(
+ `${authHost}/user/stripe/checkoutv2`,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ successUrl: args.successUrl,
+ cancelUrl: args.cancelUrl,
+ discount: args.discount ?? undefined,
+ metadata: args.metadata,
+ plan: args.plan,
+ onboardingTrial: args.onboardingTrial,
+ }),
+ }
+ );
},
/**
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
index b0f6ceb14a..ddd018c0d0 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
@@ -9,6 +9,7 @@ import type {
AppleLoginRequest,
ChangePlanRequest,
ChangePlanResponse,
+ CheckoutSessionV2Response,
CodexConfigRequest,
CodexConnectionStatus,
CodexEnvironment,
@@ -5468,7 +5469,7 @@ export const getUserQuota = async (
* @summary Creates a Stripe checkout session for the user to subscribe.
*/
export type createCheckoutSessionV2Response200 = {
- data: StripeSessionResponse;
+ data: CheckoutSessionV2Response;
status: 200;
};
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/checkoutSessionV2Response.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/checkoutSessionV2Response.ts
new file mode 100644
index 0000000000..c31184946d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/checkoutSessionV2Response.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CheckoutSessionV2ResponseTrialDays } from './checkoutSessionV2ResponseTrialDays';
+
+/**
+ * Hosted checkout with the billing terms the server actually granted.
+ */
+export interface CheckoutSessionV2Response {
+ /**
+ * Trial duration, absent for an immediately paid checkout.
+ * @minimum 0
+ */
+ trialDays?: CheckoutSessionV2ResponseTrialDays;
+ /** The opaque URL returned by Stripe. */
+ url: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/checkoutSessionV2ResponseTrialDays.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/checkoutSessionV2ResponseTrialDays.ts
new file mode 100644
index 0000000000..d62de5c096
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/checkoutSessionV2ResponseTrialDays.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Trial duration, absent for an immediately paid checkout.
+ * @minimum 0
+ */
+export type CheckoutSessionV2ResponseTrialDays = number | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts
index 806e841793..54be9c75f9 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts
@@ -19,6 +19,8 @@ export interface CreateCheckoutSessionV2Request {
discount?: CreateCheckoutSessionV2RequestDiscount;
/** Tracking metadata for conversion attribution */
metadata?: CheckoutSessionMetadata;
+ /** Request the automatic, first-subscription 30-day Premium trial. */
+ onboardingTrial?: boolean;
plan?: CreateCheckoutSessionV2RequestPlan;
/** The URL to redirect to on successful checkout */
successUrl: string;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
index 513e59edec..5a487ee7bd 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
@@ -14,6 +14,8 @@ export * from './checkoutSessionMetadata';
export * from './checkoutSessionMetadataFbc';
export * from './checkoutSessionMetadataFbp';
export * from './checkoutSessionMetadataGaClientId';
+export * from './checkoutSessionV2Response';
+export * from './checkoutSessionV2ResponseTrialDays';
export * from './codexConfigRequest';
export * from './codexConnectionStatus';
export * from './codexConnectionStatusAccountId';
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index 44d18cdf1f..a238cf27a8 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -4568,7 +4568,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/StripeSessionResponse"
+ "$ref": "#/components/schemas/CheckoutSessionV2Response"
}
}
}
@@ -4884,6 +4884,23 @@
}
}
},
+ "CheckoutSessionV2Response": {
+ "type": "object",
+ "description": "Hosted checkout with the billing terms the server actually granted.",
+ "required": ["url"],
+ "properties": {
+ "trialDays": {
+ "type": ["integer", "null"],
+ "format": "int32",
+ "description": "Trial duration, absent for an immediately paid checkout.",
+ "minimum": 0
+ },
+ "url": {
+ "type": "string",
+ "description": "The opaque URL returned by Stripe."
+ }
+ }
+ },
"CodexConfigRequest": {
"type": "object",
"description": "Explicit remote environment for future Codex sessions.",
@@ -5040,6 +5057,10 @@
"$ref": "#/components/schemas/CheckoutSessionMetadata",
"description": "Tracking metadata for conversion attribution"
},
+ "onboardingTrial": {
+ "type": "boolean",
+ "description": "Request the automatic, first-subscription 30-day Premium trial."
+ },
"plan": {
"oneOf": [
{
diff --git a/apps/web/src/lib/service-clients/service-github-public/client.ts b/apps/web/src/lib/service-clients/service-github-public/client.ts
new file mode 100644
index 0000000000..5d6f6be342
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-github-public/client.ts
@@ -0,0 +1,21 @@
+/** Public repository metadata; never send Macro credentials to GitHub. */
+export async function getMacroGithubStars(
+ signal?: AbortSignal
+): Promise<number> {
+ const response = await fetch('https://api.github.com/repos/macro-inc/macro', {
+ credentials: 'omit',
+ signal,
+ });
+ if (!response.ok) throw new Error('Unable to load GitHub stars');
+ const data: unknown = await response.json();
+ if (
+ typeof data !== 'object' ||
+ data === null ||
+ !('stargazers_count' in data) ||
+ typeof data.stargazers_count !== 'number' ||
+ !Number.isSafeInteger(data.stargazers_count) ||
+ data.stargazers_count < 0
+ )
+ throw new Error('Invalid GitHub star count');
+ return data.stargazers_count;
+}
diff --git a/apps/web/src/lib/service-clients/service-stripe/client.test.ts b/apps/web/src/lib/service-clients/service-stripe/client.test.ts
new file mode 100644
index 0000000000..20a83fa186
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-stripe/client.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ checkout: vi.fn() }));
+vi.mock('@service-auth/client', () => ({
+ authServiceClient: { createCheckoutSessionV2: mocks.checkout },
+}));
+vi.mock('@core/util/mockClient', () => ({ registerClient: vi.fn() }));
+
+import { stripeServiceClient } from './client';
+
+beforeEach(() => mocks.checkout.mockReset());
+const url = 'https://checkout.stripe.com/test';
+const response = (trialDays?: number | null) => ({
+ isOk: () => true,
+ value: { url, trialDays },
+});
+
+describe('automatic onboarding trial checkout', () => {
+ it('requests the trial without a code and returns its confirmed checkout', async () => {
+ mocks.checkout.mockResolvedValue(response(30));
+ await expect(
+ stripeServiceClient.createCheckoutSessionV2({
+ plan: 'premium',
+ onboardingTrial: true,
+ })
+ ).resolves.toBe(url);
+ expect(mocks.checkout).toHaveBeenCalledWith(
+ expect.objectContaining({
+ plan: 'premium',
+ onboardingTrial: true,
+ discount: null,
+ })
+ );
+ });
+
+ it.each([undefined, null, 0, 7])(
+ 'refuses a trial redirect when the backend returns %s trial days',
+ async (days) => {
+ mocks.checkout.mockResolvedValue(response(days));
+ await expect(
+ stripeServiceClient.createCheckoutSessionV2({
+ plan: 'premium',
+ onboardingTrial: true,
+ })
+ ).rejects.toThrow('Your free trial could not be confirmed');
+ }
+ );
+
+ it('preserves normal paid checkout for callers that did not request a trial', async () => {
+ mocks.checkout.mockResolvedValue(response());
+ await expect(
+ stripeServiceClient.createCheckoutSessionV2({ plan: 'premium' })
+ ).resolves.toBe(url);
+ });
+
+ it('preserves an ineligibility error instead of redirecting to paid checkout', async () => {
+ mocks.checkout.mockResolvedValue({
+ isOk: () => false,
+ error: [
+ {
+ message:
+ 'The 30-day trial is only available for your first Premium subscription',
+ },
+ ],
+ });
+ await expect(
+ stripeServiceClient.createCheckoutSessionV2({ onboardingTrial: true })
+ ).rejects.toThrow('only available for your first Premium subscription');
+ });
+});
diff --git a/apps/web/src/lib/service-clients/service-stripe/client.ts b/apps/web/src/lib/service-clients/service-stripe/client.ts
index 2866ba3f0d..b0ad520b71 100644
--- a/apps/web/src/lib/service-clients/service-stripe/client.ts
+++ b/apps/web/src/lib/service-clients/service-stripe/client.ts
@@ -35,8 +35,8 @@ function getGaClientId(): Promise<string | undefined> {
export const stripeServiceClient = {
/**
- * Creates a checkout session via the v2 endpoint. Unlike v1, this does not
- * accept a tier — the backend infers it from the new pricing model.
+ * Creates a checkout session via the v2 endpoint. The backend resolves the
+ * plan price and trial eligibility; trial requests require confirmed terms.
* @returns The URL of the checkout session
*/
createCheckoutSessionV2: async (
@@ -49,9 +49,18 @@ export const stripeServiceClient = {
cancelUrl?: string;
/** The plan to subscribe to; defaults to Premium. */
plan?: PaidPlan;
+ /** Request the server-validated first-subscription trial. */
+ onboardingTrial?: boolean;
} = {}
) => {
- const { type = '', discount, successUrl, cancelUrl, plan } = args;
+ const {
+ type = '',
+ discount,
+ successUrl,
+ cancelUrl,
+ plan,
+ onboardingTrial,
+ } = args;
const gaClientId = await getGaClientId();
const { fbp, fbc } = getMetaIds();
@@ -68,6 +77,7 @@ export const stripeServiceClient = {
fbc: fbc ?? null,
},
plan,
+ onboardingTrial,
});
if (!result.isOk()) {
@@ -76,7 +86,12 @@ export const stripeServiceClient = {
);
}
- return result.value;
+ if (onboardingTrial && result.value.trialDays !== 30) {
+ throw new Error(
+ 'Your free trial could not be confirmed. Please try again later.'
+ );
+ }
+ return result.value.url;
},
/**
* Creates a portal session
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index 460d5f7a6b..a8c4390692 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -1,14 +1,12 @@
import { ROUTER_BASE, ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
-import { setCookie } from '@app/features/auth/Shared';
import { usePendingInviteRedemption } from '@app/features/gtm-invite/usePendingInviteRedemption';
import { HomePreferencesProvider } from '@app/features/home/home-prefs';
import { GlobalShareInboxConflictDialog } from '@app/features/inbox/ShareInboxConflictDialog';
import { IncomingMeetingInvitationsProvider } from '@app/features/meetings/incoming-meeting-invitations';
import { MeetingSessionProvider } from '@app/features/meetings/meeting-session-provider';
import { usePendingNotificationNavigationEffect } from '@app/features/notifications/PendingNotificationNavigationEffect';
-import { InteractiveOnboardingModal } from '@app/features/onboarding/InteractiveOnboardingModal';
-import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';
import { SearchProvider } from '@app/features/soup/search/context';
+import { InteractiveOnboardingModal } from '@app/features/tutorial/InteractiveOnboardingModal';
import {
AnalyticsContextProvider,
useAnalytics,
@@ -29,7 +27,6 @@ import { Layout } from '@components/app/Layout';
import { ReactiveFavicon } from '@components/app/ReactiveFavicon';
import { ChatAttachmentsInit } from '@core/component/AI/signal/globalAttachments';
import { ToastRegion } from '@core/component/Toast/ToastRegion';
-import { enableOnboardingV4 } from '@core/constant/featureFlags';
import { ChannelsContextProvider } from '@core/context/channels';
import { EmailLinksContextProvider } from '@core/context/emailLinks';
import { QuickAccessProvider } from '@core/context/quickAccess';
@@ -49,6 +46,7 @@ import { createBlockOrchestrator } from '@core/orchestrator';
import { formatTabTitle, tabTitleSignal } from '@core/signal/tabTitle';
import {
getLoginCookieOptions,
+ setCookie,
syncLoginStorage,
updateCookie,
} from '@core/util/cookies';
@@ -295,20 +293,13 @@ function QuerySyncProviderWithUserId() {
function InitialInteractiveOnboardingModal() {
const userInfoQuery = useUserInfoQuery();
- const onboardingV4 = useOnboardingV4Flag();
const [open, setOpen] = createSignal(true);
const [onboardingStarted, setOnboardingStarted] = createSignal(false);
const modalOpen = () =>
open() &&
- // `just run_local` sets VITE_ENABLE_ONBOARDING_V4=false; without this the
- // v4-off fallback would still open this legacy modal. Opt in with
- // `just run_local --enable-onboarding`.
- enableOnboardingV4.override !== false &&
- // Onboarding-v4 replaces this modal on desktop; the Layout redirect
- // sends first-time users to /onboarding instead. Desktop waits for the
- // flag to resolve so this doesn't flash before that redirect fires.
- (isMobile() || (!onboardingV4().loading && !onboardingV4().enabled)) &&
+ // Desktop first-run users go through /onboarding instead (Layout redirect).
+ isMobile() &&
!isNativeMobilePlatform() &&
userInfoQuery.data?.authenticated === true &&
(userInfoQuery.data.tutorialComplete === false || onboardingStarted());
diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsx
index 1be14370ca..e54113c03b 100644
--- a/apps/web/src/routes/app-router-view.tsx
+++ b/apps/web/src/routes/app-router-view.tsx
@@ -1,6 +1,7 @@
import { ROUTER_BASE } from '@app/constants/routerBase';
import { ActivityRouteView } from '@app/features/activity/route-views';
import { AgentsRouteView } from '@app/features/agents-view/route-views';
+import { MobileWebSignup } from '@app/features/auth/auth';
import { CallDetailRouteView } from '@app/features/block-call/route-views';
import { PrDetailRouteView } from '@app/features/block-pr/route-views';
import { CalendarRouteView } from '@app/features/calendar-view/route-views';
@@ -32,7 +33,6 @@ import {
RecentRouteView,
SearchRouteView,
} from '@app/features/next-soup/route-views';
-import MobileWebSignup from '@app/features/onboarding/MobileWebSignup';
import {
ReminderDetailRouteView,
RemindersRouteView,
@@ -79,7 +79,6 @@ import {
LoginPopupSuccess,
OnboardingPage,
PublicBookingRoutePage,
- SetupPage,
SignupPage,
TaskSlugPage,
WelcomePage,
@@ -143,7 +142,6 @@ import {
routinesRoute,
searchRoute,
settingsRoute,
- setupRoute,
signupRoute,
taskDetailRoute,
taskSlugRoute,
@@ -219,7 +217,6 @@ export function AppRouterView() {
<Route definition={welcomeRoute} component={WelcomePage} />
<Route definition={mobileEmailSignupRoute} component={MobileWebSignup} />
<Route definition={onboardingRoute} component={OnboardingPage} />
- <Route definition={setupRoute} component={SetupPage} />
<Route definition={inviteRoute} component={InviteWelcome} />
<Route
definition={internalInviteLinksRoute}
diff --git a/apps/web/src/routes/pages.tsx b/apps/web/src/routes/pages.tsx
index a1151277c3..042357f611 100644
--- a/apps/web/src/routes/pages.tsx
+++ b/apps/web/src/routes/pages.tsx
@@ -1,20 +1,17 @@
+import { Login } from '@app/features/auth/auth';
import { makeEmailAuthComponents } from '@app/features/auth/EmailAuth';
-import { Login } from '@app/features/auth/Login';
-import { MobileAuthWelcome } from '@app/features/auth/mobile-onboarding/MobileAuthWelcome';
-import { MobileOnboarding } from '@app/features/auth/mobile-onboarding/MobileOnboarding';
+import { MobileAuthWelcome } from '@app/features/mobile-onboarding/MobileAuthWelcome';
+import { MobileOnboarding } from '@app/features/mobile-onboarding/MobileOnboarding';
+import { Onboarding } from '@app/features/onboarding/onboarding';
import {
BookingReceiptPage,
PublicBookingPage,
} from '@app/features/scheduling/public-booking';
-import { OnboardingFlow } from '@app/features/setup/flow/OnboardingFlow';
-import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';
import { useRouteParams } from '@app/lib/split-router';
import { publishLoginSuccess } from '@core/auth/login-events';
-import { LoadingBlock } from '@core/component/LoadingBlock';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
-import { Navigate, useLocation } from '@solidjs/router';
import { Button } from '@ui';
-import { onCleanup, onMount, Show } from 'solid-js';
+import { onCleanup, onMount } from 'solid-js';
import {
bookingReceiptRoute,
EMAIL_SIGNUP_CALLBACK_PATH,
@@ -42,53 +39,8 @@ export function WelcomePage() {
return isNativeMobilePlatform() ? <MobileAuthWelcome /> : <Login />;
}
-/** The retired /setup path forwards to the onboarding flow, query intact. */
-function SetupRedirect() {
- const location = useLocation();
- return <Navigate href={`/onboarding${location.search}`} />;
-}
-
-/**
- * The old split-screen /setup surface is retired; the onboarding flow lives at
- * /onboarding now. Flag off, /setup must go home — forwarding would land
- * flag-off web users on /login and native users on MobileOnboarding.
- */
-export function SetupPage() {
- const onboardingV4 = useOnboardingV4Flag();
-
- return (
- <Show when={!onboardingV4().loading} fallback={<LoadingBlock />}>
- <Show when={onboardingV4().enabled} fallback={<Navigate href="/" />}>
- <SetupRedirect />
- </Show>
- </Show>
- );
-}
-
-/**
- * Web/desktop gate for /onboarding. Waits for PostHog to report flags before
- * bouncing: with the flag on but not yet loaded, a direct visit (or a reload
- * mid-flow) would otherwise get kicked to /login and lose its ?next.
- */
-function OnboardingRoute() {
- const onboardingV4 = useOnboardingV4Flag();
-
- return (
- <Show when={!onboardingV4().loading} fallback={<LoadingBlock />}>
- <Show when={onboardingV4().enabled} fallback={<Navigate href="/login" />}>
- <OnboardingFlow />
- </Show>
- </Show>
- );
-}
-
-/**
- * Flag-gated here, not just at 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).
- */
export function OnboardingPage() {
- return isNativeMobilePlatform() ? <MobileOnboarding /> : <OnboardingRoute />;
+ return isNativeMobilePlatform() ? <MobileOnboarding /> : <Onboarding />;
}
export function LoginPopupSuccess() {
diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.ts
index 4f57afb439..da3b09a53c 100644
--- a/apps/web/src/routes/routes.ts
+++ b/apps/web/src/routes/routes.ts
@@ -137,13 +137,6 @@ export const onboardingRoute = defineRoute({
externalSearch: '*',
});
-/** The retired setup path; it forwards to onboarding with its query (?next deep links). */
-export const setupRoute = defineRoute({
- id: 'setup',
- path: 'setup',
- externalSearch: '*',
-});
-
/** A personal GTM invite link (`?token=`): welcome page, then signup. */
export const inviteRoute = defineRoute({
id: 'invite',
diff --git a/docs/AGENT_GUIDE/login.md b/docs/AGENT_GUIDE/login.md
index facfcf3515..0a4c64fc7e 100644
--- a/docs/AGENT_GUIDE/login.md
+++ b/docs/AGENT_GUIDE/login.md
@@ -87,6 +87,70 @@ Use browser Back to return from GitHub: when the page is restored from BFCache,
it refreshes link status and restores the retry prompt only if reconnection is
still needed.
+## Desktop onboarding
+
+New desktop users enter the same flow from
+`/app/signup`, `/app/login`, or `/app/onboarding`. Marketing Get Started links
+open `/app/signup`. Existing members and native mobile keep their existing routes.
+
+Signed-out `/app/signup` starts at the workspace color picker, followed by feature
+interests and security. No account is required for these slides. At the work-email
+step, Connect work email uses Google sign-up to create the Macro account and link
+the primary inbox. This step offers Google sign-up only, with no alternate email
+button. The chosen accent and work step survive the OAuth
+redirect; after authentication the accent is saved to the user's theme and setup
+resumes at work email. Regular `/app/login` retains the direct sign-in screen.
+
+The steps are workspace color, feature interests, security, work Google account,
+personal Google account, tools, team, and the trial offer. Color selection forks
+the default Macro Light or Macro Dark theme for the current mode and pins the
+custom accent palette; it does not modify a built-in theme. Interests are visual
+preferences only. Security and Google steps have a Read more section below the fold.
+
+Work and personal account buttons use the existing Gmail linking flow. Skipping
+work email skips the secondary-account prompt. Verify that a Google return
+restores the correct step, shows the connected address, and allows continuation.
+Tools use the same Pipedream catalog and connection UI as Settings. Search, load
+more, cancel/retry connection, and confirm connected checks persist on return.
+Team setup retains existing membership, invite acceptance, domain suggestions,
+and editable invite recipients; submitting the form sends real invitations.
+
+The trial offer contains no card fields or wallet buttons. Its primary button
+requests an automatic 30-day Premium trial through Stripe Checkout; no coupon
+code is required. Stripe collects the payment method for billing after the trial.
+Only a customer's first subscription qualifies, including canceled subscriptions
+in that check. Ineligible trial requests show an error instead of opening an
+immediately paid checkout. Standard purchases retain their existing billing terms.
+Cancellation returns to this step. A successful return
+polls the server's license state, completes onboarding, and enters the app without
+an extra confirmation click. A pending webhook shows a retryable confirmation
+state. The Guest scroll cue opens a comparison with a separate Guest continuation.
+Both completion paths preserve an original `next` destination. Old saved email,
+connector, building, and summary step names are migrated on resume.
+
+## Public onboarding preview
+
+The standalone marketing development route `/onboarding-preview.html` continues
+from team setup to a final trial screen. The payment card starts with Apple Pay, Google Pay, and the card-number input,
+with no plan header or divider. The card scrolls internally at a maximum of
+360px or half the viewport height. Entering at least 15 digits in the local
+preview input reveals expiration, security code, country, and ZIP previews;
+clearing it hides them again. Use a test number such as `4242 4242 4242 4242`.
+The primary CTA reads `Start 30 day trial`, with the billing and cancellation
+note immediately below it. The quiet `Continue as Guest` scroll cue beneath it
+moves focus to the below-fold Guest and Pro comparison,
+using the same layout as the security details. The table includes email account
+limits, the email watermark, AI, storage, and calls. Each comparison column ends
+with its own compact CTA. `Continue as Guest`
+finishes the preview without a confirmation modal; `Continue with Pro` in the
+comparison returns to the payment section and its heading.
+Reduced-motion users scroll immediately. Wallet buttons only display a
+preview message. The card number stays in the input only and is never sent or
+saved; the remaining fields are display-only. Both plan
+continuation buttons finish the preview at the login URL; they do not purchase a
+subscription. Back returns to team setup. This payment mock remains preview-only; the authenticated flow instead opens
+Stripe Checkout as described above.
+
## Mailpit (local email)
- UI: `http://localhost:<mailpit-port>/`
diff --git a/docs/ANDROID_READINESS_AUDIT.md b/docs/ANDROID_READINESS_AUDIT.md
index 16cba022a6..359d4a1015 100644
--- a/docs/ANDROID_READINESS_AUDIT.md
+++ b/docs/ANDROID_READINESS_AUDIT.md
@@ -32,7 +32,7 @@ The pinned virtual-keyboard dependency (`70e8e8325b5ff7d681ef5f3b996ac083d4fc5a0
### 2. Implement Android authentication and connected-account handoff — P0, large
-**Confirmed:** [useSsoLogin.ts](../apps/web/src/features/auth/useSsoLogin.ts) uses the native callback/session redemption flow only for iOS. Android falls through to browser navigation and sets `original_url` to the WebView's local origin. [The navigation plugin](../apps/web/tauri/navigation_plugin/src/lib.rs) opens external destinations in the system browser, where that local origin does not return the user to the app. The same iOS-only split appears in [Gmail linking](../apps/web/src/lib/core/email-link/index.ts) and [GitHub onboarding](../apps/web/src/features/auth/mobile-onboarding/OnboardingConnectAccounts.tsx).
+**Confirmed:** [useSsoLogin.ts](../apps/web/src/features/auth/useSsoLogin.ts) uses the native callback/session redemption flow only for iOS. Android falls through to browser navigation and sets `original_url` to the WebView's local origin. [The navigation plugin](../apps/web/tauri/navigation_plugin/src/lib.rs) opens external destinations in the system browser, where that local origin does not return the user to the app. The same iOS-only split appears in [Gmail linking](../apps/web/src/lib/core/email-link/index.ts) and [GitHub onboarding](../apps/web/src/features/mobile-onboarding/OnboardingConnectAccounts.tsx).
**Do:** implement an Android browser/Custom Tabs authentication bridge with app callback delivery, cancellation, request correlation, and the existing one-time session-code exchange. Apply it consistently to every supported login provider, Gmail/calendar consent, account linking, and reauthentication. Reuse the backend session model; do not assume browser cookies automatically become native HTTP cookies. Keep intended destination/referral/onboarding state through the round trip and process recreation.
diff --git a/docs/FRONTEND_FEATURE_ARCHITECTURE.md b/docs/FRONTEND_FEATURE_ARCHITECTURE.md
index 2898a393b5..e83b2e6207 100644
--- a/docs/FRONTEND_FEATURE_ARCHITECTURE.md
+++ b/docs/FRONTEND_FEATURE_ARCHITECTURE.md
@@ -516,6 +516,13 @@ websocket import-time effects with `vi.mock`. Those are integration limitations;
feature data and capability behavior are supplied through the provider. Do not
turn those stubs into a pattern for replacing the feature logic under test.
+The same fakes make whole-feature browser tests possible without a backend.
+`features/onboarding` and `features/auth` keep an in-memory fake of their context
+in `tests/` and a `browser-test/` fixture. The fixture mounts the real views over
+that fake, with no module aliasing, and persists the fake in sessionStorage so
+OAuth and checkout round trips are real page loads. CI runs both suites on every
+web PR through `just test-signup-browser`.
+
For a frontend implementation change, run the relevant tests and checks from
`apps/web` with dependencies installed:
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index 7d540f08f5..1eba8567a8 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -33,6 +33,8 @@ files:
- apps/web/src/features/email-compose/components/**
- apps/web/src/features/changes/components/**
- apps/web/src/features/block-write/components/**
+ - apps/web/src/features/onboarding/components/**
+ - apps/web/src/features/auth/components/**
rule:
any:
- kind: string
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index e7c3942ffb..492150cc39 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -34,6 +34,8 @@ files:
- apps/web/src/features/email-compose/core/**
- apps/web/src/features/changes/core/**
- apps/web/src/features/block-write/core/**
+ - apps/web/src/features/onboarding/core/**
+ - apps/web/src/features/auth/core/**
rule:
kind: string
regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views|ui|component|context)(/|['"]))
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index c886b182f4..3199c25d74 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -52,6 +52,9 @@ files:
- apps/web/src/features/changes/primitives/**
- apps/web/src/features/block-write/queries/**
- apps/web/src/features/block-write/primitives/**
+ - apps/web/src/features/onboarding/primitives/**
+ - apps/web/src/features/auth/primitives/**
+ - apps/web/src/features/auth/queries/**
rule:
kind: string
regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views|ui|component)(/|['"]))
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index 2f088b534e..a7a59b32cd 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -97,6 +97,13 @@ files:
- apps/web/src/features/block-write/components/**
- apps/web/src/features/block-write/views/**
- apps/web/src/features/block-write/context/**
+ - apps/web/src/features/onboarding/primitives/**
+ - apps/web/src/features/onboarding/components/**
+ - apps/web/src/features/onboarding/views/**
+ - apps/web/src/features/auth/primitives/**
+ - apps/web/src/features/auth/components/**
+ - apps/web/src/features/auth/views/**
+ - apps/web/src/features/auth/queries/**
rule:
kind: string
regex: ^['"](@service-storage/graphql-soup|@core/context/user|@core/user|@property/hooks|@property/editor/hooks|@core/component/LexicalMarkdown/component/core/BlockLink|@app/lib/analytics/posthog)
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index ce9649d8b1..bc002968ff 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -33,6 +33,8 @@ files:
- apps/web/src/features/email-compose/components/**
- apps/web/src/features/changes/components/**
- apps/web/src/features/block-write/components/**
+ - apps/web/src/features/onboarding/components/**
+ - apps/web/src/features/auth/components/**
rule:
any:
- kind: string
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index cf7f532778..e3313a926a 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -34,6 +34,8 @@ files:
- apps/web/src/features/email-compose/core/**
- apps/web/src/features/changes/core/**
- apps/web/src/features/block-write/core/**
+ - apps/web/src/features/onboarding/core/**
+ - apps/web/src/features/auth/core/**
rule:
kind: string
regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views|ui|component|context)(/|['"]))
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index 4e2ca2dd7f..b340225271 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -52,6 +52,9 @@ files:
- apps/web/src/features/changes/primitives/**
- apps/web/src/features/block-write/queries/**
- apps/web/src/features/block-write/primitives/**
+ - apps/web/src/features/onboarding/primitives/**
+ - apps/web/src/features/auth/primitives/**
+ - apps/web/src/features/auth/queries/**
rule:
kind: string
regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views|ui|component)(/|['"]))
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index 8e4deb5695..3cd4666dc9 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -97,6 +97,13 @@ files:
- apps/web/src/features/block-write/components/**
- apps/web/src/features/block-write/views/**
- apps/web/src/features/block-write/context/**
+ - apps/web/src/features/onboarding/primitives/**
+ - apps/web/src/features/onboarding/components/**
+ - apps/web/src/features/onboarding/views/**
+ - apps/web/src/features/auth/primitives/**
+ - apps/web/src/features/auth/components/**
+ - apps/web/src/features/auth/views/**
+ - apps/web/src/features/auth/queries/**
rule:
kind: string
regex: ^['"](@service-storage/graphql-soup|@core/context/user|@core/user|@property/hooks|@property/editor/hooks|@core/component/LexicalMarkdown/component/core/BlockLink|@app/lib/analytics/posthog)
diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rs
index 4c6ebdf0f9..3fa38ee5ab 100644
--- a/services/authentication_service/src/api/context.rs
+++ b/services/authentication_service/src/api/context.rs
@@ -147,6 +147,13 @@ pub(crate) struct ApiContext {
pub codex_connection: Option<Arc<dyn codex_connection::domain::ConnectionService>>,
pub macro_cache_client: Arc<MacroCache>,
pub stripe_client: Arc<stripe::Client>,
+ pub subscription_checkout: Arc<
+ authentication_service::service::subscription_checkout::CheckoutService<
+ authentication_service::outbound::subscription_checkout::StripeCheckoutGateway<
+ GtmInviteServiceType,
+ >,
+ >,
+ >,
pub document_storage_service_client:
Arc<document_storage_service_client::DocumentStorageServiceClient>,
pub user_deletion:
diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rs
index f70e469af7..0b7d761c04 100644
--- a/services/authentication_service/src/api/swagger.rs
+++ b/services/authentication_service/src/api/swagger.rs
@@ -43,7 +43,9 @@ use crate::api::user::patch_user_onboarding::PatchUserOnboardingRequest;
use crate::api::user::post_get_names::PostGetNamesRequestBody;
use crate::api::user::post_get_names_with_email::GetNamesWithEmailRequestBody;
use crate::api::user::stripe::change_plan::{ChangePlanRequest, ChangePlanResponse};
-use crate::api::user::stripe::create_checkout_session_v2::CreateCheckoutSessionV2Request;
+use crate::api::user::stripe::create_checkout_session_v2::{
+ CheckoutSessionV2Response, CreateCheckoutSessionV2Request,
+};
use crate::api::user::stripe::create_portal_session::CreatePortalSessionRequest;
use crate::api::user::stripe::{PaidPlan, StripeSessionResponse};
use crate::api::{
@@ -271,6 +273,7 @@ use model::user::{
// Stripe
CreateCheckoutSessionV2Request,
+ CheckoutSessionV2Response,
CreatePortalSessionRequest,
StripeSessionResponse,
diff --git a/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs b/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
index a5f65f6c01..825dc13666 100644
--- a/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
+++ b/services/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
@@ -1,14 +1,13 @@
+use authentication_service::service::subscription_checkout::CheckoutRequest;
use axum::{Json, extract::State};
use entity_access::domain::models::OwnerTeamRole;
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::OptionalMacroUserTeamExtractorV2;
-use gtm_invite::domain::ports::GtmInviteService;
use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
-use macro_user_id::user_id::MacroUserIdStr;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
-use super::{PaidPlan, StripeOperationError, StripeSessionResponse};
+use super::{PaidPlan, StripeOperationError};
use crate::api::context::{ApiContext, AuthorizationService};
use model::response::ErrorResponse;
@@ -40,6 +39,19 @@ pub struct CreateCheckoutSessionV2Request {
/// The plan to subscribe to. Defaults to Premium.
#[serde(default)]
pub plan: Option<PaidPlan>,
+ /// Request the automatic, first-subscription 30-day Premium trial.
+ #[serde(default)]
+ pub onboarding_trial: bool,
+}
+
+/// Hosted checkout with the billing terms the server actually granted.
+#[derive(Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CheckoutSessionV2Response {
+ /// The opaque URL returned by Stripe.
+ pub url: String,
+ /// Trial duration, absent for an immediately paid checkout.
+ pub trial_days: Option<u8>,
}
/// Creates a Stripe checkout session for the user to subscribe.
@@ -49,7 +61,7 @@ pub struct CreateCheckoutSessionV2Request {
operation_id = "create_checkout_session_v2",
request_body = CreateCheckoutSessionV2Request,
responses(
- (status = 200, body = StripeSessionResponse),
+ (status = 200, body = CheckoutSessionV2Response),
(status = 400, body = ErrorResponse),
(status = 404, body = ErrorResponse),
(status = 409, body = ErrorResponse),
@@ -62,78 +74,7 @@ pub async fn create_checkout_session<Eas: EntityAccessService>(
user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
optional_team: OptionalMacroUserTeamExtractorV2<OwnerTeamRole, Eas, AuthorizationService>,
Json(req): Json<CreateCheckoutSessionV2Request>,
-) -> Result<Json<StripeSessionResponse>, StripeOperationError> {
- let plan = req.plan.unwrap_or(PaidPlan::Premium);
- let price_id = ctx.stripe_prices.price_id(plan)?.to_string();
-
- // Get the stripe customer ID from the database
- let stripe_customer_id = macro_db_client::user::get::get_stripe_customer_id_by_user_id(
- &ctx.db,
- &user.authorization.user.macro_user_id,
- )
- .await?
- .ok_or(StripeOperationError::MissingStripeId)?;
-
- let customer_id: stripe::CustomerId = stripe_customer_id.parse()?;
-
- // Check if user already has an active subscription
- let mut list_subscriptions = stripe::ListSubscriptions::new();
- list_subscriptions.customer = Some(customer_id.clone());
- list_subscriptions.limit = Some(10);
-
- let subscriptions = stripe::Subscription::list(&ctx.stripe_client, &list_subscriptions).await?;
-
- let has_active_subscription = subscriptions.data.iter().any(|sub| {
- matches!(
- sub.status,
- stripe::SubscriptionStatus::Active | stripe::SubscriptionStatus::Trialing
- )
- });
-
- if has_active_subscription {
- tracing::warn!(
- customer_id = %customer_id,
- "User attempted to create checkout session but already has an active subscription"
- );
- return Err(StripeOperationError::AlreadySubscribed);
- }
-
- // An explicit discount code is authoritative and must exist. Without one,
- // an account that signed up through a GTM invite link gets the link's
- // promotion applied for it — best-effort, so a code that went missing in
- // Stripe degrades to a regular checkout instead of blocking it.
- let promo_code_id = match req.discount.as_deref() {
- Some(discount) => Some(
- find_active_promotion_code(&ctx.stripe_client, discount)
- .await?
- .ok_or(StripeOperationError::PromoCodeNotFound)?,
- ),
- None => match gtm_invite_promo_code(&ctx, &user.authorization.user.macro_user_id).await {
- Some(code) => match find_active_promotion_code(&ctx.stripe_client, &code).await {
- Ok(Some(id)) => {
- tracing::info!(promo_code = %code, "applying GTM invite promotion to checkout");
- Some(id)
- }
- Ok(None) => {
- tracing::error!(
- promo_code = %code,
- "GTM invite promotion code is not active in Stripe; checking out without it"
- );
- None
- }
- Err(e) => {
- tracing::error!(
- error=?e,
- promo_code = %code,
- "failed to look up GTM invite promotion code; checking out without it"
- );
- None
- }
- },
- None => None,
- },
- };
-
+) -> Result<Json<CheckoutSessionV2Response>, StripeOperationError> {
// Build subscription metadata from optional tracking fields
let mut metadata = std::collections::HashMap::new();
@@ -158,71 +99,20 @@ pub async fn create_checkout_session<Eas: EntityAccessService>(
metadata.insert("fbc".to_string(), fbc);
}
- // Only set subscription_data if we have metadata to include
- let subscription_data =
- (!metadata.is_empty()).then_some(stripe::CreateCheckoutSessionSubscriptionData {
- metadata: Some(metadata),
- ..Default::default()
- });
-
- // Create the checkout session
- let params = stripe::CreateCheckoutSession {
- customer: Some(customer_id),
- mode: Some(stripe::CheckoutSessionMode::Subscription),
- success_url: Some(req.success_url.as_str()),
- cancel_url: Some(req.cancel_url.as_str()),
- allow_promotion_codes: promo_code_id.is_none().then_some(true),
- discounts: promo_code_id.map(|id| {
- vec![stripe::CreateCheckoutSessionDiscounts {
- promotion_code: Some(id.to_string()),
- ..Default::default()
- }]
- }),
- line_items: Some(vec![stripe::CreateCheckoutSessionLineItems {
- price: Some(price_id.to_string()),
- quantity: Some(1),
- ..Default::default()
- }]),
- subscription_data,
- ..Default::default()
- };
-
- let session = stripe::CheckoutSession::create(&ctx.stripe_client, params).await?;
-
- let url = session
- .url
- .ok_or(StripeOperationError::UnexpectedStripeResponse)?;
-
- // Validate but return the exact URL Stripe gave us — session URLs are signed/opaque
- // and `Url::parse(...).to_string()` can normalize in ways that break the signature.
- url::Url::parse(&url).map_err(|_| StripeOperationError::UnexpectedStripeResponse)?;
-
- Ok(Json(StripeSessionResponse { url }))
-}
-
-/// Finds the active Stripe promotion code customers redeem as `code`.
-async fn find_active_promotion_code(
- stripe_client: &stripe::Client,
- code: &str,
-) -> Result<Option<stripe::PromotionCodeId>, stripe::StripeError> {
- let mut list_params = stripe::ListPromotionCodes::new();
- list_params.code = Some(code);
- list_params.active = Some(true);
- list_params.limit = Some(1);
-
- let promo_codes = stripe::PromotionCode::list(stripe_client, &list_params).await?;
-
- Ok(promo_codes.data.into_iter().next().map(|promo| promo.id))
-}
-
-/// The promotion code an account holds from a redeemed GTM invite link, if any.
-async fn gtm_invite_promo_code(ctx: &ApiContext, user_id: &MacroUserIdStr<'_>) -> Option<String> {
- match ctx.gtm_invite_service.active_offer_for_user(user_id).await {
- Ok(Some(link)) => Some(link.promo_code.to_string()),
- Ok(None) => None,
- Err(e) => {
- tracing::error!(error=?e, "failed to look up GTM invite offer for checkout");
- None
- }
- }
+ let checkout = ctx
+ .subscription_checkout
+ .create(CheckoutRequest {
+ user_id: user.authorization.user.macro_user_id.clone(),
+ plan: req.plan.unwrap_or(PaidPlan::Premium),
+ onboarding_trial: req.onboarding_trial,
+ success_url: req.success_url,
+ cancel_url: req.cancel_url,
+ discount: req.discount,
+ metadata,
+ })
+ .await?;
+ Ok(Json(CheckoutSessionV2Response {
+ url: checkout.url,
+ trial_days: checkout.trial_days,
+ }))
}
diff --git a/services/authentication_service/src/api/user/stripe/shared.rs b/services/authentication_service/src/api/user/stripe/shared.rs
index 4d5005da7f..0022044c4f 100644
--- a/services/authentication_service/src/api/user/stripe/shared.rs
+++ b/services/authentication_service/src/api/user/stripe/shared.rs
@@ -1,3 +1,7 @@
+use authentication_service::{
+ outbound::subscription_checkout::StripeCheckoutError,
+ service::subscription_checkout::CheckoutError,
+};
use axum::{
Json,
http::StatusCode,
@@ -81,6 +85,10 @@ pub enum StripeOperationError {
PromoCodeNotFound,
#[error("Internal server error")]
UnexpectedStripeResponse,
+ #[error("The 30-day trial is only available for your first Premium subscription")]
+ TrialUnavailable,
+ #[error("Could not create checkout")]
+ CheckoutGateway(StripeCheckoutError),
#[error("User already has an active subscription")]
AlreadySubscribed,
#[error("Teams service error")]
@@ -115,6 +123,8 @@ impl IntoResponse for StripeOperationError {
StripeOperationError::PromoCodeNotFound => StatusCode::NOT_FOUND,
StripeOperationError::UnexpectedStripeResponse => StatusCode::INTERNAL_SERVER_ERROR,
StripeOperationError::AlreadySubscribed => StatusCode::CONFLICT,
+ StripeOperationError::TrialUnavailable => StatusCode::CONFLICT,
+ StripeOperationError::CheckoutGateway(_) => StatusCode::INTERNAL_SERVER_ERROR,
StripeOperationError::TeamsErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
StripeOperationError::RolesErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
StripeOperationError::PlanUnavailable => StatusCode::BAD_REQUEST,
@@ -152,3 +162,16 @@ pub struct StripeSessionResponse {
#[cfg(test)]
mod test;
+
+impl From<CheckoutError<StripeCheckoutError>> for StripeOperationError {
+ fn from(error: CheckoutError<StripeCheckoutError>) -> Self {
+ match error {
+ CheckoutError::MissingCustomer => Self::MissingStripeId,
+ CheckoutError::AlreadySubscribed => Self::AlreadySubscribed,
+ CheckoutError::TrialUnavailable => Self::TrialUnavailable,
+ CheckoutError::PlanUnavailable => Self::PlanUnavailable,
+ CheckoutError::PromoCodeNotFound => Self::PromoCodeNotFound,
+ CheckoutError::Gateway(error) => Self::CheckoutGateway(error),
+ }
+ }
+}
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index 64079d8700..a3ac2a23a7 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -506,6 +506,17 @@ async fn main() -> anyhow::Result<()> {
};
let stripe_client = Arc::new(stripe_client);
+ let gtm_invite_service = Arc::new(gtm_invite_service);
+ let subscription_checkout = Arc::new(
+ authentication_service::service::subscription_checkout::CheckoutService::new(
+ authentication_service::outbound::subscription_checkout::StripeCheckoutGateway::new(
+ db.clone(),
+ stripe_client.clone(),
+ gtm_invite_service.clone(),
+ stripe_prices.seat_prices(),
+ ),
+ ),
+ );
let ai_payment_gateway = ai_billing::outbound::StripePaymentGateway::new(stripe_client.clone());
let ai_pricing = config.ai_pricing();
let ai_billing_service = Arc::new(
@@ -562,6 +573,7 @@ async fn main() -> anyhow::Result<()> {
codex_connection,
macro_cache_client: Arc::new(macro_cache_client),
stripe_client,
+ subscription_checkout,
document_storage_service_client,
user_deletion,
email_service_client: Arc::new(email_service_client),
@@ -591,7 +603,7 @@ async fn main() -> anyhow::Result<()> {
favorites_service: Arc::new(favorites_service),
entity_access_service: entity_access_service_impl,
referral_service: Arc::new(referral_service),
- gtm_invite_service: Arc::new(gtm_invite_service),
+ gtm_invite_service,
native_app_service: Arc::new(NativeAppServiceImpl {
bundle_fetcher: DefaultBundleFetcher::new(
AppServiceUrl::new_for_environment(config.environment)
diff --git a/services/authentication_service/src/outbound.rs b/services/authentication_service/src/outbound.rs
index 00007625a4..34496650e6 100644
--- a/services/authentication_service/src/outbound.rs
+++ b/services/authentication_service/src/outbound.rs
@@ -1,3 +1,4 @@
//! Adapters for authentication service use cases.
+pub mod subscription_checkout;
pub mod user_deletion;
diff --git a/services/authentication_service/src/outbound/subscription_checkout.rs b/services/authentication_service/src/outbound/subscription_checkout.rs
new file mode 100644
index 0000000000..0831c5240a
--- /dev/null
+++ b/services/authentication_service/src/outbound/subscription_checkout.rs
@@ -0,0 +1,305 @@
+//! Checkout persistence and Stripe wire-format adapter.
+
+use std::sync::Arc;
+
+use gtm_invite::domain::{models::GtmInviteError, ports::GtmInviteService};
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+use teams::domain::model::{CustomerError, SeatPrices};
+use thiserror::Error;
+
+use crate::service::subscription_checkout::{
+ CheckoutGateway, CheckoutRequest, CheckoutTerms, ONBOARDING_TRIAL_DAYS, SubscriptionHistory,
+};
+
+const TRIAL_SESSION_MARKER: &str = "onboarding_trial";
+
+enum TrialSessionAttempt {
+ Reuse(String),
+ Create(String),
+}
+
+#[cfg(test)]
+mod test;
+
+/// Provider and persistence errors retained for logging at the HTTP boundary.
+#[derive(Debug, Error)]
+pub enum StripeCheckoutError {
+ /// Customer lookup failed.
+ #[error(transparent)]
+ Database(#[from] sqlx::Error),
+ /// Stripe rejected or could not process the request.
+ #[error(transparent)]
+ Stripe(#[from] stripe::StripeError),
+ /// Persisted customer identity was malformed.
+ #[error(transparent)]
+ CustomerId(#[from] stripe::ParseIdError),
+ /// The invite domain could not read an offer.
+ #[error(transparent)]
+ Invite(#[from] GtmInviteError),
+ /// A configured price is unavailable.
+ #[error(transparent)]
+ Price(#[from] CustomerError),
+ /// Stripe returned an invalid URL.
+ #[error(transparent)]
+ Url(#[from] url::ParseError),
+ /// Stripe omitted data needed to complete the operation safely.
+ #[error("Unexpected Stripe response")]
+ UnexpectedResponse,
+}
+
+/// Concrete capabilities composed at authentication-service startup.
+pub struct StripeCheckoutGateway<I> {
+ db: PgPool,
+ stripe: Arc<stripe::Client>,
+ invites: Arc<I>,
+ prices: SeatPrices,
+}
+
+impl<I> StripeCheckoutGateway<I> {
+ /// Bind existing customer storage, invite service, prices, and Stripe client.
+ pub fn new(
+ db: PgPool,
+ stripe: Arc<stripe::Client>,
+ invites: Arc<I>,
+ prices: SeatPrices,
+ ) -> Self {
+ Self {
+ db,
+ stripe,
+ invites,
+ prices,
+ }
+ }
+
+ // Reuse an open attempt. Anchor Stripe's idempotency key to the previous
+ // expired attempt so concurrent tabs cannot stockpile usable trial links,
+ // while an abandoned/expired checkout remains retryable.
+ async fn trial_attempt(
+ &self,
+ customer: &stripe::CustomerId,
+ request: &CheckoutRequest<'_>,
+ ) -> Result<TrialSessionAttempt, StripeCheckoutError> {
+ let mut params = stripe::ListCheckoutSessions::new();
+ params.customer = Some(customer.clone());
+ params.limit = Some(100);
+ loop {
+ let page = stripe::CheckoutSession::list(&self.stripe, &params).await?;
+ if let Some(session) = page.data.iter().find(|session| {
+ session
+ .metadata
+ .as_ref()
+ .is_some_and(|metadata| metadata.contains_key(TRIAL_SESSION_MARKER))
+ }) {
+ return match session.status {
+ Some(stripe::CheckoutSessionStatus::Open)
+ if trial_session_matches(session, request) =>
+ {
+ Ok(TrialSessionAttempt::Reuse(
+ session
+ .url
+ .clone()
+ .ok_or(StripeCheckoutError::UnexpectedResponse)?,
+ ))
+ }
+ Some(stripe::CheckoutSessionStatus::Open) => {
+ // A changed team or return destination needs fresh metadata.
+ stripe::CheckoutSession::expire(&self.stripe, &session.id).await?;
+ Ok(TrialSessionAttempt::Create(format!(
+ "onboarding-trial-{customer}-after-{}",
+ session.id
+ )))
+ }
+ Some(stripe::CheckoutSessionStatus::Expired) => {
+ Ok(TrialSessionAttempt::Create(format!(
+ "onboarding-trial-{customer}-after-{}",
+ session.id
+ )))
+ }
+ // The customer finished checkout between history lookup and
+ // this read. Do not create a second subscription in that race.
+ _ => Err(StripeCheckoutError::UnexpectedResponse),
+ };
+ }
+ if !page.has_more {
+ break;
+ }
+ params.starting_after = Some(
+ page.data
+ .last()
+ .ok_or(StripeCheckoutError::UnexpectedResponse)?
+ .id
+ .clone(),
+ );
+ }
+ Ok(TrialSessionAttempt::Create(format!(
+ "onboarding-trial-{customer}-first"
+ )))
+ }
+}
+
+impl<I: GtmInviteService> CheckoutGateway for StripeCheckoutGateway<I> {
+ type Customer = stripe::CustomerId;
+ type Promotion = stripe::PromotionCodeId;
+ type Error = StripeCheckoutError;
+
+ async fn customer(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<Self::Customer>, Self::Error> {
+ macro_db_client::user::get::get_stripe_customer_id_by_user_id(&self.db, user)
+ .await?
+ .map(|id| id.parse().map_err(StripeCheckoutError::from))
+ .transpose()
+ }
+
+ async fn history(&self, customer: &Self::Customer) -> Result<SubscriptionHistory, Self::Error> {
+ subscription_history(&self.stripe, customer).await
+ }
+
+ async fn invite_promotion(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<String>, Self::Error> {
+ Ok(self
+ .invites
+ .active_offer_for_user(user)
+ .await?
+ .map(|link| link.promo_code.to_string()))
+ }
+
+ async fn promotion(&self, code: &str) -> Result<Option<Self::Promotion>, Self::Error> {
+ let mut params = stripe::ListPromotionCodes::new();
+ params.code = Some(code);
+ params.active = Some(true);
+ params.limit = Some(1);
+ Ok(stripe::PromotionCode::list(&self.stripe, &params)
+ .await?
+ .data
+ .into_iter()
+ .next()
+ .map(|promo| promo.id))
+ }
+
+ async fn create_session(
+ &self,
+ customer: Self::Customer,
+ request: CheckoutRequest<'_>,
+ terms: CheckoutTerms,
+ promotion: Option<Self::Promotion>,
+ ) -> Result<String, Self::Error> {
+ let stripe = match terms {
+ CheckoutTerms::Paid => self.stripe.as_ref().clone(),
+ CheckoutTerms::Trial => match self.trial_attempt(&customer, &request).await? {
+ TrialSessionAttempt::Reuse(url) => {
+ url::Url::parse(&url)?;
+ return Ok(url);
+ }
+ TrialSessionAttempt::Create(key) => self
+ .stripe
+ .as_ref()
+ .clone()
+ .with_strategy(stripe::RequestStrategy::Idempotent(key)),
+ },
+ };
+ let params = checkout_params(
+ customer,
+ &request,
+ self.prices.price_id(request.plan)?,
+ terms,
+ promotion,
+ );
+ let session = stripe::CheckoutSession::create(&stripe, params).await?;
+ let url = session.url.ok_or(StripeCheckoutError::UnexpectedResponse)?;
+ // Preserve the exact signed/opaque URL returned by Stripe.
+ url::Url::parse(&url)?;
+ Ok(url)
+ }
+}
+
+fn checkout_params<'a>(
+ customer: stripe::CustomerId,
+ request: &'a CheckoutRequest<'_>,
+ price: &str,
+ terms: CheckoutTerms,
+ promotion: Option<stripe::PromotionCodeId>,
+) -> stripe::CreateCheckoutSession<'a> {
+ let trial = terms == CheckoutTerms::Trial;
+ stripe::CreateCheckoutSession {
+ customer: Some(customer),
+ mode: Some(stripe::CheckoutSessionMode::Subscription),
+ success_url: Some(&request.success_url),
+ cancel_url: Some(&request.cancel_url),
+ payment_method_collection: Some(stripe::CheckoutSessionPaymentMethodCollection::Always),
+ metadata: trial.then(|| {
+ let mut metadata = request.metadata.clone();
+ metadata.insert(
+ TRIAL_SESSION_MARKER.to_owned(),
+ ONBOARDING_TRIAL_DAYS.to_string(),
+ );
+ metadata
+ }),
+ allow_promotion_codes: (!trial && promotion.is_none()).then_some(true),
+ discounts: promotion.map(|id| {
+ vec![stripe::CreateCheckoutSessionDiscounts {
+ promotion_code: Some(id.to_string()),
+ ..Default::default()
+ }]
+ }),
+ line_items: Some(vec![stripe::CreateCheckoutSessionLineItems {
+ price: Some(price.to_owned()),
+ quantity: Some(1),
+ ..Default::default()
+ }]),
+ subscription_data: Some(stripe::CreateCheckoutSessionSubscriptionData {
+ metadata: (!request.metadata.is_empty()).then(|| request.metadata.clone()),
+ trial_period_days: trial.then_some(u32::from(ONBOARDING_TRIAL_DAYS)),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }
+}
+
+fn trial_session_matches(session: &stripe::CheckoutSession, request: &CheckoutRequest<'_>) -> bool {
+ session.success_url.as_deref() == Some(request.success_url.as_str())
+ && session.cancel_url.as_deref() == Some(request.cancel_url.as_str())
+ && ["team_id", "owner_id"].iter().all(|key| {
+ session
+ .metadata
+ .as_ref()
+ .and_then(|metadata| metadata.get(*key))
+ == request.metadata.get(*key)
+ })
+}
+
+async fn subscription_history(
+ stripe_client: &stripe::Client,
+ customer: &stripe::CustomerId,
+) -> Result<SubscriptionHistory, StripeCheckoutError> {
+ let mut params = stripe::ListSubscriptions::new();
+ params.customer = Some(customer.clone());
+ params.status = Some(stripe::SubscriptionStatusFilter::All);
+ params.limit = Some(100);
+ let mut history = SubscriptionHistory::default();
+ loop {
+ let page = stripe::Subscription::list(stripe_client, &params).await?;
+ history.has_previous_subscription |= !page.data.is_empty();
+ history.has_active_subscription |= page.data.iter().any(|sub| {
+ matches!(
+ sub.status,
+ stripe::SubscriptionStatus::Active | stripe::SubscriptionStatus::Trialing
+ )
+ });
+ if !page.has_more {
+ break;
+ }
+ params.starting_after = Some(
+ page.data
+ .last()
+ .ok_or(StripeCheckoutError::UnexpectedResponse)?
+ .id
+ .clone(),
+ );
+ }
+ Ok(history)
+}
diff --git a/services/authentication_service/src/outbound/subscription_checkout/test.rs b/services/authentication_service/src/outbound/subscription_checkout/test.rs
new file mode 100644
index 0000000000..f2af015233
--- /dev/null
+++ b/services/authentication_service/src/outbound/subscription_checkout/test.rs
@@ -0,0 +1,313 @@
+use super::*;
+use axum::{
+ Json, Router,
+ extract::{Request, State},
+};
+use std::collections::HashMap;
+use std::{collections::VecDeque, sync::Mutex};
+use teams::domain::model::SeatPlan;
+
+fn request() -> CheckoutRequest<'static> {
+ CheckoutRequest {
+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ plan: SeatPlan::Premium,
+ onboarding_trial: true,
+ success_url: "https://macro.com/app/onboarding?subscriptionSuccess=true".into(),
+ cancel_url: "https://macro.com/app/onboarding?subscriptionCancel=true".into(),
+ discount: None,
+ metadata: HashMap::new(),
+ }
+}
+
+#[test]
+fn trial_payload_requires_no_coupon_and_works_without_metadata() {
+ let input = request();
+ let params = checkout_params(
+ "cus_test".parse().unwrap(),
+ &input,
+ "price_premium",
+ CheckoutTerms::Trial,
+ None,
+ );
+ let json = serde_json::to_value(params).unwrap();
+ assert_eq!(json["customer"], "cus_test");
+ assert_eq!(json["subscription_data"]["trial_period_days"], 30);
+ assert_eq!(json["payment_method_collection"], "always");
+ assert_eq!(json["metadata"][TRIAL_SESSION_MARKER], "30");
+ assert!(
+ json.get("allow_promotion_codes")
+ .is_none_or(serde_json::Value::is_null)
+ );
+ assert!(json.get("discounts").is_none_or(serde_json::Value::is_null));
+ assert_eq!(json["line_items"][0]["price"], "price_premium");
+ assert_eq!(json["line_items"][0]["quantity"], 1);
+ assert_eq!(json["success_url"], input.success_url);
+ assert_eq!(json["cancel_url"], input.cancel_url);
+}
+
+#[test]
+fn an_open_trial_is_reused_only_for_the_same_team_and_return_destinations() {
+ let mut input = request();
+ input.metadata.insert("team_id".into(), "team-first".into());
+ let session = stripe::CheckoutSession {
+ success_url: Some(input.success_url.clone()),
+ cancel_url: Some(input.cancel_url.clone()),
+ metadata: Some(input.metadata.clone()),
+ ..Default::default()
+ };
+ assert!(trial_session_matches(&session, &input));
+ input
+ .metadata
+ .insert("team_id".into(), "team-second".into());
+ assert!(!trial_session_matches(&session, &input));
+ input.metadata.insert("team_id".into(), "team-first".into());
+ input.success_url = "https://dev.macro.com/app/onboarding?subscriptionSuccess=true".into();
+ assert!(!trial_session_matches(&session, &input));
+}
+
+#[test]
+fn trial_keeps_team_and_conversion_metadata() {
+ let mut input = request();
+ input.metadata.insert("team_id".into(), "team-test".into());
+ input
+ .metadata
+ .insert("owner_id".into(), "macro|[email protected]".into());
+ input
+ .metadata
+ .insert("ga_client_id".into(), "test-client".into());
+ let params = checkout_params(
+ "cus_test".parse().unwrap(),
+ &input,
+ "price_premium",
+ CheckoutTerms::Trial,
+ None,
+ );
+ let json = serde_json::to_value(params).unwrap();
+ assert_eq!(json["subscription_data"]["trial_period_days"], 30);
+ assert_eq!(
+ json["subscription_data"]["metadata"]["team_id"],
+ "team-test"
+ );
+ assert_eq!(
+ json["subscription_data"]["metadata"]["ga_client_id"],
+ "test-client"
+ );
+}
+
+#[test]
+fn ordinary_paid_checkout_does_not_acquire_a_trial() {
+ let input = request();
+ let params = checkout_params(
+ "cus_test".parse().unwrap(),
+ &input,
+ "price_premium",
+ CheckoutTerms::Paid,
+ None,
+ );
+ let json = serde_json::to_value(params).unwrap();
+ assert!(
+ json["subscription_data"]
+ .get("trial_period_days")
+ .is_none_or(serde_json::Value::is_null)
+ );
+ assert_eq!(json["allow_promotion_codes"], true);
+}
+
+#[derive(Clone)]
+struct StripeStub {
+ responses: Arc<Mutex<VecDeque<serde_json::Value>>>,
+ requests: Arc<Mutex<Vec<String>>>,
+}
+
+async fn respond(State(stub): State<StripeStub>, request: Request) -> Json<serde_json::Value> {
+ stub.requests
+ .lock()
+ .unwrap()
+ .push(format!("{} {}", request.method(), request.uri()));
+ Json(
+ stub.responses
+ .lock()
+ .unwrap()
+ .pop_front()
+ .expect("unexpected Stripe request"),
+ )
+}
+
+async fn stub_gateway(
+ responses: Vec<serde_json::Value>,
+) -> (
+ StripeCheckoutGateway<()>,
+ StripeStub,
+ tokio::task::JoinHandle<()>,
+) {
+ let stub = StripeStub {
+ responses: Arc::new(Mutex::new(responses.into())),
+ requests: Arc::new(Mutex::new(Vec::new())),
+ };
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/", listener.local_addr().unwrap());
+ let app = Router::new().fallback(respond).with_state(stub.clone());
+ let task = tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ let gateway = StripeCheckoutGateway::new(
+ sqlx::postgres::PgPoolOptions::new()
+ .connect_lazy("postgres://unused:unused@localhost/unused")
+ .unwrap(),
+ Arc::new(stripe::Client::from_url(url.as_str(), "sk_test_fixture")),
+ Arc::new(()),
+ SeatPrices {
+ premium: "price_test".into(),
+ max: None,
+ },
+ );
+ (gateway, stub, task)
+}
+
+fn existing_session(status: stripe::CheckoutSessionStatus) -> stripe::CheckoutSession {
+ let input = request();
+ stripe::CheckoutSession {
+ id: "cs_test_existing".parse().unwrap(),
+ status: Some(status),
+ url: Some("https://checkout.stripe.com/existing".into()),
+ success_url: Some(input.success_url),
+ cancel_url: Some(input.cancel_url),
+ metadata: Some([(TRIAL_SESSION_MARKER.into(), "30".into())].into()),
+ ..Default::default()
+ }
+}
+
+fn page(sessions: Vec<stripe::CheckoutSession>, more: bool) -> serde_json::Value {
+ serde_json::json!({"object": "list", "url": "/v1/checkout/sessions", "data": sessions, "has_more": more})
+}
+
+#[tokio::test]
+async fn reopening_checkout_reuses_the_existing_trial_link() {
+ let (gateway, stub, task) = stub_gateway(vec![page(
+ vec![existing_session(stripe::CheckoutSessionStatus::Open)],
+ false,
+ )])
+ .await;
+ let attempt = gateway
+ .trial_attempt(&"cus_test".parse().unwrap(), &request())
+ .await
+ .unwrap();
+ task.abort();
+ assert!(
+ matches!(attempt, TrialSessionAttempt::Reuse(url) if url == "https://checkout.stripe.com/existing")
+ );
+ assert_eq!(stub.requests.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn expired_checkout_has_a_stable_new_idempotency_key() {
+ let (gateway, _, task) = stub_gateway(vec![page(
+ vec![existing_session(stripe::CheckoutSessionStatus::Expired)],
+ false,
+ )])
+ .await;
+ let attempt = gateway
+ .trial_attempt(&"cus_test".parse().unwrap(), &request())
+ .await
+ .unwrap();
+ task.abort();
+ assert!(
+ matches!(attempt, TrialSessionAttempt::Create(key) if key == "onboarding-trial-cus_test-after-cs_test_existing")
+ );
+}
+
+#[tokio::test]
+async fn checkout_completed_during_history_lookup_cannot_be_created_again() {
+ let (gateway, _, task) = stub_gateway(vec![page(
+ vec![existing_session(stripe::CheckoutSessionStatus::Complete)],
+ false,
+ )])
+ .await;
+ let attempt = gateway
+ .trial_attempt(&"cus_test".parse().unwrap(), &request())
+ .await;
+ task.abort();
+ assert!(matches!(
+ attempt,
+ Err(StripeCheckoutError::UnexpectedResponse)
+ ));
+}
+
+#[tokio::test]
+async fn changed_team_expires_the_old_trial_before_creating_another() {
+ let session = existing_session(stripe::CheckoutSessionStatus::Open);
+ let expired = existing_session(stripe::CheckoutSessionStatus::Expired);
+ let (gateway, stub, task) = stub_gateway(vec![
+ page(vec![session], false),
+ serde_json::to_value(expired).unwrap(),
+ ])
+ .await;
+ let mut input = request();
+ input.metadata.insert("team_id".into(), "new-team".into());
+ let attempt = gateway
+ .trial_attempt(&"cus_test".parse().unwrap(), &input)
+ .await
+ .unwrap();
+ task.abort();
+ assert!(matches!(attempt, TrialSessionAttempt::Create(_)));
+ assert_eq!(
+ stub.requests.lock().unwrap()[1],
+ "POST /v1/checkout/sessions/cs_test_existing/expire"
+ );
+}
+
+#[tokio::test]
+async fn trial_lookup_reads_past_a_page_of_unrelated_checkouts() {
+ let unrelated = stripe::CheckoutSession {
+ id: "cs_test_unrelated".parse().unwrap(),
+ ..Default::default()
+ };
+ let (gateway, stub, task) = stub_gateway(vec![
+ page(vec![unrelated], true),
+ page(
+ vec![existing_session(stripe::CheckoutSessionStatus::Open)],
+ false,
+ ),
+ ])
+ .await;
+ let attempt = gateway
+ .trial_attempt(&"cus_test".parse().unwrap(), &request())
+ .await
+ .unwrap();
+ task.abort();
+ assert!(matches!(attempt, TrialSessionAttempt::Reuse(_)));
+ assert!(stub.requests.lock().unwrap()[1].contains("starting_after=cs_test_unrelated"));
+}
+
+#[tokio::test]
+async fn history_includes_canceled_subscriptions_and_every_page() {
+ let canceled = stripe::Subscription {
+ id: "sub_canceled".parse().unwrap(),
+ customer: stripe::Expandable::Id("cus_test".parse().unwrap()),
+ status: stripe::SubscriptionStatus::Canceled,
+ ..Default::default()
+ };
+ let trial = stripe::Subscription {
+ id: "sub_trial".parse().unwrap(),
+ customer: stripe::Expandable::Id("cus_test".parse().unwrap()),
+ status: stripe::SubscriptionStatus::Trialing,
+ ..Default::default()
+ };
+ let (gateway, stub, task) = stub_gateway(vec![
+ serde_json::json!({"object":"list", "url":"/v1/subscriptions", "data":[canceled], "has_more":true}),
+ serde_json::json!({"object":"list", "url":"/v1/subscriptions", "data":[trial], "has_more":false}),
+ ]).await;
+ let history = subscription_history(&gateway.stripe, &"cus_test".parse().unwrap())
+ .await
+ .unwrap();
+ task.abort();
+ assert!(history.has_previous_subscription);
+ assert!(history.has_active_subscription);
+ let requests = stub.requests.lock().unwrap();
+ assert!(
+ requests
+ .iter()
+ .all(|request| request.contains("status=all"))
+ );
+ assert!(requests[1].contains("starting_after=sub_canceled"));
+}
diff --git a/services/authentication_service/src/service/mod.rs b/services/authentication_service/src/service/mod.rs
index e8dcd1a633..513dd9b2e5 100644
--- a/services/authentication_service/src/service/mod.rs
+++ b/services/authentication_service/src/service/mod.rs
@@ -1,2 +1,3 @@
pub mod signup_policy;
+pub mod subscription_checkout;
pub mod user;
diff --git a/services/authentication_service/src/service/subscription_checkout.rs b/services/authentication_service/src/service/subscription_checkout.rs
new file mode 100644
index 0000000000..2bb8275a67
--- /dev/null
+++ b/services/authentication_service/src/service/subscription_checkout.rs
@@ -0,0 +1,205 @@
+//! Subscription checkout policy, independent of HTTP and the payment provider.
+
+use std::{collections::HashMap, future::Future};
+
+use macro_user_id::user_id::MacroUserIdStr;
+use teams::domain::model::SeatPlan;
+use thiserror::Error;
+
+#[cfg(test)]
+mod test;
+
+/// The introductory offer is granted by the server, never supplied as a duration by clients.
+pub const ONBOARDING_TRIAL_DAYS: u8 = 30;
+
+/// Facts across the customer's entire subscription history, including canceled subscriptions.
+#[derive(Debug, Default, Clone, Copy)]
+pub struct SubscriptionHistory {
+ /// An active subscription already owns the customer's paid access.
+ pub has_active_subscription: bool,
+ /// Any previous subscription makes the customer ineligible for an introductory trial.
+ pub has_previous_subscription: bool,
+}
+
+/// Authenticated purchase intent; the caller cannot choose a customer or price ID.
+pub struct CheckoutRequest<'a> {
+ /// Identity established by the authentication boundary.
+ pub user_id: MacroUserIdStr<'a>,
+ /// Requested seat plan.
+ pub plan: SeatPlan,
+ /// Request the introductory Premium trial instead of immediate billing.
+ pub onboarding_trial: bool,
+ /// Return destination after successful checkout.
+ pub success_url: String,
+ /// Return destination after cancellation.
+ pub cancel_url: String,
+ /// Optional promotion for a standard paid checkout.
+ pub discount: Option<String>,
+ /// Team ownership and attribution supplied by the authenticated boundary.
+ pub metadata: HashMap<String, String>,
+}
+
+/// Billing terms approved by the service.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CheckoutTerms {
+ /// Charge the configured plan price immediately.
+ Paid,
+ /// Collect a payment method now and begin billing after the introductory period.
+ Trial,
+}
+
+/// Confirms the granted terms as well as the hosted destination.
+pub struct CheckoutResult {
+ /// Opaque hosted checkout URL.
+ pub url: String,
+ /// The trial duration actually granted by the server.
+ pub trial_days: Option<u8>,
+}
+
+/// Errors that callers can distinguish without understanding the provider.
+#[derive(Debug, Error)]
+pub enum CheckoutError<E> {
+ /// The account has no billing customer.
+ #[error("User does not have a stripe id")]
+ MissingCustomer,
+ /// A second subscription must not be created.
+ #[error("User already has an active subscription")]
+ AlreadySubscribed,
+ /// Never silently replace an advertised trial with an immediate charge.
+ #[error("The 30-day trial is only available for your first Premium subscription")]
+ TrialUnavailable,
+ /// The requested plan is not currently sold.
+ #[error("This plan is not available yet")]
+ PlanUnavailable,
+ /// An explicitly supplied promotion must be valid.
+ #[error("Invalid promo code")]
+ PromoCodeNotFound,
+ /// Persistence or provider failure, preserving its original type and cause.
+ #[error(transparent)]
+ Gateway(E),
+}
+
+/// Billing capabilities used by the checkout service. Provider IDs stay opaque.
+pub trait CheckoutGateway: Send + Sync {
+ /// Validated provider customer identity.
+ type Customer: Send + Sync;
+ /// Validated provider promotion identity.
+ type Promotion: Send + Sync;
+ /// Adapter error retaining the original failure.
+ type Error: std::error::Error + Send + Sync + 'static;
+
+ /// Resolve the authenticated account's billing customer.
+ fn customer(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<Self::Customer>, Self::Error>> + Send;
+ /// Include every page and every subscription status.
+ fn history(
+ &self,
+ customer: &Self::Customer,
+ ) -> impl Future<Output = Result<SubscriptionHistory, Self::Error>> + Send;
+ /// Read the offer already granted by the invite domain.
+ fn invite_promotion(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<String>, Self::Error>> + Send;
+ /// Resolve an active promotion code.
+ fn promotion(
+ &self,
+ code: &str,
+ ) -> impl Future<Output = Result<Option<Self::Promotion>, Self::Error>> + Send;
+ /// Create a checkout with exactly the approved terms and optional promotion.
+ fn create_session(
+ &self,
+ customer: Self::Customer,
+ request: CheckoutRequest<'_>,
+ terms: CheckoutTerms,
+ promotion: Option<Self::Promotion>,
+ ) -> impl Future<Output = Result<String, Self::Error>> + Send;
+}
+
+/// Orchestrates eligibility, existing invite offers, and provider checkout creation.
+pub struct CheckoutService<G> {
+ gateway: G,
+}
+
+impl<G: CheckoutGateway> CheckoutService<G> {
+ /// Compose a service with its billing adapter.
+ pub fn new(gateway: G) -> Self {
+ Self { gateway }
+ }
+
+ /// Create a paid checkout or a code-free first-subscription trial.
+ pub async fn create(
+ &self,
+ request: CheckoutRequest<'_>,
+ ) -> Result<CheckoutResult, CheckoutError<G::Error>> {
+ if !SeatPlan::PURCHASABLE.contains(&request.plan) {
+ return Err(CheckoutError::PlanUnavailable);
+ }
+ let customer = self
+ .gateway
+ .customer(&request.user_id)
+ .await
+ .map_err(CheckoutError::Gateway)?
+ .ok_or(CheckoutError::MissingCustomer)?;
+ let history = self
+ .gateway
+ .history(&customer)
+ .await
+ .map_err(CheckoutError::Gateway)?;
+ if history.has_active_subscription {
+ return Err(CheckoutError::AlreadySubscribed);
+ }
+ let terms = if request.onboarding_trial {
+ if request.plan != SeatPlan::Premium || history.has_previous_subscription {
+ return Err(CheckoutError::TrialUnavailable);
+ }
+ CheckoutTerms::Trial
+ } else {
+ CheckoutTerms::Paid
+ };
+
+ // The introductory trial is automatic and does not stack with discount codes.
+ // Preserve existing invite/explicit-promotion behavior for standard purchases.
+ let promotion = if terms == CheckoutTerms::Trial {
+ None
+ } else if let Some(code) = request.discount.as_deref() {
+ Some(
+ self.gateway
+ .promotion(code)
+ .await
+ .map_err(CheckoutError::Gateway)?
+ .ok_or(CheckoutError::PromoCodeNotFound)?,
+ )
+ } else {
+ self.invite_promotion(&request.user_id).await
+ };
+ let url = self
+ .gateway
+ .create_session(customer, request, terms, promotion)
+ .await
+ .map_err(CheckoutError::Gateway)?;
+ Ok(CheckoutResult {
+ url,
+ trial_days: (terms == CheckoutTerms::Trial).then_some(ONBOARDING_TRIAL_DAYS),
+ })
+ }
+
+ async fn invite_promotion(&self, user: &MacroUserIdStr<'_>) -> Option<G::Promotion> {
+ let offer = async {
+ match self.gateway.invite_promotion(user).await? {
+ Some(code) => self.gateway.promotion(&code).await,
+ None => Ok(None),
+ }
+ }
+ .await;
+ match offer {
+ Ok(promotion) => promotion,
+ Err(error) => {
+ tracing::error!(error=?error, "failed to apply optional invite promotion");
+ None
+ }
+ }
+ }
+}
diff --git a/services/authentication_service/src/service/subscription_checkout/test.rs b/services/authentication_service/src/service/subscription_checkout/test.rs
new file mode 100644
index 0000000000..704479a4a0
--- /dev/null
+++ b/services/authentication_service/src/service/subscription_checkout/test.rs
@@ -0,0 +1,189 @@
+use super::*;
+use std::sync::Mutex;
+
+#[derive(Default)]
+struct FakeGateway {
+ history: SubscriptionHistory,
+ history_failure: bool,
+ missing_customer: bool,
+ invalid_promo: bool,
+ invite: bool,
+ created: Mutex<Vec<(CheckoutTerms, Option<String>)>>,
+ promotion_reads: Mutex<u8>,
+}
+
+impl CheckoutGateway for FakeGateway {
+ type Customer = ();
+ type Promotion = String;
+ type Error = std::io::Error;
+
+ async fn customer(&self, _: &MacroUserIdStr<'_>) -> Result<Option<()>, Self::Error> {
+ Ok((!self.missing_customer).then_some(()))
+ }
+ async fn history(&self, _: &()) -> Result<SubscriptionHistory, Self::Error> {
+ if self.history_failure {
+ return Err(std::io::Error::other("offline"));
+ }
+ Ok(self.history)
+ }
+ async fn invite_promotion(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ ) -> Result<Option<String>, Self::Error> {
+ Ok(self.invite.then(|| "invite".into()))
+ }
+ async fn promotion(&self, code: &str) -> Result<Option<String>, Self::Error> {
+ *self.promotion_reads.lock().unwrap() += 1;
+ Ok((!self.invalid_promo).then(|| code.to_owned()))
+ }
+ async fn create_session(
+ &self,
+ _: (),
+ _: CheckoutRequest<'_>,
+ terms: CheckoutTerms,
+ promotion: Option<String>,
+ ) -> Result<String, Self::Error> {
+ self.created.lock().unwrap().push((terms, promotion));
+ Ok("https://checkout.stripe.com/test".into())
+ }
+}
+
+fn request(trial: bool) -> CheckoutRequest<'static> {
+ CheckoutRequest {
+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ plan: SeatPlan::Premium,
+ onboarding_trial: trial,
+ success_url: "https://macro.com/app/onboarding?subscriptionSuccess=true".into(),
+ cancel_url: "https://macro.com/app/onboarding?subscriptionCancel=true".into(),
+ discount: None,
+ metadata: HashMap::new(),
+ }
+}
+
+#[tokio::test]
+async fn first_subscription_gets_trial_without_a_code_or_invite() {
+ let service = CheckoutService::new(FakeGateway::default());
+ let checkout = service.create(request(true)).await.unwrap();
+ assert_eq!(checkout.trial_days, Some(30));
+ assert_eq!(
+ *service.gateway.created.lock().unwrap(),
+ vec![(CheckoutTerms::Trial, None)]
+ );
+ assert_eq!(*service.gateway.promotion_reads.lock().unwrap(), 0);
+}
+
+#[tokio::test]
+async fn canceled_subscription_does_not_get_another_trial_or_a_paid_fallback() {
+ let service = CheckoutService::new(FakeGateway {
+ history: SubscriptionHistory {
+ has_previous_subscription: true,
+ has_active_subscription: false,
+ },
+ ..Default::default()
+ });
+ assert!(matches!(
+ service.create(request(true)).await,
+ Err(CheckoutError::TrialUnavailable)
+ ));
+ assert!(service.gateway.created.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn active_and_trialing_customers_cannot_buy_a_second_subscription() {
+ let service = CheckoutService::new(FakeGateway {
+ history: SubscriptionHistory {
+ has_previous_subscription: true,
+ has_active_subscription: true,
+ },
+ ..Default::default()
+ });
+ for trial in [true, false] {
+ assert!(matches!(
+ service.create(request(trial)).await,
+ Err(CheckoutError::AlreadySubscribed)
+ ));
+ }
+ assert!(service.gateway.created.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn history_failure_cannot_turn_a_trial_into_an_immediate_charge() {
+ let service = CheckoutService::new(FakeGateway {
+ history_failure: true,
+ ..Default::default()
+ });
+ assert!(matches!(
+ service.create(request(true)).await,
+ Err(CheckoutError::Gateway(_))
+ ));
+ assert!(service.gateway.created.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn ordinary_checkout_keeps_its_paid_terms_and_invite_promotion() {
+ let service = CheckoutService::new(FakeGateway {
+ invite: true,
+ history: SubscriptionHistory {
+ has_previous_subscription: true,
+ has_active_subscription: false,
+ },
+ ..Default::default()
+ });
+ let checkout = service.create(request(false)).await.unwrap();
+ assert_eq!(checkout.trial_days, None);
+ assert_eq!(
+ *service.gateway.created.lock().unwrap(),
+ vec![(CheckoutTerms::Paid, Some("invite".into()))]
+ );
+}
+
+#[tokio::test]
+async fn explicit_invalid_discount_is_rejected_for_paid_checkout() {
+ let service = CheckoutService::new(FakeGateway {
+ invalid_promo: true,
+ ..Default::default()
+ });
+ let mut input = request(false);
+ input.discount = Some("bad-code".into());
+ assert!(matches!(
+ service.create(input).await,
+ Err(CheckoutError::PromoCodeNotFound)
+ ));
+ assert!(service.gateway.created.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn trial_does_not_require_or_stack_an_invite_discount() {
+ let service = CheckoutService::new(FakeGateway {
+ invite: true,
+ invalid_promo: true,
+ ..Default::default()
+ });
+ let mut input = request(true);
+ input.discount = Some("old-code".into());
+ service.create(input).await.unwrap();
+ assert_eq!(
+ *service.gateway.created.lock().unwrap(),
+ vec![(CheckoutTerms::Trial, None)]
+ );
+ assert_eq!(*service.gateway.promotion_reads.lock().unwrap(), 0);
+}
+
+#[tokio::test]
+async fn missing_customer_and_unavailable_plan_never_create_checkout() {
+ let service = CheckoutService::new(FakeGateway {
+ missing_customer: true,
+ ..Default::default()
+ });
+ assert!(matches!(
+ service.create(request(true)).await,
+ Err(CheckoutError::MissingCustomer)
+ ));
+ let mut input = request(true);
+ input.plan = SeatPlan::Max;
+ assert!(matches!(
+ service.create(input).await,
+ Err(CheckoutError::PlanUnavailable)
+ ));
+ assert!(service.gateway.created.lock().unwrap().is_empty());
+}
diff --git a/tooling/just/xtask.just b/tooling/just/xtask.just
index 71e70bdcab..52a7f39656 100644
--- a/tooling/just/xtask.just
+++ b/tooling/just/xtask.just
@@ -12,7 +12,6 @@ alias local := run_local
# just run_local # default instance
# just run_local --instance agent-a # isolated, concurrent instance
# just run_local --no-doppler --env-file ./local.env --no-frontend --no-build
-# just run_local --enable-onboarding # opt into the existing onboarding v4 flag
# just run_local --no-snapshot # re-run the full DB/kickstart/index init
run_local *ARGS:
{{ xtask }} run-local "$@"
diff --git a/tooling/xtask/crates/xtask_local/src/local.rs b/tooling/xtask/crates/xtask_local/src/local.rs
index 562c581ffe..bb2b55fe73 100644
--- a/tooling/xtask/crates/xtask_local/src/local.rs
+++ b/tooling/xtask/crates/xtask_local/src/local.rs
@@ -423,7 +423,6 @@ pub fn run_stack(mode: Mode, args: &cli::RunArgs) -> Result<()> {
&instance,
mode,
args.traces.enabled() && summary::port_open(4318),
- args.enable_onboarding,
)?
};
diff --git a/tooling/xtask/crates/xtask_local/src/local/cli.rs b/tooling/xtask/crates/xtask_local/src/local/cli.rs
index 009bf01b0b..69f4c315f5 100644
--- a/tooling/xtask/crates/xtask_local/src/local/cli.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/cli.rs
@@ -117,11 +117,6 @@ pub struct RunArgs {
/// Do not start or serve the frontend.
#[arg(long)]
pub no_frontend: bool,
- /// Turn on onboarding v4 for the attached vite server
- /// (`VITE_ENABLE_ONBOARDING_V4=true`). Off by default so signing in does
- /// not dump you into the stepper. No effect on `stack up` static bundles.
- #[arg(long)]
- pub enable_onboarding: bool,
/// Stream subprocess output and show per-step timings.
#[arg(long, short)]
pub verbose: bool,
diff --git a/tooling/xtask/crates/xtask_local/src/local/cli/test.rs b/tooling/xtask/crates/xtask_local/src/local/cli/test.rs
index 147c9d4bee..69a437f9c4 100644
--- a/tooling/xtask/crates/xtask_local/src/local/cli/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/cli/test.rs
@@ -46,15 +46,6 @@ fn stack_update_accepts_binaries_dir_with_build_aux_services() {
assert!(args.build_aux_services);
}
-#[test]
-fn run_local_defaults_onboarding_off() {
- let cli = Cli::try_parse_from(["cargo-x", "run-local"]).unwrap();
- let Cmd::RunLocal(args) = cli.command else {
- panic!("expected run-local command");
- };
- assert!(!args.enable_onboarding);
-}
-
#[test]
fn run_local_defaults_cf_tunnels_off() {
let cli = Cli::try_parse_from(["cargo-x", "run-local"]).unwrap();
@@ -73,15 +64,6 @@ fn run_local_accepts_with_cf_tunnel() {
assert!(args.with_cf_tunnel);
}
-#[test]
-fn run_local_accepts_enable_onboarding() {
- let cli = Cli::try_parse_from(["cargo-x", "run-local", "--enable-onboarding"]).unwrap();
- let Cmd::RunLocal(args) = cli.command else {
- panic!("expected run-local command");
- };
- assert!(args.enable_onboarding);
-}
-
#[test]
fn stack_has_no_snapshot_verb() {
match Cli::try_parse_from(["cargo-x", "stack", "snapshot"]) {
diff --git a/tooling/xtask/crates/xtask_local/src/local/e2e.rs b/tooling/xtask/crates/xtask_local/src/local/e2e.rs
index e85c64f5d4..6d48bace27 100644
--- a/tooling/xtask/crates/xtask_local/src/local/e2e.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/e2e.rs
@@ -119,7 +119,6 @@ pub fn run(args: &LocalE2eArgs) -> Result<()> {
env: EnvArgs::default(),
build: BuildArgs::default(),
no_frontend: true,
- enable_onboarding: false,
// E2E stacks are ephemeral and throughput-sensitive; no collector,
// and Playwright brings its own browsers.
traces: TracesBackend::Off,
diff --git a/tooling/xtask/crates/xtask_local/src/local/frontend.rs b/tooling/xtask/crates/xtask_local/src/local/frontend.rs
index 88f64699a0..7bc657edf3 100644
--- a/tooling/xtask/crates/xtask_local/src/local/frontend.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/frontend.rs
@@ -115,12 +115,7 @@ pub fn build_static(stage: &Stage, instance: &Instance, mode: Mode) -> Result<()
/// and exercises the real browser -> proxy -> collector path. Left unset
/// otherwise. This overrides the bare-dev defaults in apps/web/.env.local
/// (Vite lets process env win).
-fn dev_env(
- instance: &Instance,
- mode: Mode,
- traces_enabled: bool,
- enable_onboarding: bool,
-) -> Result<Vec<(String, String)>> {
+fn dev_env(instance: &Instance, mode: Mode, traces_enabled: bool) -> Result<Vec<(String, String)>> {
let mut env = vec![
(
"PORT".to_string(),
@@ -168,12 +163,6 @@ fn dev_env(
"VITE_ENABLE_BROWSER_OTEL".to_string(),
traces_enabled.to_string(),
));
- // Existing override: always set so the app's DEV_MODE default (on) does
- // not win. `just run_local --enable-onboarding` is the opt-in.
- env.push((
- "VITE_ENABLE_ONBOARDING_V4".to_string(),
- enable_onboarding.to_string(),
- ));
Ok(env)
}
@@ -314,7 +303,6 @@ pub fn start(
instance: &Instance,
mode: Mode,
traces_enabled: bool,
- enable_onboarding: bool,
) -> Result<Option<Frontend>> {
if mode.spec().wait_backend_before_frontend {
wait_backend_ready(stage, instance)?;
@@ -367,7 +355,7 @@ pub fn start(
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
- for (k, v) in dev_env(instance, mode, traces_enabled, enable_onboarding)? {
+ for (k, v) in dev_env(instance, mode, traces_enabled)? {
cmd.env(k, v);
}
let process = spawn(stage, &mut cmd, port)?;
diff --git a/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs b/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs
index 06d7a25a6a..85a74f6cd9 100644
--- a/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs
@@ -10,7 +10,7 @@ fn stack_frontend_uses_same_origin_with_an_instance_specific_server_target() {
Instance::derive(Some("other-dev"), Some(20300)).unwrap(),
] {
for mode in [Mode::Local, Mode::Dev] {
- let env: std::collections::HashMap<_, _> = dev_env(&instance, mode, true, false)
+ let env: std::collections::HashMap<_, _> = dev_env(&instance, mode, true)
.unwrap()
.into_iter()
.collect();
@@ -35,7 +35,7 @@ fn stack_frontend_uses_same_origin_with_an_instance_specific_server_target() {
assert!(!env.contains_key("VITE_AI_EDITING_WORKER_URL"));
}
}
- let env: std::collections::HashMap<_, _> = dev_env(&instance, Mode::Local, false, false)
+ let env: std::collections::HashMap<_, _> = dev_env(&instance, Mode::Local, false)
.unwrap()
.into_iter()
.collect();
diff --git a/tooling/xtask/crates/xtask_local/src/local/stack.rs b/tooling/xtask/crates/xtask_local/src/local/stack.rs
index 74e3f5c6bd..daff1e4ab2 100644
--- a/tooling/xtask/crates/xtask_local/src/local/stack.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/stack.rs
@@ -323,7 +323,6 @@ fn bootstrap_from_update(args: &UpdateArgs) -> Result<()> {
binaries_dir: args.binaries_dir.clone(),
},
no_frontend: false,
- enable_onboarding: false,
verbose: args.verbose,
no_snapshot: false,
traces: super::cli::TracesBackend::default(),
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
index c66610d1bd..d4d51568f6 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
@@ -107,6 +107,7 @@ fn test() -> Job {
.add_step(steps::setup_nix())
.add_step(steps::setup_reqs_web("Setup", true))
.add_step(run_tests())
+ .add_step(run_signup_browser_tests())
.add_step(steps::teardown_nix())
}
@@ -282,6 +283,14 @@ fn run_tests() -> Step<Run> {
.working_directory(xtask_paths::repo_dir!("apps/web"))
}
+/// Sign-in, sign-up, and onboarding against their fake backends: real views in
+/// Chromium, no network, so they run on every web PR.
+fn run_signup_browser_tests() -> Step<Run> {
+ Step::new("Sign-up Browser Tests")
+ .run("just test-signup-browser")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+}
+
fn cycles_import_check() -> Step<Run> {
Step::new("Cycles Import Check")
.run("biome lint --changed --no-errors-on-unmatched --only=suspicious/noImportCycles")
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
index db0f514cac..ba5f7310ac 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
@@ -121,3 +121,26 @@ fn build_job_uses_remote_sccache_and_wasm_cache() {
"build still produces the vite bundle: {build}"
);
}
+
+#[test]
+fn test_job_runs_signup_browser_tests_after_vitest() {
+ let yaml = web_app_check_main().to_string().expect("workflow yaml");
+ // The job and its vitest step are both named "Test"; slice from the job.
+ let start = yaml.find("name: Test\n").expect("Test job");
+ let end = yaml[start..]
+ .find("name: Cycles Import Check")
+ .map_or(yaml.len(), |offset| start + offset);
+ let test_job = &yaml[start..end];
+ let vitest = test_job.find("bunx vitest").expect("vitest step");
+ let browser = test_job
+ .find("just test-signup-browser")
+ .expect("sign-up browser step");
+ assert!(
+ vitest < browser,
+ "browser tests run after vitest: {test_job}"
+ );
+ assert!(
+ test_job.contains("playwright: 'true'"),
+ "the Test job installs Playwright's Chromium: {test_job}"
+ );
+}