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): stop showing aliases as inboxes and report every inbox connection outcome (#8967)

teoc3413c371fe1
diff --git a/apps/web/src/features/auth/EmailAuth.test.tsx b/apps/web/src/features/auth/EmailAuth.test.tsx
index 968162037a..3eeba01801 100644
--- a/apps/web/src/features/auth/EmailAuth.test.tsx
+++ b/apps/web/src/features/auth/EmailAuth.test.tsx
@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({
refetch: vi.fn(),
failure: vi.fn(),
success: vi.fn(),
+ alert: vi.fn(),
linkId: 'oauth-link',
searchParams: {} as Record<string, string | string[]>,
tutorialComplete: true as boolean,
@@ -22,7 +23,6 @@ const mocks = vi.hoisted(() => ({
track: vi.fn(),
openAddInbox: vi.fn(),
fetchProviders: vi.fn(),
- peek: vi.fn(),
custom: vi.fn(),
dismiss: vi.fn(),
}));
@@ -52,6 +52,7 @@ vi.mock('@core/component/Toast/Toast', () => ({
toast: {
success: mocks.success,
failure: mocks.failure,
+ alert: mocks.alert,
custom: mocks.custom,
dismiss: mocks.dismiss,
},
@@ -60,8 +61,8 @@ vi.mock('@core/constant/SettingsState', () => ({
restoreSettingsReturnTo: vi.fn(),
}));
vi.mock('@core/email-link/return-layout', () => ({
+ readInboxLinkReturn: mocks.restore,
consumeInboxLinkReturn: mocks.restore,
- readInboxLinkReturn: mocks.peek,
}));
vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
@@ -126,13 +127,12 @@ beforeEach(() => {
'https://login.microsoftonline.com/organizations/v2.0/adminconsent?client_id=app',
});
mocks.refetch.mockResolvedValue({});
- mocks.restore.mockReturnValue({ url: '/calendar/week' });
- mocks.peek.mockReturnValue({
+ mocks.restore.mockReturnValue({
url: '/calendar/week',
scopes: 'gmail_and_calendar',
});
mocks.custom.mockReturnValue(7);
- mocks.init.mockReturnValue(okAsync(undefined));
+ mocks.init.mockReturnValue(okAsync('new-inbox'));
});
afterEach(cleanup);
@@ -155,6 +155,53 @@ describe('inbox consent callback', () => {
);
});
+ it('names the address when the account chooser returned an inbox that was already connected', async () => {
+ mocks.restore.mockReturnValue({
+ url: '/email',
+ addition: {
+ provider: 'GMAIL',
+ connectedInboxes: [
+ { id: 'gmail-inbox', emailAddress: '[email protected]' },
+ { id: 'workspace-inbox', emailAddress: '[email protected]' },
+ ],
+ },
+ });
+ mocks.init.mockReturnValue(okAsync('workspace-inbox'));
+ render(() => <EmailLinkCallback />);
+ await waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledWith('/email', { replace: true })
+ );
+ expect(mocks.alert).toHaveBeenCalledExactlyOnceWith(
+ expect.stringContaining('[email protected]'),
+ expect.anything()
+ );
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.track).toHaveBeenCalledExactlyOnceWith(
+ 'email_link_callback_result',
+ { outcome: 'already_connected' }
+ );
+ });
+
+ it('reports a new inbox from a plain add as connected', async () => {
+ mocks.restore.mockReturnValue({
+ url: '/email',
+ addition: {
+ provider: 'GMAIL',
+ connectedInboxes: [
+ { id: 'gmail-inbox', emailAddress: '[email protected]' },
+ ],
+ },
+ });
+ render(() => <EmailLinkCallback />);
+ await waitFor(() =>
+ expect(mocks.track).toHaveBeenCalledExactlyOnceWith(
+ 'email_link_callback_result',
+ { outcome: 'connected' }
+ )
+ );
+ expect(mocks.alert).not.toHaveBeenCalled();
+ });
+
it('explains pending work and lets the user return without a later redirect', async () => {
let finish!: () => void;
mocks.init.mockReturnValue(
@@ -310,7 +357,7 @@ describe('consent that ended without a grant', () => {
});
it('retries with email alone when the refused flow left no stash', async () => {
- mocks.peek.mockReturnValue(undefined);
+ mocks.restore.mockReturnValue(undefined);
mocks.searchParams = {
link_id: 'oauth-link',
email_link_error: 'gmail_not_granted',
@@ -327,7 +374,7 @@ describe('consent that ended without a grant', () => {
});
});
- it('returns quietly when the user cancelled on the consent screen', async () => {
+ it('says nothing was connected when the user cancelled on the consent screen', async () => {
mocks.searchParams = {
link_id: 'oauth-link',
email_link_error: 'cancelled',
@@ -339,6 +386,7 @@ describe('consent that ended without a grant', () => {
replace: true,
})
);
+ expect(mocks.alert).toHaveBeenCalledOnce();
expect(mocks.failure).not.toHaveBeenCalled();
expect(mocks.init).not.toHaveBeenCalled();
});
diff --git a/apps/web/src/features/auth/EmailAuth.tsx b/apps/web/src/features/auth/EmailAuth.tsx
index 09d2cfcf8b..7496a9e20a 100644
--- a/apps/web/src/features/auth/EmailAuth.tsx
+++ b/apps/web/src/features/auth/EmailAuth.tsx
@@ -12,6 +12,11 @@ import { LoadingBlock } from '@core/component/LoadingBlock';
import { toast } from '@core/component/Toast/Toast';
import { settingsTabToSlug } from '@core/constant/settingsTabsConfig';
import { useEmailLinks } from '@core/email-link';
+import {
+ announceAlreadyConnected,
+ announceConsentCancelled,
+ announceLinkedInbox,
+} from '@core/email-link/link-outcome';
import {
consumeInboxLinkReturn,
readInboxLinkReturn,
@@ -179,14 +184,15 @@ function promptForEmailAccess(scopes: ConsentScopes | undefined) {
/**
* Handles the OAuth callback after an already-authenticated user adds another
* inbox via /link/gmail or /link/outlook. Reads `link_id` from the query string
- * and invokes init to provision the second `email_links` row. Falls back to a
- * toast on failure.
+ * and invokes init to provision the second `email_links` row. Every outcome is
+ * announced: init also succeeds when the account chooser returned an inbox the
+ * user already had, which a plain add reports as already connected.
*
* A consent screen that ended without a usable grant arrives with
- * `email_link_error` instead: a cancel goes straight back, a tenant that needs
- * admin approval gets the dialog with the approval link, a Google consent that
- * left out the email permissions gets a prompt that stays until dismissed and
- * retries the same request, and anything else gets a toast.
+ * `email_link_error` instead: a cancel says nothing was connected, a tenant
+ * that needs admin approval gets the dialog with the approval link, a Google
+ * consent that left out the email permissions gets a prompt that stays until
+ * dismissed and retries the same request, and anything else gets a toast.
* An administrator who approved the tenant arrives with `email_link_notice`.
*
* Web consent navigates the page; desktop returns from the system browser via
@@ -212,7 +218,6 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
ownerEmail: string;
} | null>(null);
const [adminConsent, setAdminConsent] = createSignal<{
- linkId: string | null;
url: string | undefined;
} | null>(null);
@@ -222,12 +227,16 @@ 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. The callback replaced the layout URL, so the stash
- // records what the user had open before consent.
+ const linkId = stringParam(searchParams.link_id);
+ // What the flow stashed against this attempt, if it stashed anything: the
+ // layout it left from (the callback replaced the layout URL) and, for a
+ // plain add, the inboxes already connected when it started. It is cleared
+ // only on leaving, so a reload while init runs can still use it.
+ const stashed = linkId ? readInboxLinkReturn(linkId) : undefined;
+
// Reports true when it navigated, so callers can fall through otherwise.
- const restoreLayoutBeforeConsent = (linkId: string) => {
- const stored = consumeInboxLinkReturn(linkId);
+ const restoreLayoutBeforeConsent = () => {
+ const stored = linkId ? consumeInboxLinkReturn(linkId) : undefined;
if (!stored) return false;
navigate(stored.url, { replace: true });
return true;
@@ -237,7 +246,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
// 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 | null) => {
+ const navigateAfterLink = () => {
if (disposed) return;
// A first-run user connected this inbox from the onboarding flow:
// return straight to it. Landing in mail settings would mount the app
@@ -250,7 +259,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
navigate(onboardingPathWithStep(searchParams.step), { replace: true });
return;
}
- if (linkId && restoreLayoutBeforeConsent(linkId)) return;
+ if (restoreLayoutBeforeConsent()) return;
if (isMobile()) {
navigateToSuccess();
return;
@@ -261,20 +270,20 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
const runInit = async (linkId: string, forceShare: boolean) => {
try {
await initEmailLink({ linkId, forceShare }).match(
- async () => {
- trackOutcome('connected');
+ async (connectedLinkId) => {
// Pull the newly-provisioned link into the cache before leaving the
// callback so the inbox panel shows it immediately on return rather
// than flashing a stale list until its own refetch lands.
await query.refetch();
- toast.success('Account connected');
- navigateAfterLink(linkId);
+ trackOutcome(announceLinkedInbox(connectedLinkId, stashed?.addition));
+ navigateAfterLink();
},
async (err) => {
if (err.tag === 'AlreadyInitialized') {
trackOutcome('already_initialized');
await query.refetch();
- navigateAfterLink(linkId);
+ announceAlreadyConnected(stashed?.addition?.provider);
+ navigateAfterLink();
return;
}
// The mailbox is already connected by someone else. Hold the callback open
@@ -293,7 +302,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
toast.failure(
'A professional subscription is required to add another inbox.'
);
- navigateAfterLink(linkId);
+ navigateAfterLink();
return;
}
if (err.tag === 'NoGmailGrant') {
@@ -301,12 +310,12 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
toast.failure(
'Gmail access was not granted. Please allow all requested permissions and try again.'
);
- navigateAfterLink(linkId);
+ navigateAfterLink();
return;
}
trackOutcome('failed');
toast.failure('Failed to add inbox');
- navigateAfterLink(linkId);
+ navigateAfterLink();
}
);
} catch {
@@ -315,33 +324,32 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
toast.failure(
'Failed to finish connecting your account. Please try again from Settings.'
);
- navigateAfterLink(linkId);
+ navigateAfterLink();
}
};
// The consent screen ended without a grant. The pending link is already
// released server-side; this only explains the outcome and hands off.
- const handleConsentFailure = (error: string, linkId: string | null) => {
+ const handleConsentFailure = (error: string) => {
if (error === CONSENT_CANCELLED_ERROR) {
- navigateAfterLink(linkId);
+ announceConsentCancelled();
+ navigateAfterLink();
return;
}
if (error === GMAIL_NOT_GRANTED_ERROR) {
trackOutcome('gmail_not_granted');
// The retry asks for what this flow asked for: a calendar entry point
// wants email and calendar together, not email alone.
- promptForEmailAccess(
- linkId ? readInboxLinkReturn(linkId)?.scopes : undefined
- );
- navigateAfterLink(linkId);
+ promptForEmailAccess(stashed?.scopes);
+ navigateAfterLink();
return;
}
if (error !== ADMIN_CONSENT_REQUIRED_ERROR) {
toast.failure('Failed to connect your account. Please try again.');
- navigateAfterLink(linkId);
+ navigateAfterLink();
return;
}
- setAdminConsent({ linkId, url: undefined });
+ setAdminConsent({ url: undefined });
fireAndForget(loadAdminConsentUrl(), 'email-auth');
};
@@ -360,19 +368,18 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
// Completing consent does not depend on the old inbox list loading first.
// A paused or slow query must not prevent the new grant from being applied.
onMount(() => {
- const linkId = stringParam(searchParams.link_id);
if (
stringParam(searchParams.email_link_notice) ===
ADMIN_CONSENT_GRANTED_NOTICE
) {
toast.success('Approved. Try connecting again.');
openAddInboxDialog();
- navigateAfterLink(linkId);
+ navigateAfterLink();
return;
}
const linkError = stringParam(searchParams.email_link_error);
if (linkError) {
- handleConsentFailure(linkError, linkId);
+ handleConsentFailure(linkError);
return;
}
if (!linkId) {
@@ -401,13 +408,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
We’re applying your Google permissions. Calendar events may take a
few minutes to sync after you return.
</p>
- <Button
- variant="secondary"
- size="sm"
- onClick={() =>
- navigateAfterLink(stringParam(searchParams.link_id))
- }
- >
+ <Button variant="secondary" size="sm" onClick={navigateAfterLink}>
Back to app
</Button>
</div>
@@ -420,15 +421,13 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
open
adminConsentUrl={consent().url}
onClose={() => {
- const linkId = consent().linkId;
setAdminConsent(null);
- navigateAfterLink(linkId);
+ navigateAfterLink();
}}
onConnectDifferentAccount={() => {
- const linkId = consent().linkId;
setAdminConsent(null);
openAddInboxDialog();
- navigateAfterLink(linkId);
+ navigateAfterLink();
}}
/>
)}
@@ -440,9 +439,8 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
emailAddress={c().emailAddress}
ownerEmail={c().ownerEmail}
onCancel={() => {
- const linkId = c().linkId;
setConflict(null);
- if (!restoreLayoutBeforeConsent(linkId)) navigateToSuccess();
+ if (!restoreLayoutBeforeConsent()) navigateToSuccess();
}}
onShare={() => {
const linkId = c().linkId;
diff --git a/apps/web/src/features/email-compose/browser-test/sender-fixture.tsx b/apps/web/src/features/email-compose/browser-test/sender-fixture.tsx
index f185c6b28f..3556f40c5e 100644
--- a/apps/web/src/features/email-compose/browser-test/sender-fixture.tsx
+++ b/apps/web/src/features/email-compose/browser-test/sender-fixture.tsx
@@ -50,6 +50,19 @@ export function SenderFixture() {
>
Simulate unavailable aliases
</button>
+ <button
+ onClick={() =>
+ setFixtureInboxes([
+ {
+ id: 'owned',
+ email_address: '[email protected]',
+ sendAs: aliases,
+ },
+ ])
+ }
+ >
+ Simulate one inbox with an alias
+ </button>
<output data-testid="alias-filter">
{JSON.stringify(fixtureScope)}
</output>
diff --git a/apps/web/src/features/email-compose/browser-test/sender.browser.e2e.ts b/apps/web/src/features/email-compose/browser-test/sender.browser.e2e.ts
index da33817714..b10f8fa96d 100644
--- a/apps/web/src/features/email-compose/browser-test/sender.browser.e2e.ts
+++ b/apps/web/src/features/email-compose/browser-test/sender.browser.e2e.ts
@@ -27,51 +27,100 @@ test('reply defaults to its alias and selections retain the owning inbox', async
await expect(page.getByTestId('sender')).toHaveText('owned:[email protected]');
});
-test('an unavailable saved alias does not select the sole primary inbox and can still be cleared', async ({
- page,
-}) => {
- await page.goto('/?senders');
- const sidebar = page.getByRole('navigation', { name: 'Inboxes' });
- await sidebar
- .getByRole('button', { name: '[email protected]', exact: true })
- .first()
- .click();
- await page
- .getByRole('button', { name: 'Simulate unavailable aliases' })
- .click();
- await expect(page.getByTestId('alias-filter')).toContainText(
- );
- await expect(
- sidebar.getByRole('button', { name: '[email protected]', exact: true })
- ).not.toHaveAttribute('aria-current', 'true');
- await sidebar.getByRole('button', { name: 'All inboxes' }).click();
- await expect(page.getByTestId('alias-filter')).toHaveText('{}');
- await expect(
- sidebar.getByRole('button', { name: '[email protected]', exact: true })
- ).toHaveAttribute('aria-current', 'true');
-});
+test.describe('touch inbox list', () => {
+ test.use({
+ hasTouch: true,
+ isMobile: true,
+ viewport: { width: 390, height: 844 },
+ });
-test('sidebar aliases select independently and All clears both filters', async ({
- page,
-}) => {
- await page.setViewportSize({ width: 390, height: 844 });
- await page.goto('/?senders');
- const sidebar = page.getByRole('navigation', { name: 'Inboxes' });
- const aliases = sidebar.getByRole('button', {
- exact: true,
+ test('an unavailable saved alias does not select the sole primary inbox and can still be cleared', async ({
+ page,
+ }) => {
+ await page.goto('/?senders');
+ const sidebar = page.getByRole('navigation', { name: 'Inboxes' });
+ await sidebar
+ .getByRole('button', {
+ exact: true,
+ })
+ .click();
+ await page
+ .getByRole('button', { name: 'Simulate unavailable aliases' })
+ .click();
+ await expect(page.getByTestId('alias-filter')).toContainText(
+ );
+ await expect(
+ sidebar.getByRole('button', { name: '[email protected]', exact: true })
+ ).not.toHaveAttribute('aria-current', 'true');
+ await sidebar.getByRole('button', { name: 'All inboxes' }).click();
+ await expect(page.getByTestId('alias-filter')).toHaveText('{}');
+ await expect(
+ sidebar.getByRole('button', { name: '[email protected]', exact: true })
+ ).toHaveAttribute('aria-current', 'true');
+ });
+
+ test('sidebar aliases select independently and All clears both filters', async ({
+ page,
+ }) => {
+ await page.goto('/?senders');
+ const sidebar = page.getByRole('navigation', { name: 'Inboxes' });
+ const ownedAlias = sidebar.getByRole('button', {
+ exact: true,
+ });
+ const delegatedAlias = sidebar.getByRole('button', {
+ exact: true,
+ });
+ await ownedAlias.click();
+ await expect(page.getByTestId('alias-filter')).toContainText(
+ '"inboxId":"owned"'
+ );
+ await expect(ownedAlias).toHaveAttribute('aria-current', 'true');
+ await delegatedAlias.click();
+ await expect(page.getByTestId('alias-filter')).toContainText(
+ '"inboxId":"delegated"'
+ );
+ await expect(delegatedAlias).toHaveAttribute('aria-current', 'true');
+ await sidebar.getByRole('button', { name: 'All inboxes' }).click();
+ await expect(page.getByTestId('alias-filter')).toHaveText('{}');
+ });
+
+ test('an alias does not make one inbox count as several', async ({
+ page,
+ }) => {
+ await page.goto('/?senders');
+ await page
+ .getByRole('button', { name: 'Simulate one inbox with an alias' })
+ .click();
+ const sidebar = page.getByRole('navigation', { name: 'Inboxes' });
+ const inbox = sidebar.getByRole('button', {
+ exact: true,
+ });
+ const alias = sidebar.getByRole('button', {
+ exact: true,
+ });
+ await expect(alias).toBeVisible();
+ await expect(
+ sidebar.getByRole('button', { name: 'All inboxes' })
+ ).toHaveCount(0);
+ await expect(inbox).toHaveAttribute('aria-current', 'true');
+
+ await alias.click();
+ await expect(page.getByTestId('alias-filter')).toContainText(
+ '"emailAddress":"[email protected]"'
+ );
+ await expect(alias).toHaveAttribute('aria-current', 'true');
+ await expect(inbox).not.toHaveAttribute('aria-current', 'true');
+
+ await inbox.click();
+ await expect(page.getByTestId('alias-filter')).toHaveText(
+ '{"inboxIds":["owned"]}'
+ );
+ await expect(inbox).toHaveAttribute('aria-current', 'true');
});
- await aliases.nth(0).click();
- await expect(page.getByTestId('alias-filter')).toContainText(
- '"inboxId":"owned"'
- );
- await expect(aliases.nth(0)).toHaveAttribute('aria-current', 'true');
- await aliases.nth(1).click();
- await expect(page.getByTestId('alias-filter')).toContainText(
- '"inboxId":"delegated"'
- );
- await expect(aliases.nth(1)).toHaveAttribute('aria-current', 'true');
- await sidebar.getByRole('button', { name: 'All inboxes' }).click();
- await expect(page.getByTestId('alias-filter')).toHaveText('{}');
});
diff --git a/apps/web/src/features/email-compose/browser-test/ui-shim.ts b/apps/web/src/features/email-compose/browser-test/ui-shim.ts
index 9bf2ea4418..292391fcbd 100644
--- a/apps/web/src/features/email-compose/browser-test/ui-shim.ts
+++ b/apps/web/src/features/email-compose/browser-test/ui-shim.ts
@@ -1,7 +1,9 @@
+export { AvatarGroup } from '../../../components/ui/components/Avatar';
export {
Button,
buttonClasses,
} from '../../../components/ui/components/Button';
+export { ButtonGroup } from '../../../components/ui/components/ButtonGroup';
export { Dialog } from '../../../components/ui/components/Dialog';
export { Dropdown } from '../../../components/ui/components/Dropdown';
export { Panel } from '../../../components/ui/components/Panel';
diff --git a/apps/web/src/features/email-view/components/EmailInboxSelector.tsx b/apps/web/src/features/email-view/components/EmailInboxSelector.tsx
index eb9c29505a..1a7e9dee02 100644
--- a/apps/web/src/features/email-view/components/EmailInboxSelector.tsx
+++ b/apps/web/src/features/email-view/components/EmailInboxSelector.tsx
@@ -6,6 +6,7 @@ import { enableMultiInbox } from '@core/constant/featureFlags';
import { useAddInboxFlow } from '@core/email-link';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { fireAndForget } from '@core/util/fireAndForget';
+import AtIcon from '@icon/system/regular/at.svg';
import CaretDownIcon from '@icon/system/regular/caret-down.svg';
import CheckIcon from '@icon/system/regular/check.svg';
import PlusIcon from '@icon/system/regular/plus.svg';
@@ -31,12 +32,16 @@ type InboxOption = {
photoUrl?: string;
inboxId?: string;
aliasAddress?: string;
+ /** The address of the inbox a send-as alias belongs to. */
+ aliasOf?: string;
};
/**
* Single-select over the user's linked inboxes: one inbox, or all of them.
* `undefined` in view state means all; a chosen inbox is stored as `[id]`.
* Legacy multi-id selections are normalized to their first inbox on restore.
+ * Send-as aliases (which Gmail can add on its own, e.g. for a Gmailify
+ * account) filter their inbox by address; they are never counted as inboxes.
*/
function useInboxSelection() {
const { state, setInboxIds, setAliasFilter } = useEmailView();
@@ -44,41 +49,50 @@ function useInboxSelection() {
const multiInboxFlag = useFeatureFlag(enableMultiInbox);
const addInbox = useAddInboxFlow();
- const options = createMemo((): InboxOption[] =>
- fromInboxOptions(
- linksQuery.isSuccess ? (linksQuery.data?.links ?? []) : []
- ).map((option) => ({
+ const options = createMemo((): InboxOption[] => {
+ const links = linksQuery.isSuccess ? (linksQuery.data?.links ?? []) : [];
+ return fromInboxOptions(links).map((option) => ({
id: option.id,
inboxId: option.inboxId,
label: option.email_address,
photoUrl: option.photo_url ?? undefined,
aliasAddress: option.isAlias ? option.email_address : undefined,
- }))
- );
+ aliasOf: option.isAlias
+ ? links.find((link) => link.id === option.inboxId)?.email_address
+ : undefined,
+ }));
+ });
+ const inboxes = () => options().filter((option) => !option.aliasAddress);
+ const soleInbox = () => (inboxes().length === 1 ? inboxes()[0] : undefined);
const isAll = () => state.inboxIds === undefined && !state.aliasFilter;
// A persisted alias still needs a clear/switch control if it disappears.
- const hasMultipleInboxes = () => options().length > 1 || !!state.aliasFilter;
+ const hasMultipleInboxes = () => inboxes().length > 1 || !!state.aliasFilter;
const isSelected = (id: string) =>
- (options().length === 1 && !state.aliasFilter) || selectedId() === id;
+ (!state.aliasFilter && soleInbox()?.id === id) || selectedId() === id;
const selectedId = () => {
if (state.aliasFilter)
return `${state.aliasFilter.inboxId}:${state.aliasFilter.emailAddress.toLowerCase()}`;
const ids = state.inboxIds;
return ids?.length === 1 ? ids[0] : undefined;
};
- const selectedOption = () => {
+ const selectedOption = (): InboxOption | undefined => {
const id = selectedId();
- return id === undefined
- ? undefined
- : (options().find((option) => option.id === id) ??
- (state.aliasFilter
- ? { id, label: state.aliasFilter.emailAddress }
- : undefined));
+ if (id === undefined) return undefined;
+ const option = options().find((option) => option.id === id);
+ const alias = state.aliasFilter;
+ if (option || !alias) return option;
+ return {
+ id,
+ label: alias.emailAddress,
+ aliasAddress: alias.emailAddress,
+ aliasOf: inboxes().find((inbox) => inbox.id === alias.inboxId)?.label,
+ };
};
return {
options,
+ soleInbox,
/** Keep the connected account visible even when there is no choice to make. */
visible: () => multiInboxFlag().enabled || options().length > 0,
hasMultipleInboxes,
@@ -109,20 +123,51 @@ function useInboxSelection() {
};
}
+/** An alias is another address of an inbox, so it never gets an account avatar. */
function InboxAvatar(props: {
option: InboxOption;
size: UserIconSize;
class?: string;
}) {
return (
- <UserIcon
- {...inboxIconProps(props.option.label)}
- photoUrl={props.option.photoUrl}
- size={props.size}
- class={props.class}
- suppressClick
- showTooltip={false}
- />
+ <Show
+ when={!props.option.aliasAddress}
+ fallback={
+ <AtIcon
+ aria-hidden="true"
+ class={cn('size-4 shrink-0 text-ink-muted', props.class)}
+ />
+ }
+ >
+ <UserIcon
+ {...inboxIconProps(props.option.label)}
+ photoUrl={props.option.photoUrl}
+ size={props.size}
+ class={props.class}
+ suppressClick
+ showTooltip={false}
+ />
+ </Show>
+ );
+}
+
+function InboxOptionLabel(props: { option: InboxOption }) {
+ const title = () =>
+ props.option.aliasOf
+ ? `${props.option.label}, alias of ${props.option.aliasOf}`
+ : props.option.label;
+ return (
+ <span class="flex min-w-0 flex-1 items-baseline gap-1.5" title={title()}>
+ <span class="truncate">{props.option.label}</span>
+ <Show when={props.option.aliasAddress}>
+ <span class="shrink-0 text-xs text-ink-muted">
+ Alias
+ <Show when={props.option.aliasOf}>
+ {(inbox) => <span class="sr-only"> of {inbox()}</span>}
+ </Show>
+ </span>
+ </Show>
+ </span>
);
}
@@ -151,9 +196,7 @@ function InboxAccountGroup(props: {
const selection = props.selection;
const selectedOption = () =>
selection.selectedOption() ??
- (selection.options().length === 1 && selection.isAll()
- ? selection.options()[0]
- : undefined);
+ (selection.isAll() ? selection.soleInbox() : undefined);
const label = () =>
selectedOption()?.label ??
(selection.options().length ? selection.label() : 'No inboxes connected');
@@ -215,7 +258,7 @@ function InboxAccountGroup(props: {
value={option.id}
icon={<InboxAvatar option={option} size="sm" />}
>
- {option.label}
+ <InboxOptionLabel option={option} />
</InboxRadioItem>
)}
</For>
@@ -289,12 +332,7 @@ function InboxAccountList(props: {
<CheckIcon class="size-4 text-accent" />
</Show>
</ViewSidebar.Icon>
- <span
- class={cn('truncate', option.aliasAddress && 'pl-2')}
- title={option.label}
- >
- {option.label}
- </span>
+ <InboxOptionLabel option={option} />
</ViewSidebar.Item>
)}
</For>
@@ -374,7 +412,7 @@ export function EmailInboxFilter(props: { class?: string }) {
value={option.id}
icon={<InboxAvatar option={option} size="sm" />}
>
- {option.label}
+ <InboxOptionLabel option={option} />
</InboxRadioItem>
)}
</For>
@@ -443,7 +481,7 @@ export function EmailInboxMenu(props: { class?: string; grouped?: boolean }) {
value={option.id}
icon={<InboxAvatar option={option} size="sm" />}
>
- {option.label}
+ <InboxOptionLabel option={option} />
</InboxRadioItem>
)}
</For>
@@ -520,7 +558,7 @@ export function EmailInboxDrawerSection(props: { value: string }) {
onChange={() => selection.select(option.id)}
icon={<InboxAvatar option={option} size="sm" />}
>
- {option.label}
+ <InboxOptionLabel option={option} />
</MobileFilterDrawer.Option>
)}
</For>
diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.ts
index 0f50f0508b..0c50f986e4 100644
--- a/apps/web/src/lib/analytics/app-events.ts
+++ b/apps/web/src/lib/analytics/app-events.ts
@@ -224,12 +224,14 @@ export type AppEvents = {
*/
email_message_sent: { isReply: boolean };
/**
- * How the inbox-link OAuth callback ended. `connected` covers re-linking an
- * inbox that was already connected; the client cannot tell them apart.
+ * How the inbox-link OAuth callback ended. `already_connected` is a plain add
+ * whose account chooser returned an inbox the user already had; `connected`
+ * still covers reconnects and calendar upgrades of an existing inbox.
*/
email_link_callback_result: {
outcome:
| 'connected'
+ | 'already_connected'
| 'already_initialized'
| 'shared_inbox_conflict'
| 'payment_required'
diff --git a/apps/web/src/lib/core/email-link/index.ts b/apps/web/src/lib/core/email-link/index.ts
index 333c67a0b2..89f5a81675 100644
--- a/apps/web/src/lib/core/email-link/index.ts
+++ b/apps/web/src/lib/core/email-link/index.ts
@@ -30,6 +30,12 @@ import type { UseQueryResult } from '@tanstack/solid-query';
import { err, okAsync, ResultAsync } from 'neverthrow';
import { createMemo, createSignal, getOwner } from 'solid-js';
import { inboxAuthorizationUrl } from './consent';
+import {
+ announceAlreadyConnected,
+ announceConsentCancelled,
+ announceLinkedInbox,
+ type InboxAddition,
+} from './link-outcome';
import { selectEmailProvider } from './ProviderDialog';
import { rememberInboxLinkReturn } from './return-layout';
import { requestShareInboxConfirmation } from './share-conflict';
@@ -90,18 +96,18 @@ function parseSharedInboxConflict(message: string): {
* Pass `forceShare` to confirm promoting a mailbox another user already connected into
* a shared inbox, after the user accepts the `SharedInboxConflict` prompt.
*
- * @returns ok if syncing was started, err if syncing failed
+ * @returns ok with the id of the inbox now accessible, err if syncing failed
*/
function initEmailLink(args?: {
linkId?: string;
forceShare?: boolean;
-}): ResultAsync<void, EmailInitError> {
+}): ResultAsync<string, EmailInitError> {
return ResultAsync.fromSafePromise(
emailClient.init({ linkId: args?.linkId, forceShare: args?.forceShare })
).andThen((initResult) => {
if (initResult.isErr()) {
if (isPaymentRequired(initResult.error))
- return err<void, EmailInitError>({ tag: 'PaymentRequired' });
+ return err<string, EmailInitError>({ tag: 'PaymentRequired' });
const conflict = initResult.error.find(
(e) => e.code === SHARED_INBOX_CONFLICT_CODE
);
@@ -110,19 +116,19 @@ function initEmailLink(args?: {
tag: 'SharedInboxConflict',
...parseSharedInboxConflict(conflict.message),
};
- return err<void, EmailInitError>(conflictError);
+ return err<string, EmailInitError>(conflictError);
}
if (initResult.error.some((e) => e.code === NO_GMAIL_GRANT_CODE)) {
- return err<void, EmailInitError>({ tag: 'NoGmailGrant' });
+ return err<string, EmailInitError>({ tag: 'NoGmailGrant' });
}
const error: EmailInitError = initResult.error.some(
(e) => e.code === ALREADY_INITIALIZED_CODE
)
? { tag: 'AlreadyInitialized' }
: { tag: 'FailedToInitialize', message: 'Failed to initialize' };
- return err<void, EmailInitError>(error);
+ return err<string, EmailInitError>(error);
}
- return okAsync<void, EmailInitError>(undefined);
+ return okAsync<string, EmailInitError>(initResult.value.link_id);
});
}
@@ -225,6 +231,13 @@ function isTooManyPendingLinks(
const TOO_MANY_PENDING_LINKS_MESSAGE =
'Too many inbox connections in progress.';
+type AddInboxOptions = {
+ scopes?: ConsentScopes;
+ provider?: 'GMAIL' | 'OUTLOOK';
+ reconnectLinkId?: string;
+ emailAddress?: string;
+};
+
/**
* Starts the add-inbox flow: fetches the selected provider's authorization URL and
* navigates the browser to the OAuth consent page. The callback returns to
@@ -245,6 +258,10 @@ const TOO_MANY_PENDING_LINKS_MESSAGE =
* 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.
+ *
+ * A plain add (mailbox consent, no account named) also records the inboxes
+ * already connected, so a chooser that returns one of them is reported as
+ * already connected instead of as a new account.
*/
export function useAddInboxFlow() {
const owner = getOwner();
@@ -253,11 +270,15 @@ export function useAddInboxFlow() {
const { query, initEmailLink } = useEmailLinks();
const { showPaywall } = usePaywallState();
- const completeNativeLink = async (linkId: string, forceShare: boolean) => {
+ const completeNativeLink = async (
+ linkId: string,
+ forceShare: boolean,
+ addition: InboxAddition | undefined
+ ) => {
await initEmailLink({ linkId, forceShare }).match(
- async () => {
+ async (connectedLinkId) => {
await query.refetch();
- toast.success('Account connected');
+ announceLinkedInbox(connectedLinkId, addition);
},
async (error) => {
if (error.tag === 'PaymentRequired') {
@@ -266,6 +287,7 @@ export function useAddInboxFlow() {
}
if (error.tag === 'AlreadyInitialized') {
await query.refetch();
+ announceAlreadyConnected(addition?.provider);
return;
}
if (error.tag === 'SharedInboxConflict' && !forceShare) {
@@ -273,7 +295,10 @@ export function useAddInboxFlow() {
emailAddress: error.emailAddress,
ownerEmail: error.ownerEmail,
onShare: () =>
- fireAndForget(completeNativeLink(linkId, true), 'add-inbox'),
+ fireAndForget(
+ completeNativeLink(linkId, true, addition),
+ 'add-inbox'
+ ),
});
return;
}
@@ -299,6 +324,7 @@ export function useAddInboxFlow() {
const startNativeFlow = async (
scopes: ConsentScopes,
provider: 'GMAIL' | 'OUTLOOK',
+ addition: InboxAddition | undefined,
reconnectLinkId?: string,
emailAddress?: string
) => {
@@ -326,28 +352,47 @@ export function useAddInboxFlow() {
inboxAuthorizationUrl(result.value.authorization_url, emailAddress)
);
if (!auth.success) {
- if (auth.error !== 'User canceled login') {
- toast.failure('Failed to add inbox');
- }
+ if (auth.error === 'User canceled login') announceConsentCancelled();
+ else toast.failure('Failed to add inbox');
return;
}
- await completeNativeLink(result.value.link_id, false);
+ await completeNativeLink(result.value.link_id, false, addition);
+ };
+
+ // Reconnects, account hints, and calendar consent may target an existing
+ // inbox on purpose, so only a plain add compares against connected ones.
+ const plainAddition = async (
+ provider: 'GMAIL' | 'OUTLOOK',
+ scopes: ConsentScopes,
+ options: AddInboxOptions | undefined
+ ): Promise<InboxAddition | undefined> => {
+ if (scopes !== 'gmail' || options?.reconnectLinkId || options?.emailAddress)
+ return undefined;
+ // Without the current list, an existing inbox would read as a new one.
+ const links = queryReadyGate(query)
+ ? query.data.links
+ : (await query.refetch()).data?.links;
+ if (!links) return undefined;
+ return {
+ provider,
+ connectedInboxes: links.map((link) => ({
+ id: link.id,
+ emailAddress: link.email_address,
+ })),
+ };
};
- return async (options?: {
- scopes?: ConsentScopes;
- provider?: 'GMAIL' | 'OUTLOOK';
- reconnectLinkId?: string;
- emailAddress?: string;
- }) => {
+ return async (options?: AddInboxOptions) => {
const scopes = options?.scopes ?? 'gmail';
const provider = options?.provider ?? (await selectEmailProvider(owner));
if (!provider) return;
+ const addition = await plainAddition(provider, scopes, options);
if (isNativeMobilePlatform()) {
await startNativeFlow(
scopes,
provider,
+ addition,
options?.reconnectLinkId,
options?.emailAddress
);
@@ -370,6 +415,7 @@ export function useAddInboxFlow() {
rememberInboxLinkReturn(result.value.link_id, {
url: `${toBaseRelative(window.location.pathname)}${window.location.search}${window.location.hash}`,
scopes,
+ addition,
});
const authorizationUrl = inboxAuthorizationUrl(
result.value.authorization_url,
@@ -415,7 +461,11 @@ export function useEmailLinks() {
query: query,
isConnected: () => hasEmailLinks(query),
initEmailLink: (args?: { linkId?: string; forceShare?: boolean }) =>
- initEmailLink(args).map(startEmailPolling).map(invalidations),
+ initEmailLink(args).map(async (linkId) => {
+ startEmailPolling();
+ await invalidations();
+ return linkId;
+ }),
disconnect: () => disconnectEmail().andTee(invalidations),
resyncInbox: (linkId: string) =>
resyncInbox(linkId).andTee(() => invalidateEmailLinks()),
diff --git a/apps/web/src/lib/core/email-link/link-outcome.ts b/apps/web/src/lib/core/email-link/link-outcome.ts
new file mode 100644
index 0000000000..77a2115d72
--- /dev/null
+++ b/apps/web/src/lib/core/email-link/link-outcome.ts
@@ -0,0 +1,55 @@
+import { toast } from '@core/component/Toast/Toast';
+
+/**
+ * Where a plain add started: its provider and the inboxes already connected.
+ * The provider's account chooser can hand back one of those accounts (for
+ * example a Google Workspace user signed in under a secondary domain); init
+ * then succeeds with the existing inbox and adds nothing, so only this
+ * snapshot tells that apart from a new connection.
+ */
+export type InboxAddition = {
+ provider: 'GMAIL' | 'OUTLOOK';
+ connectedInboxes: { id: string; emailAddress: string }[];
+};
+
+function chooseAnotherAccountHint(provider?: InboxAddition['provider']) {
+ if (provider === 'GMAIL')
+ return 'To add another inbox, choose a different account in Google’s account chooser.';
+ if (provider === 'OUTLOOK')
+ return 'To add another inbox, sign in with a different Microsoft account.';
+ return 'To add another inbox, choose a different account when you sign in.';
+}
+
+export function announceAlreadyConnected(
+ provider?: InboxAddition['provider'],
+ emailAddress?: string
+) {
+ toast.alert(
+ emailAddress
+ ? `${emailAddress} is already connected`
+ : 'This account is already connected',
+ { subtext: chooseAnotherAccountHint(provider) }
+ );
+}
+
+/** Announces a successful init and returns its analytics outcome. */
+export function announceLinkedInbox(
+ linkId: string,
+ addition: InboxAddition | undefined
+): 'connected' | 'already_connected' {
+ const existing = addition?.connectedInboxes.find(
+ (inbox) => inbox.id === linkId
+ );
+ if (addition && existing) {
+ announceAlreadyConnected(addition.provider, existing.emailAddress);
+ return 'already_connected';
+ }
+ toast.success('Account connected');
+ return 'connected';
+}
+
+export function announceConsentCancelled() {
+ toast.alert('Account not connected', {
+ subtext: 'Sign-in was cancelled before access was granted.',
+ });
+}
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.ts
index de7789d5e7..81f6071a95 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
@@ -10,6 +10,9 @@ const mocks = vi.hoisted(() => ({
refetch: vi.fn(),
success: vi.fn(),
failure: vi.fn(),
+ alert: vi.fn(),
+ links: [] as { id: string; email_address: string; provider: string }[],
+ linksLoaded: true,
desktop: false,
mobile: true,
openDesktop: vi.fn(),
@@ -29,7 +32,7 @@ vi.mock('@core/auth/native-auth', () => ({
}),
}));
vi.mock('@core/component/Toast/Toast', () => ({
- toast: { success: mocks.success, failure: mocks.failure },
+ toast: { success: mocks.success, failure: mocks.failure, alert: mocks.alert },
}));
vi.mock('@core/constant/PaywallState', () => ({
PaywallKey: { MULTI_INBOX: 'multi-inbox' },
@@ -50,7 +53,11 @@ vi.mock('@queries/auth/outlook-link', () => ({
vi.mock('@queries/auth/user-info', () => ({ invalidateUserInfo: vi.fn() }));
vi.mock('@queries/email/link', () => ({
invalidateEmailLinks: vi.fn(),
- useEmailLinksQuery: () => ({ refetch: mocks.refetch }),
+ useEmailLinksQuery: () => ({
+ refetch: mocks.refetch,
+ isPending: !mocks.linksLoaded,
+ data: mocks.linksLoaded ? { links: mocks.links } : undefined,
+ }),
}));
vi.mock('@service-email/client', () => ({
emailClient: { init: mocks.provision },
@@ -88,8 +95,12 @@ beforeEach(() => {
})
);
mocks.authenticate.mockResolvedValue({ success: true });
- mocks.provision.mockResolvedValue(ok(undefined));
- mocks.refetch.mockResolvedValue(undefined);
+ mocks.provision.mockResolvedValue(ok({ link_id: 'new-inbox' }));
+ mocks.refetch.mockImplementation(async () => ({
+ data: { links: mocks.links },
+ }));
+ mocks.links = [];
+ mocks.linksLoaded = true;
});
afterEach(() => {
@@ -167,6 +178,27 @@ describe('desktop account linking', () => {
}
);
+ it('stashes the connected inboxes for a plain add so the callback can recognize them', async () => {
+ mocks.links = [
+ {
+ id: 'gmail-inbox',
+ email_address: '[email protected]',
+ provider: 'GMAIL',
+ },
+ ];
+ await useAddInboxFlow()({ provider: 'GMAIL' });
+ expect(consumeInboxLinkReturn('pending-link')).toEqual({
+ url: '/home/~/settings/connections?view=all#selection',
+ scopes: 'gmail',
+ addition: {
+ provider: 'GMAIL',
+ connectedInboxes: [
+ { id: 'gmail-inbox', emailAddress: '[email protected]' },
+ ],
+ },
+ });
+ });
+
it('reports a browser launch failure without provisioning the inbox', async () => {
mocks.openDesktop.mockResolvedValue({ success: false });
await useAddInboxFlow()({ provider: 'GMAIL' });
@@ -262,6 +294,77 @@ describe('native account linking', () => {
expect(mocks.provision).not.toHaveBeenCalled();
expect(mocks.refetch).not.toHaveBeenCalled();
expect(mocks.failure).not.toHaveBeenCalled();
+ expect(mocks.alert).toHaveBeenCalledOnce();
+ });
+
+ it('names the address when a plain add resolves to an inbox that was already connected', async () => {
+ mocks.links = [
+ {
+ id: 'gmail-inbox',
+ email_address: '[email protected]',
+ provider: 'GMAIL',
+ },
+ {
+ id: 'workspace-inbox',
+ email_address: '[email protected]',
+ provider: 'GMAIL',
+ },
+ ];
+ mocks.provision.mockResolvedValue(ok({ link_id: 'workspace-inbox' }));
+ await useAddInboxFlow()({ provider: 'GMAIL' });
+ expect(mocks.alert).toHaveBeenCalledExactlyOnceWith(
+ expect.stringContaining('[email protected]'),
+ expect.anything()
+ );
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+
+ it('loads the inbox list before a plain add when it has not loaded yet', async () => {
+ mocks.linksLoaded = false;
+ mocks.links = [
+ {
+ id: 'gmail-inbox',
+ email_address: '[email protected]',
+ provider: 'GMAIL',
+ },
+ ];
+ mocks.provision.mockResolvedValue(ok({ link_id: 'gmail-inbox' }));
+ await useAddInboxFlow()({ provider: 'GMAIL' });
+ expect(mocks.alert).toHaveBeenCalledExactlyOnceWith(
+ expect.stringContaining('[email protected]'),
+ expect.anything()
+ );
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+
+ it('confirms a reconnect that resolves to the inbox it targeted', async () => {
+ mocks.links = [
+ {
+ id: 'gmail-inbox',
+ email_address: '[email protected]',
+ provider: 'GMAIL',
+ },
+ ];
+ mocks.provision.mockResolvedValue(ok({ link_id: 'gmail-inbox' }));
+ await useAddInboxFlow()({
+ provider: 'GMAIL',
+ reconnectLinkId: 'gmail-inbox',
+ emailAddress: '[email protected]',
+ });
+ expect(mocks.success).toHaveBeenCalledWith('Account connected');
+ expect(mocks.alert).not.toHaveBeenCalled();
+ });
+
+ it('says an already initialized inbox is already connected', async () => {
+ mocks.provision.mockResolvedValue(
+ err([
+ { code: 'ALREADY_INITIALIZED', message: 'User is already initialized' },
+ ])
+ );
+ await useAddInboxFlow()({ provider: 'GMAIL' });
+ expect(mocks.refetch).toHaveBeenCalledOnce();
+ expect(mocks.alert).toHaveBeenCalledOnce();
+ expect(mocks.success).not.toHaveBeenCalled();
});
});
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
index 73eaccbd94..306ab68d8e 100644
--- a/apps/web/src/lib/core/email-link/return-layout.test.ts
+++ b/apps/web/src/lib/core/email-link/return-layout.test.ts
@@ -70,6 +70,20 @@ describe('inbox link return layout', () => {
expect(consumeInboxLinkReturn(LINK_ID)).toBeUndefined();
});
+ it('keeps the stash for a callback that reloads before it leaves', () => {
+ const addition = {
+ provider: 'GMAIL' as const,
+ connectedInboxes: [{ id: 'inbox-1', emailAddress: '[email protected]' }],
+ };
+ rememberInboxLinkReturn(LINK_ID, { url: '/mail', addition });
+
+ readInboxLinkReturn(LINK_ID);
+
+ expect(readInboxLinkReturn(LINK_ID)).toEqual({ url: '/mail', addition });
+ expect(consumeInboxLinkReturn(LINK_ID)).toEqual({ url: '/mail', addition });
+ expect(readInboxLinkReturn(LINK_ID)).toBeUndefined();
+ });
+
it('ignores a stash left behind by a different flow', () => {
rememberInboxLinkReturn('abandoned-link', { url: '/home' });
diff --git a/apps/web/src/lib/core/email-link/return-layout.ts b/apps/web/src/lib/core/email-link/return-layout.ts
index 938d0b66a4..a7426cc038 100644
--- a/apps/web/src/lib/core/email-link/return-layout.ts
+++ b/apps/web/src/lib/core/email-link/return-layout.ts
@@ -1,4 +1,5 @@
import type { ConsentScopes } from '@service-auth/client';
+import type { InboxAddition } from './link-outcome';
const RETURN_LAYOUT_KEY = 'macro:inbox-link:return-layout';
@@ -8,7 +9,7 @@ const CONSENT_SCOPES: ReadonlyArray<ConsentScopes> = [
'calendar',
];
-/** Where the app should land once the inbox consent round trip comes back. */
+/** What the callback needs once the inbox consent round trip comes back. */
export type InboxLinkReturn = {
/**
* The base-relative layout URL the flow started from — path plus query and
@@ -22,12 +23,15 @@ export type InboxLinkReturn = {
* mailbox and calendar together).
*/
scopes?: ConsentScopes;
+ /** Set only for a plain add; see {@link InboxAddition}. */
+ addition?: InboxAddition;
};
type StoredInboxLinkReturn = InboxLinkReturn & { linkId: string };
/**
- * Remember where to return once inbox consent completes.
+ * Remember where to return once inbox consent completes, and for a plain add
+ * which inboxes were already connected.
*
* 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.
@@ -54,9 +58,9 @@ export function rememberInboxLinkReturn(
}
/**
- * Read the layout stashed by {@link rememberInboxLinkReturn} for this link
- * without clearing it. Returns undefined when nothing was stashed or the stash
- * belongs to a different flow.
+ * What {@link rememberInboxLinkReturn} stashed for this link, left in place.
+ * Returns undefined when nothing was stashed or the stash belongs to a
+ * different flow.
*/
export function readInboxLinkReturn(
linkId: string
@@ -73,32 +77,26 @@ export function readInboxLinkReturn(
try {
stored = JSON.parse(raw) as Partial<StoredInboxLinkReturn>;
} catch {
- stored = undefined;
+ return undefined;
}
if (!stored || stored.linkId !== linkId || typeof stored.url !== 'string') {
return undefined;
}
const scopes = CONSENT_SCOPES.find((value) => value === stored.scopes);
- return scopes ? { url: stored.url, scopes } : { url: stored.url };
+ return { url: stored.url, scopes, addition: stored.addition };
}
-/**
- * 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.
- */
+/** Read and clear the stash, as {@link readInboxLinkReturn} reads it. */
export function consumeInboxLinkReturn(
linkId: string
): InboxLinkReturn | undefined {
const stored = readInboxLinkReturn(linkId);
-
// 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 happened.
+ // Storage is unavailable, so there is nothing left to clear.
}
-
return stored;
}
diff --git a/apps/web/src/lib/service-clients/service-email/client.ts b/apps/web/src/lib/service-clients/service-email/client.ts
index ea52f9211a..8bb7f822c3 100644
--- a/apps/web/src/lib/service-clients/service-email/client.ts
+++ b/apps/web/src/lib/service-clients/service-email/client.ts
@@ -38,6 +38,7 @@ import type {
GetAttachmentResponse,
GetScheduledResponse,
GetThreadResponse,
+ InitResponse,
ListBackfillJobsResponse,
ListContactsResponse,
ListEmailFiltersResponse,
@@ -233,7 +234,7 @@ export const emailClient = {
const query = params.toString();
const path = query ? `/email/init?${query}` : '/email/init';
- return fetchWithToken<EmptyResponse, InitErrorCode>(`${emailHost}${path}`, {
+ return fetchWithToken<InitResponse, InitErrorCode>(`${emailHost}${path}`, {
method: 'POST',
// A custom handler replaces safeFetch's default status mapping. 409 carries
// the shared-inbox conflict fields and 400 a machine-readable code; other
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index 1d9d7d5631..81ddaa8ba5 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -1190,7 +1190,11 @@ A failed alias lookup for one inbox does not hide other inboxes' aliases. An
invalid or unavailable selected alias is rejected on save/send, never silently
replaced with the primary address.
-The sidebar and mobile inbox picker also list aliases beneath their inbox.
+The sidebar and mobile inbox picker also list aliases beneath their inbox, as
+address filters rather than accounts: an `@` glyph instead of a portrait, an
+`Alias` label, and `alias of <inbox>` in the accessible name and tooltip. Gmail
+can add a verified alias on its own (for example a Gmailify or "Check mail from
+other accounts" address), so an alias must never look like a connected inbox.
Selecting one scopes mail to that inbox and the exact address in From/To/Cc/Bcc;
search candidates are checked against the same GraphQL scope. Search and Reminders
automatically advance nonmatching candidate pages until a match or exhaustion;
@@ -1200,8 +1204,11 @@ lookup shows an error without discarding already-confirmed rows. If a saved alia
disappears from the catalog, the primary address must not look selected; use
`All inboxes` or choose an available address to clear that scope. Scheduled mail
matches its saved sender. `All inboxes` clears both the inbox and alias selection,
-and the selection survives reloads. With one inbox **and aliases**, the All row
-and address pickers remain available. To check without sending real mail, open
+and the selection survives reloads. Aliases never count toward multiple inboxes:
+with one inbox and aliases there is no `All inboxes` row, the inbox is the
+selected row, and choosing it clears an alias selection. Selecting an alias is a
+filter, so it adds the `from <alias>` header picker, the mobile Inbox section,
+and `All inboxes` until the user clears it. To check without sending real mail, open
both pickers, select an alias, switch to the primary address, reopen a saved alias
draft, and confirm the address remains unchanged. Alias discovery uses
`MailAccounts`, draft saves use `saveEmailDraft`, and delivery uses
@@ -1221,8 +1228,8 @@ sending; the picker never displays another inbox as selected before that choice.
With no explicit selection, an unavailable primary still falls back to
the first linked inbox.
The desktop account dropdown marks the selected inbox with a checkmark. With
-exactly one connected inbox and no aliases, the selector displays its address
-and omits `All inboxes`; the mobile filter drawer has no inbox section. The
+exactly one connected inbox and no alias selected, the selector displays its
+address and omits `All inboxes`; the mobile filter drawer has no inbox section. The
touch sidebar keeps its existing account rows and shows up to four before
scrolling independently. With many accounts, scroll to the last inbox in the
dropdown and check that selecting it updates the selector and header filter.
diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.md
index 28ca8a157c..1f2a1ff798 100644
--- a/docs/agent-guide/login.md
+++ b/docs/agent-guide/login.md
@@ -33,8 +33,18 @@ existing app session and restores the saved layout, including its query and hash
Verify each enabled provider, including reconnects with email-only and calendar
permissions. Check 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.
+canceling leaves the app usable and says nothing was connected. iOS and Android
+continue to use their native authentication sessions.
+
+Every callback outcome is announced on web, desktop, and native. Init also
+succeeds when the provider's account chooser returns an account that is already
+connected (for example a Google Workspace user who signs in under a secondary
+domain): `Connect another account` then reports `<address> is already connected`
+with a hint to pick a different account, instead of `Account connected`. Only a
+plain add (mailbox consent, no reconnect target or login hint) checks this;
+reconnects and calendar upgrades of an existing inbox still report
+`Account connected`. To check, connect an account that is already in the inbox
+list and confirm the alert names it and no new row appears.
A consent that ends without a usable grant returns to the callback with
`email_link_error` instead of a provisionable `link_id`: `cancelled` returns