Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): return desktop Gmail consent to the app
Eric Hayes5169ac3a5b19
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 388abda723..3c80984db6 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -91,6 +91,8 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.- Reconcile global focus when focused DOM subtrees are removed; iOS can omit blur events, otherwise floating creation actions stay hidden after search or editor teardown.- Mount the floating mobile AI composer only on the Agents view; other views keep their New action or their own reply/comment composer.- All API/network calls live in service-clients.+- Keep desktop inbox consent in the system browser with a+ `macro:///inbox-link-callback` return; webview origins are not desktop callbacks.- Draft autosaves preserve active email thread messages; evict inactive legacycaches on save and the active cache on thread exit. Revalidate GraphQL threadpages only when a save cannot patch the message list (missing snapshot or adiff --git a/apps/web/src/features/auth/EmailAuth.tsx b/apps/web/src/features/auth/EmailAuth.tsxindex 8f08c5436e..b1bc3de162 100644--- a/apps/web/src/features/auth/EmailAuth.tsx+++ b/apps/web/src/features/auth/EmailAuth.tsx@@ -117,8 +117,8 @@ const POST_LINK_FALLBACK_ROUTE = `${DEFAULT_ROUTE}/~/settings/${settingsTabToSlu* inbox via /link/gmail. Reads `link_id` from the query string and invokes init to* provision the second `email_links` row. Falls back to a toast on failure.*- * Consent runs as a full page navigation, so the split layout — which lives in- * the URL — is gone by the time this mounts. The add-inbox flow stashed it+ * Web consent navigates the page; desktop returns from the system browser via+ * a deep link. Both replace the split layout URL. The add-inbox flow stashed it* against this `link_id`; restoring it is what keeps enabling calendar (or* adding an inbox) from clobbering whatever the user had open.*/@@ -143,8 +143,8 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {const userInfoQuery = useUserInfoQuery();// 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- // survived — the stash is the only record of what the user had open.+ // flow that stashed one. The callback replaced the layout URL, so the stash+ // records what the user had open before consent.// Reports true when it navigated, so callers can fall through otherwise.const restoreLayoutBeforeConsent = (linkId: string) => {const stored = consumeInboxLinkReturn(linkId);diff --git a/apps/web/src/lib/core/email-link/index.ts b/apps/web/src/lib/core/email-link/index.tsindex 8ad540fe84..ff5f8df0ca 100644--- a/apps/web/src/lib/core/email-link/index.ts+++ b/apps/web/src/lib/core/email-link/index.ts@@ -1,10 +1,15 @@import { ROUTER_BASE_CONCAT, toBaseRelative } from '@app/constants/routerBase';import { updateUserAuth } from '@core/auth';-import { createNativeAuthSession } from '@core/auth/native-auth';+import {+ createNativeAuthSession,+ openDesktopAuthSession,+} from '@core/auth/native-auth';import { toast } from '@core/component/Toast/Toast';import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { fireAndForget } from '@core/util/fireAndForget';+import { isPlatform } from '@core/util/platform';+import { Telemetry } from '@macro-inc/observability';import { useInitGmailLink } from '@queries/auth';import { invalidateUserInfo } from '@queries/auth/user-info';import { invalidateEmailLinks, useEmailLinksQuery } from '@queries/email/link';@@ -231,9 +236,10 @@ const TOO_MANY_PENDING_LINKS_MESSAGE =* shared-inbox conflict is surfaced through `requestShareInboxConfirmation`,* rendered by the globally mounted dialog.*- * Everywhere else — web and desktop — the consent screen replaces the page, so- * the layout the user was working in is stashed against the new link id first- * and the callback restores it. Native mobile needs no stash: its layout never unmounts.+ * Desktop opens consent in the system browser and returns through a macro:///+ * deep link; web navigates the page. Both stash the current layout against the+ * new link id so the callback restores it. Native mobile needs no stash: its+ * layout never unmounts.*/export function useAddInboxFlow() {const initGmailLink = useInitGmailLink();@@ -310,22 +316,38 @@ export function useAddInboxFlow() {return;}- const callbackUrl = `${window.location.origin}${ROUTER_BASE_CONCAT}inbox-link-callback`;+ const desktop = isPlatform('desktop');+ const callbackUrl = desktop+ ? 'macro:///inbox-link-callback'+ : `${window.location.origin}${ROUTER_BASE_CONCAT}inbox-link-callback`;const result = await initGmailLink.mutateAsync({originalUrl: callbackUrl,scopes,});if (result.isOk()) {- // Leaving for Google unloads the app, and the split layout only lives in- // the URL — stash it so the callback can put it back rather than landing- // everyone on a default layout.+ // Web consent unloads the app; the desktop deep link replaces its route.+ // Preserve the layout so either callback can put it back.rememberInboxLinkReturn(result.value.link_id, {url: `${toBaseRelative(window.location.pathname)}${window.location.search}${window.location.hash}`,});- window.location.href = inboxAuthorizationUrl(+ const authorizationUrl = inboxAuthorizationUrl(result.value.authorization_url,options?.emailAddress);+ if (desktop) {+ await Telemetry.span('email.link.open_browser', async (span) => {+ span.setAttr('email.link.id', result.value.link_id);+ const opened = await openDesktopAuthSession(authorizationUrl);+ if (!opened.success) {+ span.error('Unable to open account connection browser');+ toast.failure(+ 'Failed to open the browser to connect your account. Please try again.'+ );+ }+ });+ return;+ }+ window.location.href = authorizationUrl;} else if (isPaymentRequired(result.error)) {showPaywall(PaywallKey.MULTI_INBOX);} else if (isTooManyPendingLinks(result.error)) {diff --git a/apps/web/src/lib/core/email-link/native-link.test.ts b/apps/web/src/lib/core/email-link/native-link.test.tsindex 38375ee94c..5e77f7b5b5 100644--- a/apps/web/src/lib/core/email-link/native-link.test.ts+++ b/apps/web/src/lib/core/email-link/native-link.test.ts@@ -1,4 +1,4 @@-import { ok } from 'neverthrow';+import { err, ok } from 'neverthrow';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({@@ -8,14 +8,19 @@ const mocks = vi.hoisted(() => ({refetch: vi.fn(),success: vi.fn(),failure: vi.fn(),+ desktop: false,+ mobile: true,+ openDesktop: vi.fn(),+ paywall: vi.fn(),}));vi.mock('@app/constants/routerBase', () => ({ROUTER_BASE_CONCAT: '/app/',- toBaseRelative: (value: string) => value,+ toBaseRelative: (value: string) => value.replace(/^\/app/, ''),}));vi.mock('@core/auth', () => ({ updateUserAuth: vi.fn() }));vi.mock('@core/auth/native-auth', () => ({+ openDesktopAuthSession: mocks.openDesktop,createNativeAuthSession: () => ({callbackUrl: 'macro://android-auth/test-attempt',authenticate: mocks.authenticate,@@ -26,10 +31,13 @@ vi.mock('@core/component/Toast/Toast', () => ({}));vi.mock('@core/constant/PaywallState', () => ({PaywallKey: { MULTI_INBOX: 'multi-inbox' },- usePaywallState: () => ({ showPaywall: vi.fn() }),+ usePaywallState: () => ({ showPaywall: mocks.paywall }),}));vi.mock('@core/mobile/isNativeMobilePlatform', () => ({- isNativeMobilePlatform: () => true,+ isNativeMobilePlatform: () => mocks.mobile,+}));+vi.mock('@core/util/platform', () => ({+ isPlatform: () => mocks.desktop,}));vi.mock('@queries/auth', () => ({useInitGmailLink: () => ({ mutateAsync: mocks.start }),@@ -48,10 +56,24 @@ vi.mock('@service-email/client', () => ({vi.mock('./share-conflict', () => ({ requestShareInboxConfirmation: vi.fn() }));import { useAddInboxFlow } from './index';+import { consumeInboxLinkReturn } from './return-layout';beforeEach(() => {vi.clearAllMocks();vi.useFakeTimers();+ mocks.desktop = false;+ mocks.mobile = true;+ mocks.openDesktop.mockResolvedValue({ success: true });+ sessionStorage.clear();+ vi.stubGlobal('window', {+ location: {+ origin: 'http://tauri.localhost',+ pathname: '/app/home/~/settings/connections',+ search: '?view=all',+ hash: '#selection',+ href: 'http://tauri.localhost/app/home/~/settings/connections?view=all#selection',+ },+ });mocks.start.mockResolvedValue(ok({link_id: 'pending-link',@@ -66,6 +88,76 @@ beforeEach(() => {afterEach(() => {vi.runOnlyPendingTimers();vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('desktop account linking', () => {+ beforeEach(() => {+ mocks.mobile = false;+ mocks.desktop = true;+ });++ it.each(['gmail', 'calendar', 'gmail_and_calendar'] as const)(+ 'opens %s consent in the system browser with an inbox callback',+ async (scopes) => {+ const originalLocation = window.location.href;+ await useAddInboxFlow()({ scopes, emailAddress: '[email protected]' });+ expect(mocks.start).toHaveBeenCalledExactlyOnceWith({+ originalUrl: 'macro:///inbox-link-callback',+ scopes,+ });+ expect(mocks.openDesktop).toHaveBeenCalledExactlyOnceWith(+ 'https://accounts.google.com/authorize?login_hint=second%40example.com'+ );+ expect(consumeInboxLinkReturn('pending-link')).toEqual({+ url: '/home/~/settings/connections?view=all#selection',+ });+ expect(window.location.href).toBe(originalLocation);+ expect(mocks.authenticate).not.toHaveBeenCalled();+ expect(mocks.provision).not.toHaveBeenCalled();+ expect(mocks.success).not.toHaveBeenCalled();+ }+ );++ it('reports a browser launch failure without provisioning the inbox', async () => {+ mocks.openDesktop.mockResolvedValue({ success: false });+ await useAddInboxFlow()();+ expect(mocks.failure).toHaveBeenCalledWith(+ 'Failed to open the browser to connect your account. Please try again.'+ );+ expect(mocks.provision).not.toHaveBeenCalled();+ });++ it.each(['PAYMENT_REQUIRED', 'TOO_MANY_PENDING_LINKS'])(+ 'does not open consent when the backend returns %s',+ async (code) => {+ mocks.start.mockResolvedValue(err([{ code }]));+ await useAddInboxFlow()();+ expect(mocks.openDesktop).not.toHaveBeenCalled();+ expect(mocks.provision).not.toHaveBeenCalled();+ if (code === 'PAYMENT_REQUIRED') {+ expect(mocks.paywall).toHaveBeenCalledWith('multi-inbox');+ } else {+ expect(mocks.failure).toHaveBeenCalledWith(+ 'Too many inbox connections in progress.'+ );+ }+ }+ );+});++it('keeps web consent on the originating host', async () => {+ mocks.mobile = false;+ vi.stubGlobal('window', {+ location: { ...window.location, origin: 'https://www.macro.com' },+ });+ await useAddInboxFlow()();+ expect(mocks.start).toHaveBeenCalledWith({+ originalUrl: 'https://www.macro.com/app/inbox-link-callback',+ scopes: 'gmail',+ });+ expect(window.location.href).toBe('https://accounts.google.com/authorize');+ expect(mocks.openDesktop).not.toHaveBeenCalled();});describe('native account linking', () => {diff --git a/apps/web/src/lib/core/email-link/return-layout.ts b/apps/web/src/lib/core/email-link/return-layout.tsindex 9ba1718333..4648fa0627 100644--- a/apps/web/src/lib/core/email-link/return-layout.ts+++ b/apps/web/src/lib/core/email-link/return-layout.ts@@ -15,8 +15,8 @@ type StoredInboxLinkReturn = InboxLinkReturn & { linkId: string };/*** Remember where to return once Gmail consent completes.*- * On web and desktop the consent screen is a full page navigation, so the app- * — split layout included — is torn down and rebuilt from the callback URL.+ * Web consent is a full page navigation; desktop opens the system browser and+ * its return deep link replaces the app route with the callback URL.* The layout lives in the URL, so stashing it here is what lets the callback* put the user back where they were instead of falling back to a default.*diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.mdindex 75d5d1e2ff..3769849ecb 100644--- a/docs/agent-guide/login.md+++ b/docs/agent-guide/login.md@@ -23,7 +23,15 @@Production Google/SSO and inbox/calendar connections may return to either`https://macro.com` or `https://www.macro.com`. Verify connections from both hosts;-the inbox link flow returns to `/app/inbox-link-callback` on the originating host.+the web inbox link flow returns to `/app/inbox-link-callback` on the originating host.++On desktop, connecting another Gmail account or enabling calendar opens Google+consent in the system browser. The app stays open; the callback is+`macro:///inbox-link-callback?link_id=...`, which provisions the inbox using the+existing app session and restores the saved layout, including its query and hash.+Verify that opening consent alone does not report an account connected, that+returning from consent shows the second account, and that canceling leaves the+app usable. iOS and Android continue to use their native authentication sessions.## Temporary open signup in Develop