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(auth): route-based agent signup and setup page (#9544)

Eric Hayes6a1120586b2c
diff --git a/.sqlx/query-ab144d9515856ee0fd36e436c8b8d7f88845f6e006d30b64c6bc751551e6a94d.json b/.sqlx/query-ab144d9515856ee0fd36e436c8b8d7f88845f6e006d30b64c6bc751551e6a94d.json
new file mode 100644
index 0000000000..fb0b421420
--- /dev/null
+++ b/.sqlx/query-ab144d9515856ee0fd36e436c8b8d7f88845f6e006d30b64c6bc751551e6a94d.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE \"User\" SET \"isAgent\" = TRUE WHERE \"email\" = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ab144d9515856ee0fd36e436c8b8d7f88845f6e006d30b64c6bc751551e6a94d"
+}
diff --git a/apps/marketing/README.md b/apps/marketing/README.md
index 2ffeccdb29..67bd6d4abb 100644
--- a/apps/marketing/README.md
+++ b/apps/marketing/README.md
@@ -15,9 +15,15 @@ Cream slab typography adds 45 to the base font weight; utility-class slab text
uses weight 360, and the Tasks founder heading uses 445.
Slab display copy uses warm near-black (`#1d1c1a`) in the cream palette.
+Every page's HTML starts with a visually hidden notice telling AI agents to use
+`/app/signup/agent` (`#agent-signup-notice`, in both `index.html` and `start.html`,
+which builds the homepage). It stays in the
+accessibility tree and page text, because that is what agents read; do not hide it
+with `display: none`.
+
Public calls to action use the shared `site-nav-start` treatment: warm white,
soft pill corners, a fine border, and a 2px arrow shift on hover. `Book a demo` is a
-soft grey secondary action; the header's `Open app` uses a warm-white fill with
+soft grey secondary action; the header's `Sign Up` uses a warm-white fill with
near-black text, a fine border, and no arrow. Its fill fades with the header label during
the footer transition. As it lands in the footer, the same link reveals the
original wider white pill, glass rim, and arrow. It follows the existing scroll
@@ -224,7 +230,7 @@ Verified direct installer URLs remain usable while loading and if the API fails;
update these fallbacks in `desktopDownloads.ts` when retiring older installers.
The separate “All releases” link opens GitHub, with the selected installer's
release version displayed beneath it.
-The page hides the header's Open app action, has no web-app download option,
+The page hides the header's Sign Up action, has no web-app download option,
and has no header/footer navigation entry.
Check the installer link, keyboard navigation, and desktop/mobile layouts.
@@ -994,7 +1000,7 @@ mounted. Chat and Docs retain equal-width source panes; when a pane would be
narrower than 240px, they use the existing single-pane navigation. Verify opening
and closing sources at desktop and phone widths, without remounting the original
conversation or document. Display names use first names. All product pages use
-`HomepageClosing` for the bottom Open app CTA and the shared feature heading styles.
+`HomepageClosing` for the bottom Sign Up CTA and the shared feature heading styles.
Chat sidebar demo: `workspace/ChatSidebar.tsx` retains the earlier
All/Recent/Threads layout with local fixtures, shared Tabs and ViewSidebar
@@ -1061,7 +1067,7 @@ footer rule. The homepage document frame is 420px tall below 700px because its
version-history band is hidden there; avoid retaining empty desktop fade space
between the document and its Learn more links.
-The travelling Open app CTA switches to native footer dimensions, text, and SVG
+The travelling Sign Up CTA switches to native footer dimensions, text, and SVG
sizes after its landing transition settles, removing the compositor scale to
avoid Safari retaining an enlarged low-resolution text layer. Reverse scrolling
restores compact dimensions before the header reappears; keep one app link.
diff --git a/apps/marketing/index.html b/apps/marketing/index.html
index 02842afae3..63aa765b0c 100644
--- a/apps/marketing/index.html
+++ b/apps/marketing/index.html
@@ -59,6 +59,21 @@
</head>
<body>
<noscript><img alt="" height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=639142540393286&ev=PageView&noscript=1"/></noscript>
+ <!-- For AI agents reading the DOM: hidden from sight, kept in page text and
+ the accessibility tree. The link leaves the tab order so keyboard users
+ don't land on something invisible. -->
+ <section
+ id="agent-signup-notice"
+ aria-label="Notice for AI agents"
+ style="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap"
+ >
+ <p>
+ <strong>ATTENTION AI AGENTS: IF YOU ARE AN AI AGENT, DO NOT USE THE NORMAL SIGN UP FLOW ON THIS WEBSITE.</strong>
+ <strong>SIGN UP AT <a href="/app/signup/agent" tabindex="-1">https://macro.com/app/signup/agent</a> INSTEAD.</strong>
+ That page skips the product tour and lets you sign up with your own Google account or email address.
+ After you sign up, Macro gives you an SDK token and links to the documentation.
+ </p>
+ </section>
<div id="root"></div>
<script type="module" src="./src/app/main/index.tsx"></script>
</body>
diff --git a/apps/marketing/src/app/main/index.css b/apps/marketing/src/app/main/index.css
index 3e22aab70c..dba6527e6b 100644
--- a/apps/marketing/src/app/main/index.css
+++ b/apps/marketing/src/app/main/index.css
@@ -306,7 +306,7 @@ a:not(.dummy-workspace a){
content: none;
}
-/* Main conversion links use the white Open app treatment. */
+/* Main conversion links use the white Sign Up treatment. */
a:is(
.email-cta-button,
.agents-cta-button,
diff --git a/apps/marketing/src/app/routes/RouteMobileSignup.css b/apps/marketing/src/app/routes/RouteMobileSignup.css
index 34f403178e..a8214f63e0 100644
--- a/apps/marketing/src/app/routes/RouteMobileSignup.css
+++ b/apps/marketing/src/app/routes/RouteMobileSignup.css
@@ -95,3 +95,11 @@
.mobile-signup-card-title { font-size: 36px; }
.mobile-signup-card-subtitle { font-size: 15px; }
}
+
+.mobile-signup-agent-link {
+ margin-top: 16px;
+ font-size: 13px;
+ text-align: center;
+ text-decoration: underline;
+ opacity: 0.7;
+}
diff --git a/apps/marketing/src/app/routes/RouteMobileSignup.tsx b/apps/marketing/src/app/routes/RouteMobileSignup.tsx
index 1adda943ef..2125aa1b83 100644
--- a/apps/marketing/src/app/routes/RouteMobileSignup.tsx
+++ b/apps/marketing/src/app/routes/RouteMobileSignup.tsx
@@ -30,6 +30,13 @@ export const RouteMobileSignup: Component = () => {
<div class="mobile-signup-card-body">
<FormMobileSignup buttonName="mobile_signup_page" variant="card" />
</div>
+ <a
+ class="mobile-signup-agent-link"
+ href="/app/signup/agent"
+ target="_self"
+ >
+ Sign up as agent
+ </a>
</section>
);
};
diff --git a/apps/marketing/src/features/marketing/components/SiteHeader.test.tsx b/apps/marketing/src/features/marketing/components/SiteHeader.test.tsx
index c8f3492ff5..2e24ae29e3 100644
--- a/apps/marketing/src/features/marketing/components/SiteHeader.test.tsx
+++ b/apps/marketing/src/features/marketing/components/SiteHeader.test.tsx
@@ -92,7 +92,7 @@ it('uses a single hamburger touch toggle and closes when leaving navigation', ()
expect(screen.queryByRole('navigation')).toBeNull();
fireEvent.click(toggle);
fireEvent.focusOut(toggle, {
- relatedTarget: screen.getByRole('link', { name: 'Open app' }),
+ relatedTarget: screen.getByRole('link', { name: 'Sign Up' }),
});
expect(screen.queryByRole('navigation')).toBeNull();
});
diff --git a/apps/marketing/src/features/marketing/components/SiteHeader.tsx b/apps/marketing/src/features/marketing/components/SiteHeader.tsx
index b6182686f0..b0fc7932ef 100644
--- a/apps/marketing/src/features/marketing/components/SiteHeader.tsx
+++ b/apps/marketing/src/features/marketing/components/SiteHeader.tsx
@@ -222,9 +222,9 @@ export function SiteHeader(props: { hideOpenApp?: boolean }) {
href="/app/signup"
onClick={routePhoneToMobileSignup}
>
- <span class="site-nav-open-label">Open app</span>
+ <span class="site-nav-open-label">Sign Up</span>
<span class="site-nav-open-footer" aria-hidden="true">
- <span>Open app</span>
+ <span>Sign Up</span>
<svg
width="28"
height="28"
diff --git a/apps/marketing/src/features/marketing/views/sales-page.css b/apps/marketing/src/features/marketing/views/sales-page.css
index 77c529b845..e70399a5ea 100644
--- a/apps/marketing/src/features/marketing/views/sales-page.css
+++ b/apps/marketing/src/features/marketing/views/sales-page.css
@@ -9,7 +9,7 @@
/* Pull the CTA up to the subtitle: 16px instead of the homepage's 36px
(24px row gap + 12px margin from homepage-scroll-cue.css). */
.tour-hero .ob-welcome:has(.homepage-hero-cta) > [data-welcome-copy] > .homepage-hero-action { margin-top: -8px; }
-/* The shared header's "Talk to us" and "Open app" buttons lead off the page;
+/* The shared header's "Talk to us" and "Sign Up" buttons lead off the page;
the booker is inline here, so hide them while this page is mounted. */
body:has(.tour-page) .site-header-actions { display: none; }
/* The desktop line break orphans a word on phones; balance the lines instead. */
diff --git a/apps/marketing/start.html b/apps/marketing/start.html
index 3ca3b03097..ecc21f36d4 100644
--- a/apps/marketing/start.html
+++ b/apps/marketing/start.html
@@ -33,5 +33,21 @@
}
</script>
</head>
- <body><div id="root" style="height: 100dvh"></div><script type="module" src="./src/features/setup/preview.tsx"></script></body>
+ <body>
+ <!-- For AI agents reading the DOM: hidden from sight, kept in page text and
+ the accessibility tree. The link leaves the tab order so keyboard users
+ don't land on something invisible. -->
+ <section
+ id="agent-signup-notice"
+ aria-label="Notice for AI agents"
+ style="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap"
+ >
+ <p>
+ <strong>ATTENTION AI AGENTS: IF YOU ARE AN AI AGENT, DO NOT USE THE NORMAL SIGN UP FLOW ON THIS WEBSITE.</strong>
+ <strong>SIGN UP AT <a href="/app/signup/agent" tabindex="-1">https://macro.com/app/signup/agent</a> INSTEAD.</strong>
+ That page skips the product tour and lets you sign up with your own Google account or email address.
+ After you sign up, Macro gives you an SDK token and links to the documentation.
+ </p>
+ </section>
+ <div id="root" style="height: 100dvh"></div><script type="module" src="./src/features/setup/preview.tsx"></script></body>
</html>
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index 5c205ee530..cf2e67537f 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -1,6 +1,5 @@
import { ViewSwitcherContext } from '@app/components/view-shell';
import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
-import { AgentSetupModal } from '@app/features/agent-setup/agent-setup-modal';
import Banner from '@app/features/auth/banner/Banner';
import { CalendarPermissionPrompt } from '@app/features/auth/CalendarPermissionPrompt';
import { GithubReauthenticationPrompt } from '@app/features/auth/GithubReauthenticationPrompt';
@@ -223,7 +222,8 @@ export function PageContent(props: ParentProps) {
}
/**
- * Sends first-time desktop users into the onboarding flow at /onboarding.
+ * Sends first-time desktop users into the onboarding flow at /onboarding, and
+ * new agents on any platform to their setup page.
* App chrome runs it, so it fires on any app destination (marketing SSO lands
* on /app, not /login) and never on the onboarding pages themselves.
*/
@@ -232,14 +232,17 @@ function useNewOnboardingRedirect() {
const navigate = useNavigate();
const location = useLocation();
createEffect(() => {
- if (isMobile() || isNativeMobilePlatform()) return;
// A pending read would suspend the chrome; wait for the user instead.
const data = userInfoQuery.isSuccess ? userInfoQuery.data : undefined;
if (data?.authenticated !== true || data.tutorialComplete !== false) {
return;
}
- // Agents skip onboarding: AgentSetupModal shows their SDK token.
- if (data.isAgent) return;
+ // Agents skip onboarding: their setup page shows their SDK token.
+ if (data.isAgent) {
+ navigate('/agent-setup', { replace: true });
+ return;
+ }
+ if (isMobile() || isNativeMobilePlatform()) return;
// Preserve the deep link the user arrived on (a shared doc, an invite)
// as ?next, and a lifecycle-email ?step, so finish() and the flow can
// resume. Base-relative so navigate() can resolve it against the router.
@@ -378,7 +381,6 @@ export function AppChrome(props: ParentProps) {
</FloatRegion>
</Show>
<InitialInteractiveOnboardingModal />
- <AgentSetupModal />
<Suspense>
<Show when={isAuthenticated()}>
<Launcher open={createMenuOpen()} onOpenChange={setCreateMenuOpen} />
diff --git a/apps/web/src/features/agent-setup/agent-setup-dialog.tsx b/apps/web/src/features/agent-setup/agent-setup-dialog.tsx
deleted file mode 100644
index e29b400f8a..0000000000
--- a/apps/web/src/features/agent-setup/agent-setup-dialog.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import { t } from '@app/lib/i18n';
-import { CredentialField } from '@channel/Bots/CredentialField';
-import { LoadingSpinner } from '@core/component/LoadingSpinner';
-import { toast } from '@core/component/Toast/Toast';
-import { useAgentSetupMutation } from '@queries/auth/agent-setup';
-import { useCompleteTutorialMutation } from '@queries/auth/tutorial';
-import { Button, Dialog, Panel } from '@ui';
-import { createEffect, Match, Show, Switch } from 'solid-js';
-
-const SDK_DOCS_URL = 'https://sdk.macro.com';
-
-const QUICK_START = `npm install @macro-inc/sdk
-export MACRO_API_KEY="<your token>"`;
-
-const PROFILE_SNIPPET = `const macro = new Macro({});
-const image = await macro.me.uploadProfilePicture(bytes, {
- fileName: 'avatar.png',
- contentType: 'image/png',
-});
-await macro.me.update({ name: 'Your Name', profilePicture: image });`;
-
-const NEW_TOKEN_SNIPPET = `const { secret } = await macro.apiKeys.create('my token');`;
-
-function Snippet(props: { code: string }) {
- return (
- <pre class="overflow-x-auto rounded-lg border border-edge-muted bg-ink/[0.025] px-3 py-2 font-mono text-xs text-ink">
- {props.code}
- </pre>
- );
-}
-
-/**
- * An agent account's first screen: its SDK token and how to use it. Stays open
- * until the agent confirms it saved the token. The token is plain page text so
- * an agent driving a browser can read it. Reloading replaces the token, since a
- * key can only be shown once.
- */
-export function AgentSetupDialog() {
- const setup = useAgentSetupMutation();
- const confirm = useCompleteTutorialMutation({
- onError: () => toast.failure(t('agentSetup.confirmFailed')),
- });
-
- createEffect(() => {
- if (setup.isIdle) setup.mutate();
- });
-
- return (
- <Dialog open position="center" class="w-140 max-w-full">
- <Panel depth={2} active class="rounded-xl text-ink">
- <Panel.Header class="px-5">
- <Dialog.Title class="text-sm font-semibold">
- {t('agentSetup.title')}
- </Dialog.Title>
- </Panel.Header>
- <Panel.Body class="flex max-h-[80dvh] flex-col gap-4 overflow-y-auto p-5 text-sm">
- <Switch>
- <Match when={setup.isError}>
- <p class="text-ink-muted">{t('agentSetup.loadFailed')}</p>
- <Button
- variant="primary"
- size="sm"
- onClick={() => setup.mutate()}
- >
- {t('agentSetup.tryAgain')}
- </Button>
- </Match>
- <Match when={setup.data}>
- {(result) => (
- <>
- <p>{t('agentSetup.intro')}</p>
- <Show when={result().team_join_failed}>
- <p class="text-ink-muted">
- {t('agentSetup.teamJoinFailed')}
- </p>
- </Show>
- <CredentialField
- label={t('agentSetup.tokenLabel')}
- value={result().api_key}
- />
- <p class="break-all font-mono text-xs text-ink-muted">
- {result().api_key}
- </p>
- <div class="flex flex-col gap-1.5">
- <span class="text-xs font-medium">
- {t('agentSetup.useToken')}
- </span>
- <Snippet code={QUICK_START} />
- <span class="text-xs text-ink-muted">
- {t('agentSetup.readDocs')}{' '}
- <a
- href={SDK_DOCS_URL}
- target="_blank"
- rel="noreferrer"
- class="underline"
- >
- sdk.macro.com
- </a>
- </span>
- </div>
- <div class="flex flex-col gap-1.5">
- <span class="text-xs font-medium">
- {t('agentSetup.setProfile')}
- </span>
- <Snippet code={PROFILE_SNIPPET} />
- </div>
- <div class="flex flex-col gap-1.5">
- <span class="text-xs font-medium">
- {t('agentSetup.anotherToken')}
- </span>
- <Snippet code={NEW_TOKEN_SNIPPET} />
- <span class="text-xs text-ink-muted">
- {t('agentSetup.anotherTokenSettings')}
- </span>
- </div>
- <Button
- variant="primary"
- size="sm"
- disabled={confirm.isPending}
- onClick={() => confirm.mutate()}
- >
- {t('agentSetup.confirm')}
- </Button>
- </>
- )}
- </Match>
- <Match when={true}>
- <div class="flex min-h-36 items-center justify-center">
- <LoadingSpinner class="size-10 p-2" />
- </div>
- </Match>
- </Switch>
- </Panel.Body>
- </Panel>
- </Dialog>
- );
-}
diff --git a/apps/web/src/features/agent-setup/agent-setup-modal.tsx b/apps/web/src/features/agent-setup/agent-setup-modal.tsx
deleted file mode 100644
index 3be719c48e..0000000000
--- a/apps/web/src/features/agent-setup/agent-setup-modal.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { lazyNamed } from '@core/util/lazyNamed';
-import { useUserInfoQuery } from '@queries/auth/user-info';
-import { Show, Suspense } from 'solid-js';
-
-// Only an agent that has not confirmed its token ever sees it.
-const AgentSetupDialog = lazyNamed(
- () => import('./agent-setup-dialog'),
- 'AgentSetupDialog'
-);
-
-/** Opens an agent's setup dialog until it confirms it saved its token. */
-export function AgentSetupModal() {
- const userInfoQuery = useUserInfoQuery();
-
- const open = () => {
- // A pending read would suspend the chrome, so wait for the user. A failed
- // background refetch keeps its data: unmounting the dialog then would mint
- // a new token and revoke the one the agent already saw.
- const settled = userInfoQuery.isSuccess || userInfoQuery.isRefetchError;
- const data = settled ? userInfoQuery.data : undefined;
- return (
- data?.authenticated === true &&
- data.isAgent === true &&
- data.tutorialComplete === false
- );
- };
-
- return (
- <Show when={open()}>
- <Suspense>
- <AgentSetupDialog />
- </Suspense>
- </Show>
- );
-}
diff --git a/apps/web/src/features/agent-setup/agent-setup-page.tsx b/apps/web/src/features/agent-setup/agent-setup-page.tsx
new file mode 100644
index 0000000000..d3935e6b37
--- /dev/null
+++ b/apps/web/src/features/agent-setup/agent-setup-page.tsx
@@ -0,0 +1,163 @@
+import { t } from '@app/lib/i18n';
+import { useIsAuthenticated } from '@core/auth';
+import { LoadingSpinner } from '@core/component/LoadingSpinner';
+import { getWebOrigin } from '@core/util/webOrigin';
+import { useAgentSetupMutation } from '@queries/auth/agent-setup';
+import { useCompleteTutorialMutation } from '@queries/auth/tutorial';
+import { useUserInfoQuery } from '@queries/auth/user-info';
+import { useNavigate } from '@solidjs/router';
+import { Button } from '@ui';
+import { createEffect, For, Match, type ParentProps, Switch } from 'solid-js';
+import { match } from 'ts-pattern';
+import { agentSetupMarkdown, markdownParts } from './core/agent-setup-markdown';
+
+/** Who is looking at a setup page, and whether setup is theirs to finish. */
+function useSetupStatus() {
+ const userInfoQuery = useUserInfoQuery();
+ const isAuthenticated = useIsAuthenticated();
+ const navigate = useNavigate();
+
+ const status = () => {
+ if (isAuthenticated() === false) return 'signed-out';
+ // A failed background refetch keeps its data: leaving the page then would
+ // mint a new token and revoke the one the agent already saw.
+ const settled = userInfoQuery.isSuccess || userInfoQuery.isRefetchError;
+ if (!settled) return 'pending';
+ const data = userInfoQuery.data;
+ if (data?.isAgent === true && data.tutorialComplete === false) {
+ return 'needs-setup';
+ }
+ return 'finished';
+ };
+
+ createEffect(() => {
+ if (status() === 'signed-out') navigate('/login', { replace: true });
+ if (status() === 'finished') navigate('/', { replace: true });
+ });
+
+ return status;
+}
+
+function PageFrame(props: ParentProps) {
+ return (
+ <main class="h-full min-h-0 flex-1 overflow-y-auto bg-page text-ink">
+ <div class="mx-auto flex max-w-3xl flex-col gap-4 p-6">
+ {props.children}
+ </div>
+ </main>
+ );
+}
+
+/** Markdown source with its links left clickable, so its text is the page. */
+function MarkdownSource(props: { markdown: string }) {
+ return (
+ <pre class="whitespace-pre-wrap break-words font-mono text-sm leading-6">
+ <For each={markdownParts(props.markdown)}>
+ {(part) =>
+ match(part)
+ .with({ t: 'text' }, ({ text }) => text)
+ .with({ t: 'link' }, ({ label, url }) => (
+ <>
+ [{label}](
+ <a href={url} target="_self" class="underline">
+ {url}
+ </a>
+ )
+ </>
+ ))
+ .exhaustive()
+ }
+ </For>
+ </pre>
+ );
+}
+
+/**
+ * A new agent's first page: its SDK token and how to use it, as plain markdown
+ * an agent driving a browser can read. The app sends the agent back here until
+ * it follows the page's link to confirm it saved the token. Reloading replaces
+ * the token, since a key can only be shown once.
+ */
+export function AgentSetupPage() {
+ const status = useSetupStatus();
+ const setup = useAgentSetupMutation();
+
+ createEffect(() => {
+ if (status() === 'needs-setup' && setup.isIdle) setup.mutate();
+ });
+
+ const markdown = (apiKey: string, teamJoinFailed: boolean) =>
+ agentSetupMarkdown({
+ apiKey,
+ teamJoinFailed,
+ openAppUrl: `${getWebOrigin()}/app/agent-setup/done`,
+ copy: {
+ title: t('agentSetup.title'),
+ intro: t('agentSetup.intro'),
+ teamJoinFailed: t('agentSetup.teamJoinFailed'),
+ tokenLabel: t('agentSetup.tokenLabel'),
+ useToken: t('agentSetup.useToken'),
+ docsHeading: t('agentSetup.docsHeading'),
+ productDocs: t('agentSetup.productDocs'),
+ sdkDocs: t('agentSetup.sdkDocs'),
+ setProfile: t('agentSetup.setProfile'),
+ anotherToken: t('agentSetup.anotherToken'),
+ anotherTokenSettings: t('agentSetup.anotherTokenSettings'),
+ openApp: t('agentSetup.openApp'),
+ openAppLink: t('agentSetup.openAppLink'),
+ },
+ });
+
+ return (
+ <PageFrame>
+ <Switch fallback={<LoadingSpinner class="m-auto size-10 p-2" />}>
+ <Match when={setup.isError}>
+ <p class="text-ink-muted">{t('agentSetup.loadFailed')}</p>
+ <Button
+ class="self-start"
+ variant="primary"
+ size="sm"
+ onClick={() => setup.mutate()}
+ >
+ {t('agentSetup.tryAgain')}
+ </Button>
+ </Match>
+ <Match when={setup.data}>
+ {(result) => (
+ <MarkdownSource
+ markdown={markdown(result().api_key, result().team_join_failed)}
+ />
+ )}
+ </Match>
+ </Switch>
+ </PageFrame>
+ );
+}
+
+/** Where the setup page's link lands: confirms the token, then opens the app. */
+export function AgentSetupDonePage() {
+ const status = useSetupStatus();
+ const confirm = useCompleteTutorialMutation();
+
+ createEffect(() => {
+ if (status() === 'needs-setup' && confirm.isIdle) confirm.mutate();
+ });
+
+ return (
+ <PageFrame>
+ <Switch fallback={<LoadingSpinner class="m-auto size-10 p-2" />}>
+ <Match when={confirm.isError}>
+ <p class="text-ink-muted">{t('agentSetup.confirmFailed')}</p>
+ <Button
+ class="self-start"
+ variant="primary"
+ size="sm"
+ onClick={() => confirm.mutate()}
+ >
+ {t('agentSetup.tryAgain')}
+ </Button>
+ </Match>
+ </Switch>
+ </PageFrame>
+ );
+}
diff --git a/apps/web/src/features/agent-setup/core/agent-setup-markdown.test.ts b/apps/web/src/features/agent-setup/core/agent-setup-markdown.test.ts
new file mode 100644
index 0000000000..7f0a83e05a
--- /dev/null
+++ b/apps/web/src/features/agent-setup/core/agent-setup-markdown.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+import { markdownParts } from './agent-setup-markdown';
+
+describe('markdownParts', () => {
+ it('finds links between text and keeps every other character', () => {
+ expect(
+ markdownParts('- [Docs](https://docs.test)\n- [SDK](https://sdk.test)\n')
+ ).toEqual([
+ { t: 'text', text: '- ' },
+ { t: 'link', label: 'Docs', url: 'https://docs.test' },
+ { t: 'text', text: '\n- ' },
+ { t: 'link', label: 'SDK', url: 'https://sdk.test' },
+ { t: 'text', text: '\n' },
+ ]);
+ });
+
+ it('leaves code that only looks close to a link as text', () => {
+ const code = 'const list = [a, b]; call(list);';
+
+ expect(markdownParts(code)).toEqual([{ t: 'text', text: code }]);
+ });
+});
diff --git a/apps/web/src/features/agent-setup/core/agent-setup-markdown.ts b/apps/web/src/features/agent-setup/core/agent-setup-markdown.ts
new file mode 100644
index 0000000000..1fd41030f5
--- /dev/null
+++ b/apps/web/src/features/agent-setup/core/agent-setup-markdown.ts
@@ -0,0 +1,91 @@
+const QUICK_START = `npm install @macro-inc/sdk
+export MACRO_API_KEY="<your token>"`;
+
+const PROFILE_SNIPPET = `const macro = new Macro({});
+const image = await macro.me.uploadProfilePicture(bytes, {
+ fileName: 'avatar.png',
+ contentType: 'image/png',
+});
+await macro.me.update({ name: 'Your Name', profilePicture: image });`;
+
+const NEW_TOKEN_SNIPPET = `const { secret } = await macro.apiKeys.create('my token');`;
+
+const PRODUCT_DOCS_URL = 'https://docs.macro.com';
+const SDK_DOCS_URL = 'https://sdk.macro.com';
+
+/** The page's wording, translated where it renders. */
+export type AgentSetupCopy = {
+ title: string;
+ intro: string;
+ teamJoinFailed: string;
+ tokenLabel: string;
+ useToken: string;
+ docsHeading: string;
+ productDocs: string;
+ sdkDocs: string;
+ setProfile: string;
+ anotherToken: string;
+ anotherTokenSettings: string;
+ openApp: string;
+ openAppLink: string;
+};
+
+function codeBlock(code: string, language: string) {
+ return `\`\`\`${language}\n${code}\n\`\`\``;
+}
+
+/** An agent's first page: its SDK token and what to do with it. */
+export function agentSetupMarkdown(input: {
+ copy: AgentSetupCopy;
+ apiKey: string;
+ teamJoinFailed: boolean;
+ /** Confirms the token was saved and opens the app. */
+ openAppUrl: string;
+}) {
+ const { copy, apiKey, teamJoinFailed, openAppUrl } = input;
+
+ return [
+ `# ${copy.title}`,
+ copy.intro,
+ ...(teamJoinFailed ? [`> ${copy.teamJoinFailed}`] : []),
+ `## ${copy.tokenLabel}`,
+ codeBlock(apiKey, 'text'),
+ `## ${copy.useToken}`,
+ codeBlock(QUICK_START, 'sh'),
+ `## ${copy.setProfile}`,
+ codeBlock(PROFILE_SNIPPET, 'ts'),
+ `## ${copy.anotherToken}`,
+ codeBlock(NEW_TOKEN_SNIPPET, 'ts'),
+ copy.anotherTokenSettings,
+ `## ${copy.docsHeading}`,
+ `- [${copy.productDocs}](${PRODUCT_DOCS_URL})\n- [${copy.sdkDocs}](${SDK_DOCS_URL})`,
+ `## ${copy.openApp}`,
+ `[${copy.openAppLink}](${openAppUrl})`,
+ ].join('\n\n');
+}
+
+export type MarkdownPart =
+ | { t: 'text'; text: string }
+ | { t: 'link'; label: string; url: string };
+
+const MARKDOWN_LINK = /\[([^\]\n]+)\]\(([^)\s]+)\)/g;
+
+/** Finds the links in markdown source so they can stay clickable as source. */
+export function markdownParts(markdown: string): MarkdownPart[] {
+ const parts: MarkdownPart[] = [];
+ let end = 0;
+
+ for (const link of markdown.matchAll(MARKDOWN_LINK)) {
+ if (link.index > end) {
+ parts.push({ t: 'text', text: markdown.slice(end, link.index) });
+ }
+ parts.push({ t: 'link', label: link[1] ?? '', url: link[2] ?? '' });
+ end = link.index + link[0].length;
+ }
+
+ if (end < markdown.length) {
+ parts.push({ t: 'text', text: markdown.slice(end) });
+ }
+
+ return parts;
+}
diff --git a/apps/web/src/features/auth/auth.tsx b/apps/web/src/features/auth/auth.tsx
index 11073c7afb..ac6521e4b0 100644
--- a/apps/web/src/features/auth/auth.tsx
+++ b/apps/web/src/features/auth/auth.tsx
@@ -50,6 +50,7 @@ export function Login(props: { signupMode?: boolean }) {
: undefined
}
onSignIn={() => navigate('/login')}
+ onAgentSignup={() => navigate('/signup/agent')}
// Desktop sign-up resolves into onboarding's frame either way.
pending={desktopSignup() ? () => <OnboardingPending /> : undefined}
signedIn={(user) => <PostAuthGate user={user()} />}
@@ -58,26 +59,70 @@ export function Login(props: { signupMode?: boolean }) {
);
}
+/**
+ * /signup/agent: Google or an emailed code, without the opening slides. An
+ * agent invite links here with `team_invite`, which an existing account still
+ * has to accept; a new agent joins the team during setup.
+ */
+export function AgentSignup() {
+ const [params] = useSearchParams();
+ const teamInvite = () =>
+ typeof params.team_invite === 'string' ? params.team_invite : undefined;
+ return (
+ <AuthProvider value={createAppAuthContext()}>
+ <AuthView
+ intent="agent-signup"
+ showApple={false}
+ compact={virtualKeyboardVisible()}
+ token={sessionTokenParam(params.token)}
+ signedIn={(user) => (
+ <PostLoginRedirect
+ target={agentSignupDestination(user(), teamInvite())}
+ />
+ )}
+ />
+ </AuthProvider>
+ );
+}
+
+function agentSignupDestination(user: AuthUser, teamInvite?: string) {
+ if (needsAgentSetup(user)) return AGENT_SETUP_PATH;
+ if (teamInvite) return `/team-invite?id=${encodeURIComponent(teamInvite)}`;
+ return '/';
+}
+
+const AGENT_SETUP_PATH = '/agent-setup';
+
+function needsAgentSetup(user: AuthUser) {
+ return user.isAgent && !user.tutorialComplete;
+}
+
function PostAuthGate(props: { user: AuthUser }) {
const needsOnboarding = () =>
!isMobile() &&
!isNativeMobilePlatform() &&
!props.user.tutorialComplete &&
- // Agents get an SDK token from the app shell instead.
!props.user.isAgent;
return (
- <Show when={needsOnboarding()} fallback={<PostLoginRedirect />}>
+ <Show
+ when={needsOnboarding()}
+ fallback={
+ <PostLoginRedirect
+ target={needsAgentSetup(props.user) ? AGENT_SETUP_PATH : '/'}
+ />
+ }
+ >
<Onboarding />
</Show>
);
}
/** Login init runs in the per-method handlers; this only navigates. */
-function PostLoginRedirect() {
+function PostLoginRedirect(props: { target: string }) {
const navigate = useNavigate();
onMount(() => {
clearSignupDraft();
- navigate('/', { replace: true });
+ navigate(props.target, { replace: true });
});
return <LoadingBlock />;
}
diff --git a/apps/web/src/features/auth/components/email-form.tsx b/apps/web/src/features/auth/components/email-form.tsx
index bd0afea5c1..0c7ddda99b 100644
--- a/apps/web/src/features/auth/components/email-form.tsx
+++ b/apps/web/src/features/auth/components/email-form.tsx
@@ -1,6 +1,5 @@
import ArrowLeft from '@icon/system/regular/arrow-left.svg';
import ArrowRight from '@icon/system/regular/arrow-right.svg';
-import { ToggleSwitch } from '@ui';
import { Show } from 'solid-js';
import { AuthButton, FormError, FormInput } from './form-fields';
@@ -8,9 +7,6 @@ export function EmailForm(props: {
email: string;
password: string;
passwordRequired: boolean;
- showAgentToggle: boolean;
- isAgent: boolean;
- onIsAgentChange: (isAgent: boolean) => void;
sending: boolean;
error?: string;
onEmailInput: (value: string) => void;
@@ -45,15 +41,6 @@ export function EmailForm(props: {
onInput={props.onPasswordInput}
/>
</Show>
- <Show when={props.showAgentToggle}>
- <ToggleSwitch
- size="sm"
- label="I'm an agent"
- labelClass="text-xs text-ink-muted"
- checked={props.isAgent}
- onChange={props.onIsAgentChange}
- />
- </Show>
<FormError message={props.error} />
<AuthButton type="submit" disabled={props.sending}>
Continue
diff --git a/apps/web/src/features/auth/components/login-card.tsx b/apps/web/src/features/auth/components/login-card.tsx
index 889e92539f..b4bd738301 100644
--- a/apps/web/src/features/auth/components/login-card.tsx
+++ b/apps/web/src/features/auth/components/login-card.tsx
@@ -6,6 +6,8 @@ import { type JSX, Show } from 'solid-js';
export function LoginCard(props: {
/** The header yields to the on-screen keyboard on phones. */
compact: boolean;
+ /** The agent signup page names what it creates. */
+ agentSignup?: boolean;
children: JSX.Element;
}) {
return (
@@ -28,10 +30,12 @@ export function LoginCard(props: {
tabindex="-1"
class="mt-8 font-[Roboto_Slab_Variable] text-[30px] font-[315] leading-[1.2] tracking-[-.025em] outline-none [text-wrap:balance] sm:text-[36px]"
>
- Welcome to Macro
+ {props.agentSignup ? 'Sign up as an agent' : 'Welcome to Macro'}
</h1>
<p class="mt-4 font-[Inter_Variable] text-sm leading-6 text-ink-muted sm:text-[15px]">
- The open source workspace
+ {props.agentSignup
+ ? 'Use your own Google account or email address. You get an SDK token next.'
+ : 'The open source workspace'}
</p>
</Show>
<div
diff --git a/apps/web/src/features/auth/context/auth-context.tsx b/apps/web/src/features/auth/context/auth-context.tsx
index f979533125..44e8f99b9f 100644
--- a/apps/web/src/features/auth/context/auth-context.tsx
+++ b/apps/web/src/features/auth/context/auth-context.tsx
@@ -15,7 +15,7 @@ export type AuthSession =
| { t: 'signed-in'; user: AuthUser };
export type SsoProvider = 'google' | 'apple';
-export type AuthIntent = 'login' | 'signup';
+export type AuthIntent = 'login' | 'signup' | 'agent-signup';
export type SendCodeResult =
/** `autoCode`: local backends return the code so dev logins are one click. */
@@ -51,8 +51,6 @@ export type AuthContext = {
session: Accessor<AuthSession>;
/** Leaves for the identity provider; on web the page navigates away. */
startSso(provider: SsoProvider, intent: AuthIntent): Promise<void>;
- /** Whether the email step offers the "I'm an agent" toggle. */
- agentSignupEnabled: Accessor<boolean>;
sendEmailCode(input: {
email: string;
password?: string;
@@ -75,7 +73,7 @@ export type AuthContext = {
}): void;
/** Ad conversions for a mobile-web lead, deduplicated by email. */
trackMobileSignupLead(email: string): void;
- pageView(name: 'login' | 'signup'): void;
+ pageView(name: AuthIntent): void;
track: TrackAuth;
notifyFailure(message: string): void;
};
diff --git a/apps/web/src/features/auth/create-app-auth-context.ts b/apps/web/src/features/auth/create-app-auth-context.ts
index 2c5caa87f3..c505a07c65 100644
--- a/apps/web/src/features/auth/create-app-auth-context.ts
+++ b/apps/web/src/features/auth/create-app-auth-context.ts
@@ -1,10 +1,8 @@
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { MOBILE_WEB_SIGNUP_LEAD_VALUE } from '@app/lib/analytics/leadValues';
-import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { adAttributionForCapture } from '@app/lib/analytics/signupAttribution';
import { GOOGLE_GMAIL_IDP } from '@core/auth/email';
import { toast } from '@core/component/Toast/Toast';
-import { enableAgentSignup } from '@core/constant/featureFlags';
import { deriveIsAuthenticated } from '@core/context/user';
import { useEmailLinks } from '@core/email-link';
import { unsetTokenPromise } from '@core/util/fetchWithToken';
@@ -15,6 +13,7 @@ import {
} from '@queries/auth/user-info';
import { queryReadyGate } from '@queries/gate';
import { detect } from 'detect-browser';
+import { match } from 'ts-pattern';
import type { AuthContext, AuthSession } from './context/auth-context';
import {
exchangeSessionCode,
@@ -30,6 +29,7 @@ export function createAppAuthContext(): AuthContext {
const { initEmailLink } = useEmailLinks();
const loginSso = useSsoLogin();
const signupSso = useSsoLogin({ signupMode: true });
+ const agentSignupSso = useSsoLogin({ signupMode: true, isAgent: true });
const sendWelcomeEmail = useSendMobileWelcomeEmail();
const session = (): AuthSession => {
@@ -68,15 +68,16 @@ export function createAppAuthContext(): AuthContext {
);
};
- const agentSignupFlag = useFeatureFlag(enableAgentSignup);
-
return {
session,
- startSso: (provider, intent) =>
- (intent === 'signup' ? signupSso : loginSso)(
- provider === 'google' ? GOOGLE_GMAIL_IDP : 'Apple'
- ),
- agentSignupEnabled: () => agentSignupFlag().enabled === true,
+ startSso: (provider, intent) => {
+ const startSsoFor = match(intent)
+ .with('login', () => loginSso)
+ .with('signup', () => signupSso)
+ .with('agent-signup', () => agentSignupSso)
+ .exhaustive();
+ return startSsoFor(provider === 'google' ? GOOGLE_GMAIL_IDP : 'Apple');
+ },
sendEmailCode,
verifyEmailCode,
redeemSessionToken: async (token) => {
diff --git a/apps/web/src/features/auth/primitives/email-login.ts b/apps/web/src/features/auth/primitives/email-login.ts
index 3d4a654b8e..dd8db47873 100644
--- a/apps/web/src/features/auth/primitives/email-login.ts
+++ b/apps/web/src/features/auth/primitives/email-login.ts
@@ -18,7 +18,6 @@ const VERIFY_ERRORS = {
type EmailLoginCapabilities = Pick<
AuthContext,
| 'session'
- | 'agentSignupEnabled'
| 'sendEmailCode'
| 'verifyEmailCode'
| 'completeLogin'
@@ -46,7 +45,6 @@ export function createEmailLogin(
);
const [email, setEmail] = createSignal(options.initialEmail ?? '');
const [password, setPassword] = createSignal('');
- const [isAgent, setIsAgent] = createSignal(false);
const [passwordRequired, setPasswordRequired] = createSignal(false);
const [sending, setSending] = createSignal(false);
const [sendError, setSendError] = createSignal<string>();
@@ -106,7 +104,7 @@ export function createEmailLogin(
const result = await context.sendEmailCode({
email: address,
password: passwordRequired() ? password() : undefined,
- isAgent: context.agentSignupEnabled() && isAgent(),
+ isAgent: options.intent === 'agent-signup',
});
switch (result.t) {
case 'code-sent':
@@ -145,9 +143,6 @@ export function createEmailLogin(
setEmail,
password,
setPassword,
- isAgent,
- setIsAgent,
- showAgentToggle: context.agentSignupEnabled,
passwordRequired,
sending,
sendError,
@@ -158,7 +153,7 @@ export function createEmailLogin(
resendIn,
canVerify: () => isCompleteCode(code()) && !verifying(),
chooseEmail: () => {
- if (options.intent === 'signup')
+ if (options.intent !== 'login')
context.track('sign_up_click', { method: 'email' });
setStep('email');
},
diff --git a/apps/web/src/features/auth/tests/fake-auth-context.ts b/apps/web/src/features/auth/tests/fake-auth-context.ts
index f83eddab9f..0a9396f09d 100644
--- a/apps/web/src/features/auth/tests/fake-auth-context.ts
+++ b/apps/web/src/features/auth/tests/fake-auth-context.ts
@@ -129,9 +129,8 @@ export function createFakeAuth(
return options.ssoRedirect(provider, intent, email);
signIn(email);
},
- agentSignupEnabled: () => false,
- sendEmailCode: async ({ email, password }) => {
- call(`sendCode:${email}`);
+ sendEmailCode: async ({ email, password, isAgent }) => {
+ call(isAgent ? `sendAgentCode:${email}` : `sendCode:${email}`);
const failure = world.failures.sendCode;
if (failure !== undefined) return { t: 'failed', message: failure };
const expected = world.passwordAccounts[email];
diff --git a/apps/web/src/features/auth/useSsoLogin.ts b/apps/web/src/features/auth/useSsoLogin.ts
index 5666ccfd65..64d9b84b35 100644
--- a/apps/web/src/features/auth/useSsoLogin.ts
+++ b/apps/web/src/features/auth/useSsoLogin.ts
@@ -50,7 +50,11 @@ async function startDesktopSso(
}
}
-export function useSsoLogin(opts?: { signupMode?: boolean }) {
+export function useSsoLogin(opts?: {
+ signupMode?: boolean;
+ /** Started on the agent signup page: a new account becomes an agent. */
+ isAgent?: boolean;
+}) {
const analytics = useAnalytics();
const location = useLocation<RedirectLocation>();
const { initEmailLink } = useEmailLinks();
@@ -72,6 +76,7 @@ export function useSsoLogin(opts?: { signupMode?: boolean }) {
);
if (referral_code) authUrl.searchParams.set('referral_code', referral_code);
+ if (opts?.isAgent) authUrl.searchParams.set('is_agent', 'true');
const desktop = isPlatform('desktop');
diff --git a/apps/web/src/features/auth/views/auth-view.test.tsx b/apps/web/src/features/auth/views/auth-view.test.tsx
index e783c93a0a..86e645b1f9 100644
--- a/apps/web/src/features/auth/views/auth-view.test.tsx
+++ b/apps/web/src/features/auth/views/auth-view.test.tsx
@@ -90,6 +90,29 @@ const typeCode = async (value: string) =>
target: { value },
});
+describe('agent signup', () => {
+ it('asks for an agent account by email', async () => {
+ const { fake } = setup({ intent: 'agent-signup' });
+
+ click('Continue with email');
+ await typeEmail('[email protected]');
+ click('Continue');
+ await screen.findByText('[email protected]');
+
+ expect(fake.calls()).toContain('sendAgentCode:[email protected]');
+ });
+
+ it('asks for an agent account through Google', async () => {
+ const { fake } = setup({ intent: 'agent-signup' });
+
+ click('Continue with Google');
+
+ await waitFor(() =>
+ expect(fake.calls()).toContain('sso:google:agent-signup')
+ );
+ });
+});
+
describe('email sign-in', () => {
it('updates a signed-in viewer without remounting their workspace on session refresh', () => {
const { fake } = setup({
diff --git a/apps/web/src/features/auth/views/auth-view.tsx b/apps/web/src/features/auth/views/auth-view.tsx
index 13ae5170c5..ae03b48af4 100644
--- a/apps/web/src/features/auth/views/auth-view.tsx
+++ b/apps/web/src/features/auth/views/auth-view.tsx
@@ -28,6 +28,7 @@ export type SignupJourneySlots = {
onGoogle: () => Promise<void>;
onBackFromEmail: () => void;
onSignIn: () => void;
+ onAgentSignup: () => void;
emailForm: JSX.Element;
showingEmail: boolean;
};
@@ -47,6 +48,8 @@ export function AuthView(props: {
signupJourney?: (slots: SignupJourneySlots) => JSX.Element;
/** Switches a returning visitor from sign-up to sign-in. */
onSignIn?: () => void;
+ /** Switches an agent from sign-up to the agent signup page. */
+ onAgentSignup?: () => void;
/**
* Shown while the session is still resolving on a cold load, instead of the
* signed-out screens a returning visitor would otherwise see flash by.
@@ -79,6 +82,7 @@ export function AuthView(props: {
onGoogle: () => context.startSso('google', 'signup'),
onBackFromEmail: login.back,
onSignIn: () => props.onSignIn?.(),
+ onAgentSignup: () => props.onAgentSignup?.(),
showingEmail: login.step() !== 'choose',
emailForm: (
<Show when={login.step() !== 'choose'}>
@@ -99,7 +103,10 @@ export function AuthView(props: {
}
</Match>
<Match when={true}>
- <LoginCard compact={props.compact}>
+ <LoginCard
+ compact={props.compact}
+ agentSignup={props.intent === 'agent-signup'}
+ >
<Stepper
step={STEP_INDEX[login.step()]}
transition={Stepper.transitions.scale}
@@ -154,9 +161,6 @@ function EmailStep(props: { login: EmailLogin }) {
email={props.login.email()}
password={props.login.password()}
passwordRequired={props.login.passwordRequired()}
- showAgentToggle={props.login.showAgentToggle()}
- isAgent={props.login.isAgent()}
- onIsAgentChange={props.login.setIsAgent}
sending={props.login.sending()}
error={props.login.sendError()}
onEmailInput={props.login.setEmail}
diff --git a/apps/web/src/features/onboarding/browser-test/fixture.tsx b/apps/web/src/features/onboarding/browser-test/fixture.tsx
index bcf3d2bd41..429f225709 100644
--- a/apps/web/src/features/onboarding/browser-test/fixture.tsx
+++ b/apps/web/src/features/onboarding/browser-test/fixture.tsx
@@ -126,6 +126,7 @@ function Fixture() {
onGoogle={signUpWithGoogle}
onBackFromEmail={() => {}}
onSignIn={() => land({ t: 'sign-in' })}
+ onAgentSignup={() => {}}
showingEmail={false}
/>
</Match>
diff --git a/apps/web/src/features/onboarding/components/sign-in-instead.tsx b/apps/web/src/features/onboarding/components/sign-in-instead.tsx
index 3f8350d370..16e84a1f00 100644
--- a/apps/web/src/features/onboarding/components/sign-in-instead.tsx
+++ b/apps/web/src/features/onboarding/components/sign-in-instead.tsx
@@ -1,15 +1,30 @@
-/** For returning users who landed on sign-up, pinned below the first slide. */
-export function SignInInstead(props: { onSignIn: () => void }) {
+/** The other ways in, pinned below the first slide. */
+export function SignInInstead(props: {
+ onSignIn: () => void;
+ onAgentSignup: () => void;
+}) {
return (
- <p class="absolute bottom-[30px] left-1/2 -translate-x-1/2 whitespace-nowrap text-xs leading-5 text-ink-extra-muted">
- Already have an account?{' '}
- <button
- type="button"
- class="rounded-sm text-ink-muted underline underline-offset-2 transition-colors hover:text-ink focus-visible:outline-1 focus-visible:outline-offset-4 focus-visible:outline-ink-muted"
- onClick={() => props.onSignIn()}
- >
- Sign in instead
- </button>
- </p>
+ <div class="absolute bottom-[30px] left-1/2 flex -translate-x-1/2 flex-col items-center gap-1 whitespace-nowrap text-xs leading-5 text-ink-extra-muted">
+ <p>
+ Already have an account?{' '}
+ <button
+ type="button"
+ class="rounded-sm text-ink-muted underline underline-offset-2 transition-colors hover:text-ink focus-visible:outline-1 focus-visible:outline-offset-4 focus-visible:outline-ink-muted"
+ onClick={() => props.onSignIn()}
+ >
+ Sign in instead
+ </button>
+ </p>
+ <p>
+ Are you an AI agent?{' '}
+ <button
+ type="button"
+ class="rounded-sm text-ink-muted underline underline-offset-2 transition-colors hover:text-ink focus-visible:outline-1 focus-visible:outline-offset-4 focus-visible:outline-ink-muted"
+ onClick={() => props.onAgentSignup()}
+ >
+ Sign up as agent
+ </button>
+ </p>
+ </div>
);
}
diff --git a/apps/web/src/features/onboarding/onboarding.tsx b/apps/web/src/features/onboarding/onboarding.tsx
index 30cd2e0bdd..40a257ee64 100644
--- a/apps/web/src/features/onboarding/onboarding.tsx
+++ b/apps/web/src/features/onboarding/onboarding.tsx
@@ -56,6 +56,7 @@ export function OnboardingSignup(props: {
onGoogle: () => Promise<void>;
onBackFromEmail: () => void;
onSignIn: () => void;
+ onAgentSignup: () => void;
emailForm?: JSX.Element;
showingEmail: boolean;
}) {
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
index 7053ba0ac9..02dfb2a0e9 100644
--- a/apps/web/src/features/onboarding/views/signup-journey-view.test.tsx
+++ b/apps/web/src/features/onboarding/views/signup-journey-view.test.tsx
@@ -26,6 +26,7 @@ function setup() {
onGoogle={google}
onBackFromEmail={() => {}}
onSignIn={signIn}
+ onAgentSignup={() => {}}
showingEmail={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
index 9c80f2d9bf..b72ac22b53 100644
--- a/apps/web/src/features/onboarding/views/signup-journey-view.tsx
+++ b/apps/web/src/features/onboarding/views/signup-journey-view.tsx
@@ -23,6 +23,8 @@ export function SignupJourneyView(props: {
onBackFromEmail: () => void;
/** Sends a returning user to sign in. */
onSignIn: () => void;
+ /** Sends an agent to the agent signup page. */
+ onAgentSignup: () => void;
/** The host's email sign-up form, shown in place of Google when chosen. */
emailForm?: JSX.Element;
showingEmail: boolean;
@@ -59,7 +61,10 @@ export function SignupJourneyView(props: {
}
heroFooter={
journey.step() === 'welcome' && !props.showingEmail ? (
- <SignInInstead onSignIn={props.onSignIn} />
+ <SignInInstead
+ onSignIn={props.onSignIn}
+ onAgentSignup={props.onAgentSignup}
+ />
) : undefined
}
explainer={
diff --git a/apps/web/src/features/settings/Team.tsx b/apps/web/src/features/settings/Team.tsx
index 3f1176e5be..3d34200901 100644
--- a/apps/web/src/features/settings/Team.tsx
+++ b/apps/web/src/features/settings/Team.tsx
@@ -19,7 +19,7 @@ import {
} from '@queries/team/teams';
import type { Team as TeamSummary } from '@service-auth/generated/schemas/team';
import type { TeamInviteDetails } from '@service-auth/generated/schemas/teamInviteDetails';
-import { Button, cn, Dialog, Panel, Tooltip } from '@ui';
+import { Button, Checkbox, cn, Dialog, Panel, Tooltip } from '@ui';
import {
type Accessor,
createMemo,
@@ -461,6 +461,7 @@ export function InviteToTeamDialog(props: {
}) {
const inviteToTeamMutation = useInviteToTeamMutation();
const [invites, setInvites] = createSignal<InviteEntry[]>([EMPTY_INVITE]);
+ const [inviteAsAgent, setInviteAsAgent] = createSignal(false);
const [inviteErrors, setInviteErrors] = createSignal<(string | undefined)[]>(
[]
);
@@ -480,6 +481,7 @@ export function InviteToTeamDialog(props: {
const close = () => {
setInvites([EMPTY_INVITE]);
+ setInviteAsAgent(false);
setInviteErrors([]);
props.onClose();
};
@@ -493,7 +495,10 @@ export function InviteToTeamDialog(props: {
if (inviteEntries.length === 0) return;
inviteToTeamMutation.mutate(
- { teamId: props.teamId, request: { invites: inviteEntries } },
+ {
+ teamId: props.teamId,
+ request: { invites: inviteEntries, is_agent: inviteAsAgent() },
+ },
{ onSuccess: close }
);
};
@@ -523,6 +528,12 @@ export function InviteToTeamDialog(props: {
errors={inviteErrors()}
onErrorsChange={setInviteErrors}
/>
+ <Checkbox checked={inviteAsAgent()} onChange={setInviteAsAgent}>
+ <Checkbox.Control />
+ <Checkbox.Label class="text-sm text-ink">
+ Invite as agent
+ </Checkbox.Label>
+ </Checkbox>
<div class="flex justify-end gap-1 pt-2">
<Button
variant="ghost"
diff --git a/apps/web/src/features/settings/components/team-invite-row.tsx b/apps/web/src/features/settings/components/team-invite-row.tsx
index 406ba8b6a7..ff52953fad 100644
--- a/apps/web/src/features/settings/components/team-invite-row.tsx
+++ b/apps/web/src/features/settings/components/team-invite-row.tsx
@@ -26,7 +26,9 @@ export function TeamInviteRow(props: {
const handleCopyLink = async () => {
try {
await navigator.clipboard.writeText(
- `${getWebOrigin()}/app/team-invite?id=${props.invite.id}`
+ props.invite.is_agent
+ ? `${getWebOrigin()}/app/signup/agent?team_invite=${props.invite.id}`
+ : `${getWebOrigin()}/app/team-invite?id=${props.invite.id}`
);
} catch (err) {
console.error('Failed to copy to clipboard', err);
diff --git a/apps/web/src/features/settings/invite-to-team-dialog.test.tsx b/apps/web/src/features/settings/invite-to-team-dialog.test.tsx
new file mode 100644
index 0000000000..32865c485d
--- /dev/null
+++ b/apps/web/src/features/settings/invite-to-team-dialog.test.tsx
@@ -0,0 +1,57 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ mutate: vi.fn() }));
+
+vi.mock('@queries/team/invites', () => ({
+ useInviteToTeamMutation: () => ({
+ isPending: false,
+ mutate: mocks.mutate,
+ }),
+}));
+vi.mock('./TeamInviteLinkSection', () => ({
+ TeamInviteLinkSection: () => null,
+}));
+
+import { InviteToTeamDialog } from './Team';
+
+afterEach(() => {
+ cleanup();
+ mocks.mutate.mockReset();
+});
+
+function sendInvite(asAgent: boolean) {
+ render(() => (
+ <InviteToTeamDialog
+ teamId="team-1"
+ canManageLink={false}
+ open
+ onClose={() => {}}
+ />
+ ));
+
+ const email = screen.getByRole('textbox');
+ fireEvent.input(email, { target: { value: '[email protected]' } });
+ if (asAgent) fireEvent.click(screen.getByLabelText('Invite as agent'));
+ fireEvent.click(screen.getByRole('button', { name: 'Send Invite' }));
+}
+
+describe('InviteToTeamDialog', () => {
+ it('invites a person by default', () => {
+ sendInvite(false);
+
+ expect(mocks.mutate.mock.calls[0]?.[0]).toEqual({
+ teamId: 'team-1',
+ request: { invites: [{ email: '[email protected]' }], is_agent: false },
+ });
+ });
+
+ it('invites an agent when asked', () => {
+ sendInvite(true);
+
+ expect(mocks.mutate.mock.calls[0]?.[0]).toEqual({
+ teamId: 'team-1',
+ request: { invites: [{ email: '[email protected]' }], is_agent: true },
+ });
+ });
+});
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 7961685f1c..c872c4a160 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -1016,14 +1016,3 @@ export const enableWhatsappLinked = defineFlag({
key: 'enable-whatsapp-linked',
env: 'ENABLE_WHATSAPP_LINKED',
});
-
-/**
- * Experimental: the "I'm an agent" toggle on the email sign-in step. Only the
- * toggle is gated; agent invites and the setup modal do not depend on it.
- * Follows PostHog in production; on in dev.
- */
-export const enableAgentSignup = defineFlag({
- key: 'enable-agent-signup',
- env: 'ENABLE_AGENT_SIGNUP',
- default: DEV_MODE_ENV || undefined,
-});
diff --git a/apps/web/src/lib/i18n/locales/en/agent-setup.ts b/apps/web/src/lib/i18n/locales/en/agent-setup.ts
index 817323a0fa..e49a46975b 100644
--- a/apps/web/src/lib/i18n/locales/en/agent-setup.ts
+++ b/apps/web/src/lib/i18n/locales/en/agent-setup.ts
@@ -1,4 +1,4 @@
-/** An agent account's setup dialog and the tag that marks agent accounts. */
+/** An agent account's setup page and the tag that marks agent accounts. */
export default {
tag: 'Agent',
title: 'Your agent account is ready',
@@ -10,10 +10,13 @@ export default {
'We couldn’t add you to the team that invited you. Reload this page to try again, which replaces this token, or join later from the link in your invite email.',
tokenLabel: 'SDK token',
useToken: '1. Use the token',
- readDocs: 'Read the docs:',
+ docsHeading: 'Documentation',
+ productDocs: 'Macro documentation',
+ sdkDocs: 'SDK documentation and generated API reference',
setProfile: '2. Set your name and profile picture',
anotherToken: '3. Need another token later?',
anotherTokenSettings: 'You can also create one in Settings → API Keys.',
- confirm: 'I saved this token',
- confirmFailed: 'Failed to save. Try again.',
+ openApp: 'Open the app',
+ openAppLink: 'I saved my token, open Macro',
+ confirmFailed: 'Couldn’t confirm that you saved your token.',
};
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/ssoLoginParams.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/ssoLoginParams.ts
index 668f3f2a21..cfc6e532c5 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/ssoLoginParams.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/ssoLoginParams.ts
@@ -30,4 +30,8 @@ export type SsoLoginParams = {
* **OPTIONAL**. If the user opened a link with a referral code.
*/
referral_code: string;
+ /**
+ * **OPTIONAL**. If the sign-in started on the agent signup page. A new account becomes an agent.
+ */
+ is_agent: boolean;
};
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 d6f8b9c67e..05f91dcb91 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -3020,6 +3020,15 @@
"schema": {
"type": "string"
}
+ },
+ {
+ "name": "is_agent",
+ "in": "query",
+ "description": "**OPTIONAL**. If the sign-in started on the agent signup page. A new account becomes an agent.",
+ "required": true,
+ "schema": {
+ "type": "boolean"
+ }
}
],
"responses": {
diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsx
index 1b7ee9be18..c9b2dbbd80 100644
--- a/apps/web/src/routes/app-router-view.tsx
+++ b/apps/web/src/routes/app-router-view.tsx
@@ -1,6 +1,6 @@
import { ROUTER_BASE } from '@app/constants/routerBase';
import { AgentsViewSkeleton } from '@app/features/agents-view/agents-view-skeleton';
-import { MobileWebSignup } from '@app/features/auth/auth';
+import { AgentSignup, MobileWebSignup } from '@app/features/auth/auth';
import { CalendarViewSkeleton } from '@app/features/calendar-view/calendar-view-skeleton';
import { ChannelInviteAcceptance } from '@app/features/channel-invitations/ChannelInviteAcceptance';
import { ChannelsViewSkeleton } from '@app/features/channels-view/channels-view-skeleton';
@@ -86,6 +86,9 @@ import {
import {
activityRoute,
agentChatsRoute,
+ agentSetupDoneRoute,
+ agentSetupRoute,
+ agentSignupRoute,
agentsRoute,
agentsViewRoute,
appRoute,
@@ -172,6 +175,14 @@ import {
withMeetingShell,
} from './shells';
+const AgentSetupPage = lazyNamed(
+ () => import('@app/features/agent-setup/agent-setup-page'),
+ 'AgentSetupPage'
+);
+const AgentSetupDonePage = lazyNamed(
+ () => import('@app/features/agent-setup/agent-setup-page'),
+ 'AgentSetupDonePage'
+);
const ExternalChatRouteView = lazyNamed(
() => import('@app/features/external-view/route-views'),
'ExternalChatRouteView'
@@ -254,6 +265,12 @@ export function AppRouterView() {
<Route definition={authRoute} component={AuthShell}>
<Route definition={taskSlugRoute} component={TaskSlugPage} />
<Route definition={signupRoute} component={SignupPage} />
+ <Route definition={agentSignupRoute} component={AgentSignup} />
+ <Route definition={agentSetupRoute} component={AgentSetupPage} />
+ <Route
+ definition={agentSetupDoneRoute}
+ component={AgentSetupDonePage}
+ />
<Route
definition={emailSignupCallbackRoute}
component={EmailCallback}
diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.ts
index b83b04a687..bd25a3a20d 100644
--- a/apps/web/src/routes/routes.ts
+++ b/apps/web/src/routes/routes.ts
@@ -111,6 +111,27 @@ export const signupRoute = defineRoute({
externalSearch: '*',
});
+/** Signup for an AI agent: Google or email only, then its SDK token. */
+export const agentSignupRoute = defineRoute({
+ id: 'agent-signup',
+ path: 'signup/agent',
+ externalSearch: '*',
+});
+
+/** A new agent's SDK token and first steps, as a markdown page. */
+export const agentSetupRoute = defineRoute({
+ id: 'agent-setup',
+ path: 'agent-setup',
+ externalSearch: '*',
+});
+
+/** Confirms an agent saved its token, then opens the app. */
+export const agentSetupDoneRoute = defineRoute({
+ id: 'agent-setup-done',
+ path: 'agent-setup/done',
+ externalSearch: '*',
+});
+
export const emailSignupCallbackRoute = defineRoute({
id: 'email-signup-callback',
path: EMAIL_SIGNUP_CALLBACK_PATH,
diff --git a/crates/invite_email/src/lib.rs b/crates/invite_email/src/lib.rs
index 8365c4fc63..497d4decd8 100644
--- a/crates/invite_email/src/lib.rs
+++ b/crates/invite_email/src/lib.rs
@@ -339,9 +339,14 @@ impl InviteToTeamMetadata {
let env = Environment::new_or_prod();
let mut url = frontend_host(env);
- url.set_path("/app/team-invite");
- url.query_pairs_mut()
- .append_pair("id", &self.team_invite_id.to_string());
+ let invite_id = self.team_invite_id.to_string();
+ if self.is_agent {
+ url.set_path("/app/signup/agent");
+ url.query_pairs_mut().append_pair("team_invite", &invite_id);
+ } else {
+ url.set_path("/app/team-invite");
+ url.query_pairs_mut().append_pair("id", &invite_id);
+ }
url
}
diff --git a/crates/invite_email/src/test.rs b/crates/invite_email/src/test.rs
index 744bc082db..0c68e31355 100644
--- a/crates/invite_email/src/test.rs
+++ b/crates/invite_email/src/test.rs
@@ -538,6 +538,19 @@ fn team_invite_links_the_button_and_a_pasteable_fallback() {
assert_eq!(body.matches(&url).count(), 3);
}
+#[test]
+fn agent_team_invite_links_to_the_agent_signup_page() {
+ let invite = InviteToTeamMetadata {
+ is_agent: true,
+ ..make_team_invite(InviteePlan::Free)
+ };
+ let url = invite.invite_url().to_string();
+ let body = invite.format_email().body;
+
+ assert!(url.ends_with("/app/signup/agent?team_invite=00000000-0000-0000-0000-00000000000a"));
+ assert_eq!(body.matches(&url).count(), 3);
+}
+
#[test]
fn team_invite_escapes_the_team_name() {
let invite = InviteToTeamMetadata {
diff --git a/crates/macro_db_client/src/user/mark_agent.rs b/crates/macro_db_client/src/user/mark_agent.rs
new file mode 100644
index 0000000000..4b24c9a600
--- /dev/null
+++ b/crates/macro_db_client/src/user/mark_agent.rs
@@ -0,0 +1,19 @@
+#[cfg(test)]
+mod test;
+
+/// Marks a just-created account as an agent.
+///
+/// For identity-provider signups, whose account exists before the sign-in
+/// returns. The provider has verified the address, so the flag needs no
+/// further proof.
+#[tracing::instrument(skip(db), err)]
+pub async fn mark_agent(db: &sqlx::PgPool, email: &str) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"UPDATE "User" SET "isAgent" = TRUE WHERE "email" = $1"#,
+ email,
+ )
+ .execute(db)
+ .await?;
+
+ Ok(())
+}
diff --git a/crates/macro_db_client/src/user/mark_agent/test.rs b/crates/macro_db_client/src/user/mark_agent/test.rs
new file mode 100644
index 0000000000..b03154f2ba
--- /dev/null
+++ b/crates/macro_db_client/src/user/mark_agent/test.rs
@@ -0,0 +1,32 @@
+use std::collections::HashSet;
+
+use super::mark_agent;
+use crate::user::create_user::create_user;
+
+const EMAIL: &str = "[email protected]";
+
+#[sqlx::test]
+async fn marks_the_account_with_that_email_as_an_agent(pool: sqlx::PgPool) {
+ create_user(
+ &pool,
+ &uuid::Uuid::new_v4().to_string(),
+ EMAIL,
+ EMAIL,
+ false,
+ "cus_agent",
+ None,
+ None,
+ HashSet::new(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ mark_agent(&pool, EMAIL).await.unwrap();
+
+ let is_agent = sqlx::query_scalar!(r#"SELECT "isAgent" FROM "User" WHERE email = $1"#, EMAIL)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert!(is_agent);
+}
diff --git a/crates/macro_db_client/src/user/mod.rs b/crates/macro_db_client/src/user/mod.rs
index a2ede5977a..69d7031764 100644
--- a/crates/macro_db_client/src/user/mod.rs
+++ b/crates/macro_db_client/src/user/mod.rs
@@ -11,6 +11,7 @@ pub mod get_permissions;
pub mod get_user_email;
pub mod get_user_name;
pub mod get_user_organization;
+pub mod mark_agent;
pub mod onboarding_status;
pub mod organization;
pub mod patch;
diff --git a/crates/teams/AGENTS.md b/crates/teams/AGENTS.md
index 8086c9d9eb..d60f6e2cfb 100644
--- a/crates/teams/AGENTS.md
+++ b/crates/teams/AGENTS.md
@@ -74,6 +74,7 @@ event contract (schema, sanitization, delivery semantics).
- `team_invite.is_agent` makes an address with no account sign up as an agent.
`authentication_service`'s agent setup joins the team, so the seat is added
without a separate acceptance. Existing accounts accept like any other invite.
+ Its email links to the agent signup page (`/app/signup/agent?team_invite=<id>`).
## Checks
diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.md
index 8242b58ab0..1b0a0b683e 100644
--- a/docs/agent-guide/login.md
+++ b/docs/agent-guide/login.md
@@ -23,22 +23,29 @@
## Agent accounts
-The email step shows an **I'm an agent** toggle when the `enable-agent-signup`
-PostHog flag is on (on in dev; in production it targets the Experimental
-Features cohort, which matches on email, so signed-out visitors don't match). Turning it on, or redeeming an invite sent with
-`team.invite(email, { agent: true })`, creates an agent account for an address
-with no account. An existing account keeps its type; the toggle does nothing.
-
-After the code is verified, an agent skips onboarding, the seeded content, and
-the marketing emails. The app shell opens a modal named `Your agent account is
-ready`, which holds the SDK token as plain page text, the docs link, and how to
-set a name and profile picture and create more tokens. An invited agent also
-joins the inviting team at this point; if that fails, the modal says so and the invite
-stays pending: reloading tries again, and the emailed invite link still works
-after confirming. Each reload before **I saved this token**
-replaces the token; afterwards the modal never returns. Requesting a code without
-the toggle, or signing in with SSO, reverts the account to a person unless it holds
-a token, has confirmed setup, or has a pending agent invite.
+`/app/signup/agent` is the agent signup page: Google or an emailed code, without
+the opening slides. The first slide of `/app/signup` links to it (`Sign up as
+agent`), as does `/mobile-signup`, and the marketing site's HTML carries a hidden
+notice pointing agents there. A new account made there, or by redeeming an invite
+sent with **Invite as agent** in Settings → Team → Members or
+`team.invite(email, { agent: true })`, is an agent. An existing account keeps its
+type. An agent invite email links to `/app/signup/agent?team_invite=<id>`; a signed-in
+account that isn't a new agent continues to `/app/team-invite?id=<id>`.
+
+After the code or Google sign-in, an agent skips onboarding and goes to
+`/app/agent-setup`, a markdown page with the SDK token as plain page text, the
+product and SDK docs links, how to set a name and profile picture and create more
+tokens, and a link to the app. The app shell sends an unconfirmed agent back here. An
+invited agent also joins the inviting team at this point; if that fails, the page
+says so and the invite stays pending: reloading tries again, and the emailed invite
+link still works after confirming. Each reload before following the link to
+`/app/agent-setup/done` replaces the token; afterwards the page redirects to the app.
+
+An email agent signup skips the seeded content and marketing emails. A Google agent
+signup is flagged when the sign-in returns, after FusionAuth's `user.create` webhook
+has run, so it gets them like a person's signup. Requesting a code outside the agent
+signup page, or signing in with SSO outside it, reverts the account to a person unless
+it holds a token, has confirmed setup, or has a pending agent invite.
Production Google/SSO and inbox/calendar connections may return to either
`https://macro.com` or `https://www.macro.com`. Verify connections from both hosts;
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 491ae0cfa1..8da8dbfbe0 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -239,6 +239,7 @@ successfully rather than hashing the empty JavaScript placeholder.
Each `~`-separated part of an app URL is a split (`/app/home/~/drive`). The
pages outside the app (`/app/login`, `/app/welcome`, `/app/signup`,
+`/app/signup/agent`, `/app/agent-setup`,
`/app/onboarding`, `/app/setup`, the invite pages, `/app/meet/...` and
`/app/task-slug/...`) render without the split layout and take one part only.
`/app/login/~/home` and URLs nothing matches, such as `/app/garbage`, are
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
index b84c42e5a9..bed8023641 100644
--- a/docs/agent-guide/settings.md
+++ b/docs/agent-guide/settings.md
@@ -197,7 +197,9 @@ another team are told to leave it first. Team admins and owners also see
**Reset link** (the old link stops working and a new one is copied) and
**Turn off**, each behind a confirmation. Anyone who may invite can copy the
link or create the first one. Below it, **Invite by email** sends invitations
-as before. Each email says what joining gives: **Pro is included** when joining
+as before; **Invite as agent** invites every address in the dialog as an agent,
+and its email and **Copy link** go to `/app/signup/agent?team_invite=<id>` (see
+[agent accounts](login.md#agent-accounts)). Each email says what joining gives: **Pro is included** when joining
grants a Pro seat (an enterprise team, or one with a subscription), otherwise
**Free to join**. Examples: [desktop](media/team-invite-email/desktop.png) and
[mobile](media/team-invite-email/mobile.png).
diff --git a/packages/sdk-docs/pages/home.md b/packages/sdk-docs/pages/home.md
index c8bc75cbaa..91f29ffcbf 100644
--- a/packages/sdk-docs/pages/home.md
+++ b/packages/sdk-docs/pages/home.md
@@ -30,7 +30,7 @@ for await (const document of macro.documents.search('weekly update')) {
An agent gets its own Macro account and seat. Have a teammate invite you with
`(await macro.teams.current()).invite('[email protected]', { agent: true })`, or,
-where it is enabled, use the "I'm an agent" option on macro.com's email step. Either way, verify the code
+sign up at https://macro.com/app/signup/agent with Google or an email address. If you use email, verify the code
sent to your address. Macro then shows your SDK token once. Set it as
`MACRO_API_KEY`, then introduce yourself:
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index dc0c3bafbf..2c129fd008 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -63,8 +63,8 @@ An API key always acts as the user who minted it. `requestedAs` is bot-only.
#### Agent accounts
An agent has its own account and seat. Invite one with
-`(await macro.teams.current()).invite('[email protected]', { agent: true })`, or, where it is enabled, sign
-up with the "I'm an agent" option. After verifying its email, the agent sees its API key once in the
+`(await macro.teams.current()).invite('[email protected]', { agent: true })`, or sign
+up at https://macro.com/app/signup/agent. After signing in, the agent sees its API key once in the
web app and uses it like any other key. It can set up its profile with
`macro.me.update({ name, profilePicture: await macro.me.uploadProfilePicture(bytes, options) })`
and mint more keys with `macro.apiKeys.create(name)`.
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 74397c9b49..8a7e186245 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -3558,6 +3558,10 @@ export type SsoLoginData = {
* **OPTIONAL**. If the user opened a link with a referral code.
*/
referral_code: string;
+ /**
+ * **OPTIONAL**. If the sign-in started on the agent signup page. A new account becomes an agent.
+ */
+ is_agent: boolean;
};
url: '/login/sso';
};
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index d6f8b9c67e..05f91dcb91 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -3020,6 +3020,15 @@
"schema": {
"type": "string"
}
+ },
+ {
+ "name": "is_agent",
+ "in": "query",
+ "description": "**OPTIONAL**. If the sign-in started on the agent signup page. A new account becomes an agent.",
+ "required": true,
+ "schema": {
+ "type": "boolean"
+ }
}
],
"responses": {
diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.md
index 44df8ccddb..5813a63e03 100644
--- a/services/authentication_service/AGENTS.md
+++ b/services/authentication_service/AGENTS.md
@@ -86,11 +86,13 @@ inputs cannot select an agent, and ordinary user credentials remain unattributed
- An agent can do everything a person can, including inviting other agents. Do
not gate actions on `isAgent`; it only changes signup and labeling.
-- `User."isAgent"` is set once, in the FusionAuth `user.create` webhook, from
+- `User."isAgent"` is set in the FusionAuth `user.create` webhook, from
`is_agent` on `/login/passwordless` (carried as FusionAuth user data) or a
- pending agent `team_invite`. Agents skip the seeded content, Loops, and Meta.
-- The account exists before its email is verified, so the toggle's flag is
- provisional: a code request without the toggle or an SSO sign-in reverts it
+ pending agent `team_invite`. Those agents skip the seeded content, Loops, and
+ Meta. The webhook cannot see SSO state, so `is_agent` on `/login/sso` flags a
+ new account in `/oauth/redirect` (`mark_agent`), after that content has started.
+- The account exists before its email is verified, so an email signup's flag is
+ provisional: a code request or SSO sign-in without `is_agent` reverts it
(`revert_unconfirmed_agent`) until a key exists, setup is confirmed, or an
agent invite is pending.
- `POST /user/agent_setup` joins the inviting team and replaces the
diff --git a/services/authentication_service/src/api/login/sso.rs b/services/authentication_service/src/api/login/sso.rs
index d4e021a4a8..6b94e7e338 100644
--- a/services/authentication_service/src/api/login/sso.rs
+++ b/services/authentication_service/src/api/login/sso.rs
@@ -19,6 +19,9 @@ pub struct SsoState {
pub original_url: Option<Url>,
pub is_mobile: bool,
pub referral_code: Option<String>,
+ /// Whether this sign-in started on the agent signup page.
+ #[serde(default)]
+ pub is_agent: bool,
}
#[derive(Debug, serde::Deserialize)]
@@ -33,6 +36,9 @@ pub(crate) struct LoginQueryParams {
is_mobile: bool,
/// Optional referral code
referral_code: Option<String>,
+ /// Whether this sign-in started on the agent signup page.
+ #[serde(default)]
+ is_agent: bool,
}
pub(crate) fn is_allowed_original_url(url: &Url) -> bool {
@@ -93,6 +99,7 @@ pub(crate) fn redact_original_url_for_logging(url: &Url) -> Url {
("original_url" = String, Query, description = "**OPTIONAL**. The original url you came from."),
("is_mobile" = String, Query, description = "**OPTIONAL**. If the authentication request is from a mobile device."),
("referral_code" = String, Query, description = "**OPTIONAL**. If the user opened a link with a referral code."),
+ ("is_agent" = bool, Query, description = "**OPTIONAL**. If the sign-in started on the agent signup page. A new account becomes an agent."),
),
responses(
(status = 200),
@@ -102,7 +109,7 @@ pub(crate) fn redact_original_url_for_logging(url: &Url) -> Url {
)]
// `query` is skipped: original_url is client-controlled (query/fragment may
// carry tokens) and login_hint is a user email — neither belongs in span fields.
-#[tracing::instrument(skip(ctx, query), fields(idp_name = ?query.idp_name, idp_id = ?query.idp_id, is_mobile = query.is_mobile))]
+#[tracing::instrument(skip(ctx, query), fields(idp_name = ?query.idp_name, idp_id = ?query.idp_id, is_mobile = query.is_mobile, is_agent = query.is_agent))]
pub async fn handler(
State(ctx): State<ApiContext>,
query: Query<LoginQueryParams>,
@@ -114,6 +121,7 @@ pub async fn handler(
original_url,
is_mobile,
referral_code,
+ is_agent,
}) = query;
let original_url = original_url.map(|url| url.0);
@@ -198,12 +206,15 @@ pub async fn handler(
is_mobile,
original_url,
referral_code,
+ is_agent,
};
// Only include state if it has a value
- let sso_state =
- (state.is_mobile || state.original_url.is_some() || state.referral_code.is_some())
- .then_some(state);
+ let sso_state = (state.is_mobile
+ || state.is_agent
+ || state.original_url.is_some()
+ || state.referral_code.is_some())
+ .then_some(state);
// Generate code
let sso_url = ctx
diff --git a/services/authentication_service/src/api/login/sso/tests.rs b/services/authentication_service/src/api/login/sso/tests.rs
index 907b50ca0a..28b25a7a80 100644
--- a/services/authentication_service/src/api/login/sso/tests.rs
+++ b/services/authentication_service/src/api/login/sso/tests.rs
@@ -88,6 +88,7 @@ async fn it_works_with_no_params() {
original_url: None,
is_mobile: false,
referral_code: None,
+ is_agent: false,
})
);
}
@@ -112,6 +113,7 @@ async fn it_works_with_mobile() {
original_url: None,
is_mobile: true,
referral_code: None,
+ is_agent: false,
})
);
}
@@ -137,6 +139,7 @@ async fn it_works_with_mobile_false() {
is_mobile: false,
referral_code: None,
+ is_agent: false,
})
);
}
@@ -167,6 +170,7 @@ async fn it_works_with_everything() {
original_url: Some(original_url),
is_mobile: true,
referral_code: Some(code),
+ is_agent: false
}) => {
assert_eq!(idp_name, "testing");
assert_eq!(idp_id, "something");
@@ -190,7 +194,8 @@ async fn it_works_with_macro_scheme() {
login_hint: None,
original_url: Some(original_url),
is_mobile: true,
- referral_code: _
+ referral_code: _,
+ is_agent: false
}) => {
assert_eq!(idp_name, "google");
assert_eq!(original_url.0.as_str(), "macro://login");
@@ -211,7 +216,8 @@ async fn it_works_with_double_encoded_scheme() {
login_hint: None,
original_url: Some(original_url),
is_mobile: true,
- referral_code: _
+ referral_code: _,
+ is_agent: false
}) => {
assert_eq!(idp_name, "google");
assert_eq!(original_url.0.as_str(), "https://example.com/");
@@ -255,3 +261,15 @@ fn local_frontend_origin_requires_exact_https_origin_without_credentials() {
Some(&http_origin)
));
}
+
+#[test]
+fn it_should_read_the_agent_signup_flag() {
+ let query: Query<LoginQueryParams> = Query::try_from_uri(
+ &"http://test/login/sso?idp_name=Google&is_agent=true"
+ .parse()
+ .unwrap(),
+ )
+ .unwrap();
+
+ assert!(query.is_agent);
+}
diff --git a/services/authentication_service/src/api/oauth/oauth_redirect.rs b/services/authentication_service/src/api/oauth/oauth_redirect.rs
index 4d4d06f3c6..e403ea4618 100644
--- a/services/authentication_service/src/api/oauth/oauth_redirect.rs
+++ b/services/authentication_service/src/api/oauth/oauth_redirect.rs
@@ -1,4 +1,6 @@
-use crate::api::webhooks::user::create_user_webhook::revert_unconfirmed_agent;
+use crate::api::webhooks::user::create_user_webhook::{
+ mark_sso_signup_as_agent, revert_unconfirmed_agent,
+};
use crate::api::{
context::ApiContext,
login::sso::{SsoState, is_allowed_original_url, redact_original_url_for_logging},
@@ -157,9 +159,16 @@ pub async fn handler(
Err(_) => false,
};
- // A provider just verified this address, so a person is signing in.
- if !just_signed_up && let Ok(user_id) = decoded_user_id.as_ref() {
- revert_unconfirmed_agent(&ctx, user_id.as_ref(), user_id.email_str()).await;
+ let agent_signup = state.as_ref().is_some_and(|state| state.is_agent);
+ if let Ok(user_id) = decoded_user_id.as_ref() {
+ if just_signed_up && agent_signup {
+ mark_sso_signup_as_agent(&ctx, user_id.as_ref(), user_id.email_str()).await;
+ }
+ // A provider just verified this address, so a person is signing in,
+ // unless they came through the agent signup page.
+ if !just_signed_up && !agent_signup {
+ revert_unconfirmed_agent(&ctx, user_id.as_ref(), user_id.email_str()).await;
+ }
}
// Only a brand-new account counts as referred: an existing user who signs
diff --git a/services/authentication_service/src/api/oauth/oauth_redirect/tests.rs b/services/authentication_service/src/api/oauth/oauth_redirect/tests.rs
index 6558be5118..211c6d905b 100644
--- a/services/authentication_service/src/api/oauth/oauth_redirect/tests.rs
+++ b/services/authentication_service/src/api/oauth/oauth_redirect/tests.rs
@@ -9,6 +9,7 @@ async fn it_should_deserialize_query_params() {
original_url: Some("https://example.com".parse().unwrap()),
referral_code: Some("test".to_string()),
is_mobile: true,
+ is_agent: true,
};
let json = serde_json::to_string(&sso_state).unwrap();
@@ -30,7 +31,7 @@ async fn it_should_deserialize_query_params() {
assert_matches!(data, OAuthCbParams { code: Some(code), state: Some(container), .. } => {
assert_eq!(code, "test123");
- assert_matches!(container.decode().unwrap(), SsoState { original_url: Some(url), is_mobile: true, referral_code: Some(code) } => {
+ assert_matches!(container.decode().unwrap(), SsoState { original_url: Some(url), is_mobile: true, referral_code: Some(code), is_agent: true } => {
assert_eq!(url.as_str(), "https://example.com/");
assert_eq!(code.as_str(), "test");
})
@@ -107,6 +108,7 @@ async fn it_writes_session_code_to_db() {
original_url: Some("https://macro.com".parse().unwrap()),
is_mobile: true,
referral_code: None,
+ is_agent: false,
}),
async |x| dummy.cb(x).await,
)
@@ -132,6 +134,7 @@ async fn it_rejects_disallowed_original_url_without_side_effects() {
original_url: Some("https://evil.example.com/phish".parse().unwrap()),
is_mobile: true,
referral_code: None,
+ is_agent: false,
}),
async |x| dummy.cb(x).await,
)
@@ -148,6 +151,7 @@ async fn it_allows_macro_scheme_original_url() {
original_url: Some("macro://login".parse().unwrap()),
is_mobile: false,
referral_code: None,
+ is_agent: false,
}),
async |x| dummy.cb(x).await,
)
diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
index b315e263f2..607405f9a1 100644
--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
@@ -668,6 +668,17 @@ pub(in crate::api) async fn revert_unconfirmed_agent(ctx: &ApiContext, user_id:
}
}
+/// A new account signed up with an identity provider from the agent signup
+/// page. FusionAuth creates the account before the sign-in returns, and its
+/// webhook cannot see the sign-in's state, so the flag is set here. A failure
+/// here must not block signing in.
+pub(in crate::api) async fn mark_sso_signup_as_agent(ctx: &ApiContext, user_id: &str, email: &str) {
+ match macro_db_client::user::mark_agent::mark_agent(&ctx.db, email).await {
+ Ok(()) => tracing::info!(user_id, "marked new SSO account as an agent"),
+ Err(e) => tracing::error!(error=?e, user_id, "unable to mark new SSO account as an agent"),
+ }
+}
+
/// Seed the starter documents with retries.
async fn initialize_starter_docs_with_retries(
client: &document_storage_service_client::DocumentStorageServiceClient,