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.

fix(email): preserve the split layout across Gmail consent (#5880)

gbirman3f76c87c6f4a
diff --git a/apps/web/src/features/auth/EmailAuth.tsx b/apps/web/src/features/auth/EmailAuth.tsx
index 4b8a399839..580b3e57f7 100644
--- a/apps/web/src/features/auth/EmailAuth.tsx
+++ b/apps/web/src/features/auth/EmailAuth.tsx
@@ -1,3 +1,4 @@
+import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
import { ShareInboxConflictDialog } from '@app/features/inbox/ShareInboxConflictDialog';
import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
@@ -6,8 +7,11 @@ import { redirectToEmailAuth } from '@core/auth/email';
import { publishLoginSuccess } from '@core/auth/login-events';
import { LoadingBlock } from '@core/component/LoadingBlock';
import { toast } from '@core/component/Toast/Toast';
-import { useSettingsState } from '@core/constant/SettingsState';
+import { restoreSettingsReturnTo } from '@core/constant/SettingsState';
+import { appendSettingsSplitToUrl } from '@core/constant/settingsSplitUrl';
+import { settingsTabToSlug } from '@core/constant/settingsTabsConfig';
import { useEmailLinks } from '@core/email-link';
+import { consumeInboxLinkReturn } from '@core/email-link/return-layout';
import { isMobile } from '@core/mobile/isMobile';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { whenSettled } from '@core/util/whenSettled';
@@ -97,16 +101,31 @@ function EmailSignupCallback(props: Pick<EmailAuthParams, 'successPath'>) {
return <LoadingBlock />;
}
+/**
+ * Where the callback lands when there is no layout to restore: the app's home
+ * view with the Connections settings page docked beside it, so a user who just
+ * granted access still sees the result. Only reachable when the stash is
+ * missing — storage blocked, or a callback URL opened outside its own flow.
+ */
+const POST_LINK_FALLBACK_ROUTE = appendSettingsSplitToUrl(
+ DEFAULT_ROUTE,
+ settingsTabToSlug('Connected')
+);
+
/**
* Handles the OAuth callback after an already-authenticated user adds another Gmail
* 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
+ * against this `link_id`; restoring it is what keeps enabling calendar (or
+ * adding an inbox) from clobbering whatever the user had open.
*/
function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { query, initEmailLink } = useEmailLinks();
- const { setActiveTabId } = useSettingsState();
const [conflict, setConflict] = createSignal<{
linkId: string;
emailAddress: string;
@@ -120,9 +139,25 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
const userInfoQuery = useUserInfoQuery();
const onboardingV4 = useOnboardingV4Flag();
- // The desktop settings split doesn't exist on mobile, so the callback
- // returns mobile users to the list view with the toast as confirmation.
- const navigateToEmailSettings = () => {
+ // 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.
+ // Reports true when it navigated, so callers can fall through otherwise.
+ const restoreLayoutBeforeConsent = (linkId: string) => {
+ const stored = consumeInboxLinkReturn(linkId);
+ if (!stored) return false;
+ if (stored.settingsReturnTo) {
+ restoreSettingsReturnTo(stored.settingsReturnTo);
+ }
+ navigate(stored.url, { replace: true });
+ return true;
+ };
+
+ // Where the callback hands the user off, in order of preference: back into
+ // onboarding for a first-run user, then the layout they left, then a
+ // form-factor default — the list view on mobile, where the desktop settings
+ // split doesn't exist and the toast is the confirmation.
+ const navigateAfterLink = (linkId: string) => {
// A first-run user connected this inbox from the onboarding flow:
// return straight to it. Landing in mail settings would mount the app
// shell mid-onboarding just for NewOnboardingRedirect to bounce back.
@@ -135,12 +170,12 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
navigate('/onboarding', { replace: true });
return;
}
+ if (restoreLayoutBeforeConsent(linkId)) return;
if (isMobile()) {
navigateToSuccess();
return;
}
- setActiveTabId('Connected');
- navigate('/component/mail/component/settings', { replace: true });
+ navigate(POST_LINK_FALLBACK_ROUTE, { replace: true });
};
const runInit = async (linkId: string, forceShare: boolean) => {
@@ -151,12 +186,12 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
// than flashing a stale list until its own refetch lands.
await query.refetch();
toast.success('Inbox connected');
- navigateToEmailSettings();
+ navigateAfterLink(linkId);
},
async (err) => {
if (err.tag === 'AlreadyInitialized') {
await query.refetch();
- navigateToEmailSettings();
+ navigateAfterLink(linkId);
return;
}
// The mailbox is already connected by someone else. Hold the callback open
@@ -173,11 +208,11 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
toast.failure(
'Gmail access was not granted. Please allow all requested permissions and try again.'
);
- navigateToEmailSettings();
+ navigateAfterLink(linkId);
return;
}
toast.failure('Failed to add inbox');
- navigateToEmailSettings();
+ navigateAfterLink(linkId);
}
);
};
@@ -209,8 +244,9 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
emailAddress={c().emailAddress}
ownerEmail={c().ownerEmail}
onCancel={() => {
+ const linkId = c().linkId;
setConflict(null);
- navigateToSuccess();
+ if (!restoreLayoutBeforeConsent(linkId)) navigateToSuccess();
}}
onShare={() => {
const linkId = c().linkId;
diff --git a/apps/web/src/lib/constants/routerBase.ts b/apps/web/src/lib/constants/routerBase.ts
index 0760fa4ffa..83da13bc49 100644
--- a/apps/web/src/lib/constants/routerBase.ts
+++ b/apps/web/src/lib/constants/routerBase.ts
@@ -3,3 +3,17 @@ import { isTauri } from '@core/util/platform';
export const ROUTER_BASE = isTauri() ? '/' : '/app';
export const ROUTER_BASE_CONCAT = isTauri() ? '/' : '/app/';
+
+/**
+ * Strip the router base from a `location.pathname` (which includes it, e.g.
+ * `/app/component/inbox`) so it can be compared to — and reused with — the
+ * base-relative paths that `navigate()` and route definitions use.
+ */
+export const toBaseRelative = (pathname: string): string => {
+ if (ROUTER_BASE === '/') return pathname;
+ if (pathname === ROUTER_BASE) return '/';
+ if (pathname.startsWith(`${ROUTER_BASE}/`)) {
+ return pathname.slice(ROUTER_BASE.length);
+ }
+ return pathname;
+};
diff --git a/apps/web/src/lib/core/constant/SettingsState.tsx b/apps/web/src/lib/core/constant/SettingsState.tsx
index 9a58097e34..2c8a6b2043 100644
--- a/apps/web/src/lib/core/constant/SettingsState.tsx
+++ b/apps/web/src/lib/core/constant/SettingsState.tsx
@@ -1,5 +1,5 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
-import { ROUTER_BASE } from '@app/constants/routerBase';
+import { toBaseRelative } from '@app/constants/routerBase';
import { globalSplitManager } from '@app/signal/splitLayout';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { isMobile } from '@core/mobile/isMobile';
@@ -13,20 +13,6 @@ import {
} from './settingsSplitUrl';
import { settingsSlugToTab, settingsTabToSlug } from './settingsTabsConfig';
-/**
- * Strip the router base from a `location.pathname` (which includes it, e.g.
- * `/app/settings`) so it can be compared to — and reused with — the
- * base-relative paths that `navigate()` and route definitions use.
- */
-const toBaseRelative = (pathname: string) => {
- if (ROUTER_BASE === '/') return pathname;
- if (pathname === ROUTER_BASE) return '/';
- if (pathname.startsWith(`${ROUTER_BASE}/`)) {
- return pathname.slice(ROUTER_BASE.length);
- }
- return pathname;
-};
-
export type SettingsTab =
| 'Account'
| 'Billing'
@@ -56,6 +42,20 @@ export type SettingsTab =
// DEFAULT_ROUTE.
const [settingsReturnTo, setSettingsReturnTo] = createSignal<string>();
+/**
+ * Re-seed {@link settingsReturnTo} after a full page load has wiped it. The
+ * Gmail consent round trip tears the app down, so the add-inbox flow captures
+ * this alongside the layout it left from and the callback hands it back — the
+ * user returns to solo settings with "Back to app" still pointing at the
+ * layout they had before they opened settings.
+ */
+export const restoreSettingsReturnTo = (url: string) => {
+ setSettingsReturnTo(url);
+};
+
+/** Read-only view of {@link settingsReturnTo} for capture across a reload. */
+export const currentSettingsReturnTo = settingsReturnTo;
+
/**
* Extract the active settings tab from a docked-split path
* (`.../settings/<slug>`), or undefined if the path has no settings split.
diff --git a/apps/web/src/lib/core/email-link/index.ts b/apps/web/src/lib/core/email-link/index.ts
index a7ea3af699..900bfc8534 100644
--- a/apps/web/src/lib/core/email-link/index.ts
+++ b/apps/web/src/lib/core/email-link/index.ts
@@ -1,7 +1,8 @@
-import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
+import { ROUTER_BASE_CONCAT, toBaseRelative } from '@app/constants/routerBase';
import { updateUserAuth } from '@core/auth';
import { toast } from '@core/component/Toast/Toast';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
+import { currentSettingsReturnTo } from '@core/constant/SettingsState';
import { getNativeMobilePlatform } from '@core/util/platform';
import { useInitGmailLink } from '@queries/auth';
import { invalidateUserInfo } from '@queries/auth/user-info';
@@ -21,6 +22,7 @@ import type { UseQueryResult } from '@tanstack/solid-query';
import { invoke } from '@tauri-apps/api/core';
import { err, okAsync, ResultAsync } from 'neverthrow';
import { createMemo, createSignal } from 'solid-js';
+import { rememberInboxLinkReturn } from './return-layout';
import { requestShareInboxConfirmation } from './share-conflict';
const [emailRefetchInterval, setEmailRefetchInterval] = createSignal<
@@ -226,6 +228,10 @@ const TOO_MANY_PENDING_LINKS_MESSAGE =
* provisioned here directly with the `link_id` from the init response. A
* 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. iOS needs no stash: its layout never unmounts.
*/
export function useAddInboxFlow() {
const initGmailLink = useInitGmailLink();
@@ -312,6 +318,13 @@ export function useAddInboxFlow() {
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.
+ rememberInboxLinkReturn(result.value.link_id, {
+ url: `${toBaseRelative(window.location.pathname)}${window.location.search}${window.location.hash}`,
+ settingsReturnTo: currentSettingsReturnTo(),
+ });
window.location.href = result.value.authorization_url;
} else if (isPaymentRequired(result.error)) {
showPaywall(PaywallKey.MULTI_INBOX);
diff --git a/apps/web/src/lib/core/email-link/return-layout.test.ts b/apps/web/src/lib/core/email-link/return-layout.test.ts
new file mode 100644
index 0000000000..1fcff9d84d
--- /dev/null
+++ b/apps/web/src/lib/core/email-link/return-layout.test.ts
@@ -0,0 +1,83 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ consumeInboxLinkReturn,
+ rememberInboxLinkReturn,
+} from './return-layout';
+
+const LINK_ID = 'link-1';
+
+beforeEach(() => {
+ sessionStorage.clear();
+ vi.restoreAllMocks();
+});
+
+describe('inbox link return layout', () => {
+ it('round-trips the layout URL for the link that stashed it', () => {
+ rememberInboxLinkReturn(LINK_ID, {
+ url: '/calendar/view/component/documents?preview=0#sel',
+ });
+
+ expect(consumeInboxLinkReturn(LINK_ID)).toEqual({
+ url: '/calendar/view/component/documents?preview=0#sel',
+ settingsReturnTo: undefined,
+ });
+ });
+
+ it('round-trips the settings return layout alongside it', () => {
+ rememberInboxLinkReturn(LINK_ID, {
+ url: '/settings/connections',
+ settingsReturnTo: '/component/inbox/md/doc-1',
+ });
+
+ expect(consumeInboxLinkReturn(LINK_ID)).toEqual({
+ url: '/settings/connections',
+ settingsReturnTo: '/component/inbox/md/doc-1',
+ });
+ });
+
+ it('clears the stash so a second read finds nothing', () => {
+ rememberInboxLinkReturn(LINK_ID, { url: '/component/inbox' });
+
+ consumeInboxLinkReturn(LINK_ID);
+
+ expect(consumeInboxLinkReturn(LINK_ID)).toBeUndefined();
+ });
+
+ it('ignores a stash left behind by a different flow', () => {
+ rememberInboxLinkReturn('abandoned-link', { url: '/component/inbox' });
+
+ expect(consumeInboxLinkReturn(LINK_ID)).toBeUndefined();
+ });
+
+ it('drops a mismatched stash rather than leaving it to match later', () => {
+ rememberInboxLinkReturn('abandoned-link', { url: '/component/inbox' });
+
+ consumeInboxLinkReturn(LINK_ID);
+
+ expect(consumeInboxLinkReturn('abandoned-link')).toBeUndefined();
+ });
+
+ it('returns undefined for corrupt stored data', () => {
+ sessionStorage.setItem('macro:inbox-link:return-layout', 'not json');
+
+ expect(consumeInboxLinkReturn(LINK_ID)).toBeUndefined();
+ });
+
+ it('keeps the flow alive when storage is unavailable', () => {
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('storage blocked');
+ });
+
+ expect(() =>
+ rememberInboxLinkReturn(LINK_ID, { url: '/component/inbox' })
+ ).not.toThrow();
+ });
+
+ it('returns undefined when reading storage throws', () => {
+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
+ throw new Error('storage blocked');
+ });
+
+ expect(consumeInboxLinkReturn(LINK_ID)).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/lib/core/email-link/return-layout.ts b/apps/web/src/lib/core/email-link/return-layout.ts
new file mode 100644
index 0000000000..27dea4fdb5
--- /dev/null
+++ b/apps/web/src/lib/core/email-link/return-layout.ts
@@ -0,0 +1,88 @@
+const RETURN_LAYOUT_KEY = 'macro:inbox-link:return-layout';
+
+/** Where the app should land once the Gmail consent round trip comes back. */
+export type InboxLinkReturn = {
+ /**
+ * The base-relative layout URL the flow started from — path plus query and
+ * hash, so the `preview` param encoding Controller/Viewer Preview Pairs
+ * survives with it.
+ */
+ url: string;
+ /**
+ * `settingsReturnTo` as it stood at capture time, present when the flow
+ * started from solo settings. Restoring it keeps "Back to app" pointing at
+ * the layout behind settings instead of the default route.
+ */
+ settingsReturnTo?: string;
+};
+
+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.
+ * 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.
+ *
+ * `sessionStorage` rather than the OAuth `state`: the layout path carries
+ * document and channel ids, and `state` is handed to Google.
+ *
+ * Keyed by the link id the init call minted, which the callback receives back
+ * as `link_id`, so an abandoned flow's leftovers can't hijack a later one.
+ */
+export function rememberInboxLinkReturn(
+ linkId: string,
+ value: InboxLinkReturn
+): void {
+ const stored: StoredInboxLinkReturn = { ...value, linkId };
+ try {
+ sessionStorage.setItem(RETURN_LAYOUT_KEY, JSON.stringify(stored));
+ } catch {
+ // Storage can be unavailable (private mode, blocked site data). The
+ // callback falls back to its default layout rather than failing the link.
+ }
+}
+
+/**
+ * Read and clear the layout stashed by {@link rememberInboxLinkReturn} for
+ * this link. Returns undefined when nothing was stashed or the stash belongs
+ * to a different flow.
+ */
+export function consumeInboxLinkReturn(
+ linkId: string
+): InboxLinkReturn | undefined {
+ let raw: string | null;
+ try {
+ raw = sessionStorage.getItem(RETURN_LAYOUT_KEY);
+ } catch {
+ return undefined;
+ }
+ if (raw === null) return undefined;
+
+ let stored: Partial<StoredInboxLinkReturn> | undefined;
+ try {
+ stored = JSON.parse(raw) as Partial<StoredInboxLinkReturn>;
+ } catch {
+ stored = undefined;
+ }
+
+ // A stash that can't be matched is dead weight either way, so drop it.
+ try {
+ sessionStorage.removeItem(RETURN_LAYOUT_KEY);
+ } catch {
+ // Nothing to do — the read already succeeded.
+ }
+
+ if (!stored || stored.linkId !== linkId || typeof stored.url !== 'string') {
+ return undefined;
+ }
+ return {
+ url: stored.url,
+ settingsReturnTo:
+ typeof stored.settingsReturnTo === 'string'
+ ? stored.settingsReturnTo
+ : undefined,
+ };
+}