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
feat(email): mobile multi-inbox support (#4011)
gbirman210482eb0a10
diff --git a/js/app/packages/app/component/AddInboxDialog.tsx b/js/app/packages/app/component/AddInboxDialog.tsxindex 653f1a8cbf..5c04fed609 100644--- a/js/app/packages/app/component/AddInboxDialog.tsx+++ b/js/app/packages/app/component/AddInboxDialog.tsx@@ -24,8 +24,14 @@ export function AddInboxDialog() {const handleConfirm = async () => {if (pending()) return;setPending(true);- await addInbox();- setPending(false);+ // On web this navigates away; on native iOS the OAuth completes in place+ // and resolves, so the dialog dismisses itself.+ try {+ await addInbox();+ } finally {+ setPending(false);+ setIsOpen(false);+ }};return (diff --git a/js/app/packages/app/component/EmailAuth.tsx b/js/app/packages/app/component/EmailAuth.tsxindex ff3bfe07ce..e0498f0627 100644--- a/js/app/packages/app/component/EmailAuth.tsx+++ b/js/app/packages/app/component/EmailAuth.tsx@@ -1,14 +1,15 @@import { useAnalytics } from '@app/component/analytics-context';+import { ShareInboxConflictDialog } from '@app/component/ShareInboxConflictDialog';import { updateUserAuth } from '@core/auth';import { redirectToEmailAuth } from '@core/auth/email';import { LoadingBlock } from '@core/component/LoadingBlock';import { toast } from '@core/component/Toast/Toast';import { useSettingsState } from '@core/constant/SettingsState';import { useEmailLinks } from '@core/email-link';+import { isMobile } from '@core/mobile/isMobile';import { whenSettled } from '@core/util/whenSettled';import { invalidateAllAfterLogin } from '@queries/auth/user-info';import { useNavigate, useSearchParams } from '@solidjs/router';-import { Button, Dialog, Panel } from '@ui';import { createSignal, onMount, Show, Suspense } from 'solid-js';type EmailAuthParams = {@@ -111,7 +112,13 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {navigate(props.successPath, { replace: true });};+ // 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 navigateToAccountSettings = () => {+ if (isMobile()) {+ navigateToSuccess();+ return;+ }setActiveTabId('Account');navigate('/component/mail/component/settings', { replace: true });};@@ -123,7 +130,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {// 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('Inbox connected');+ toast.success('Inbox connected', { mobile: true });navigateToAccountSettings();},async (err) => {@@ -142,7 +149,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {});return;}- toast.failure('Failed to add inbox');+ toast.failure('Failed to add inbox', { mobile: true });navigateToSuccess();});@@ -170,56 +177,20 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {return (<Show when={conflict()} fallback={<LoadingBlock />}>{(c) => (- <Dialog+ <ShareInboxConflictDialogopen- onOpenChange={(open) => {- if (!open) {- setConflict(null);- navigateToSuccess();- }+ emailAddress={c().emailAddress}+ ownerEmail={c().ownerEmail}+ onCancel={() => {+ setConflict(null);+ navigateToSuccess();}}- position="center"- class="w-120"- >- <Panel active depth={2} class="rounded-xl">- <Panel.Header class="px-6">- <Dialog.Title class="text-ink text-sm font-semibold">- Share this inbox?- </Dialog.Title>- </Panel.Header>- <Panel.Body class="p-6 font-sans flex flex-col gap-3">- <Dialog.Description class="text-ink-muted text-sm/tight font-normal">- <span class="text-ink">{c().emailAddress}</span> is already- connected by <span class="text-ink">{c().ownerEmail}</span>.- Share it so you both manage one inbox instead of syncing a- duplicate copy.- </Dialog.Description>- <div class="pt-3 justify-end items-center gap-3 inline-flex">- <Button- variant="base"- depth={3}- onClick={() => {- setConflict(null);- navigateToSuccess();- }}- >- Cancel- </Button>- <Button- variant="active"- depth={3}- onClick={() => {- const linkId = c().linkId;- setConflict(null);- void runInit(linkId, true);- }}- >- Share inbox- </Button>- </div>- </Panel.Body>- </Panel>- </Dialog>+ onShare={() => {+ const linkId = c().linkId;+ setConflict(null);+ void runInit(linkId, true);+ }}+ />)}</Show>);diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsxindex fbea455446..2f06a8f711 100644--- a/js/app/packages/app/component/Root.tsx+++ b/js/app/packages/app/component/Root.tsx@@ -2,6 +2,7 @@ import {AnalyticsContextProvider,useAnalytics,} from '@app/component/analytics-context';+import { GlobalShareInboxConflictDialog } from '@app/component/ShareInboxConflictDialog';import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';import { ROUTER_BASE } from '@app/constants/routerBase';import { PosthogProvider, usePosthog } from '@app/lib/analytics/posthog';@@ -517,6 +518,7 @@ export function Root() {<UserContextProvider><BrowserNotificationModal /><IosPushNotificationModal />+ <GlobalShareInboxConflictDialog /><QuerySyncProviderWithUserId /><UserInfoSideEffects /><ConfiguredGlobalAppStateProvider>diff --git a/js/app/packages/app/component/ShareInboxConflictDialog.tsx b/js/app/packages/app/component/ShareInboxConflictDialog.tsxnew file mode 100644index 0000000000..ff66b349ae--- /dev/null+++ b/js/app/packages/app/component/ShareInboxConflictDialog.tsx@@ -0,0 +1,77 @@+import {+ dismissShareInboxConfirmation,+ shareInboxConflict,+} from '@core/email-link/share-conflict';+import { Button, Dialog, Panel } from '@ui';+import { Show } from 'solid-js';++/**+ * Confirmation step before promoting a mailbox another user already connected+ * into a shared inbox.+ */+export function ShareInboxConflictDialog(props: {+ open: boolean;+ emailAddress: string;+ ownerEmail: string;+ onCancel: () => void;+ onShare: () => void;+}) {+ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => {+ if (!open) props.onCancel();+ }}+ position="center"+ class="w-120 max-w-[calc(100vw-2rem)]"+ >+ <Panel active depth={2} class="rounded-xl">+ <Panel.Header class="px-6">+ <Dialog.Title class="text-ink text-sm font-semibold">+ Share this inbox?+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="p-6 font-sans flex flex-col gap-3">+ <Dialog.Description class="text-ink-muted text-sm/tight font-normal">+ <span class="text-ink">{props.emailAddress}</span> is already+ connected by <span class="text-ink">{props.ownerEmail}</span>. Share+ it so you both manage one inbox instead of syncing a duplicate copy.+ </Dialog.Description>+ <div class="pt-3 justify-end items-center gap-3 inline-flex">+ <Button variant="base" depth={3} onClick={() => props.onCancel()}>+ Cancel+ </Button>+ <Button variant="active" depth={3} onClick={() => props.onShare()}>+ Share inbox+ </Button>+ </div>+ </Panel.Body>+ </Panel>+ </Dialog>+ );+}++/**+ * Renders conflicts raised via `requestShareInboxConfirmation` (native+ * add-inbox flow, which completes outside the web callback route). Mounted+ * once at the app root.+ */+export function GlobalShareInboxConflictDialog() {+ return (+ <Show when={shareInboxConflict()}>+ {(conflict) => (+ <ShareInboxConflictDialog+ open+ emailAddress={conflict().emailAddress}+ ownerEmail={conflict().ownerEmail}+ onCancel={dismissShareInboxConfirmation}+ onShare={() => {+ const onShare = conflict().onShare;+ dismissShareInboxConfirmation();+ onShare();+ }}+ />+ )}+ </Show>+ );+}diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsxindex 6057003f4c..52ae50e94b 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx@@ -19,20 +19,25 @@ import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-conteximport { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';import type { ListView } from '@app/constants/list-views';import { isListViewID } from '@app/constants/list-views';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { UserIcon } from '@core/component/UserIcon';import { ScrollIndicators } from '@core/component/VerticalScrollIndicators';+import { ENABLE_MULTI_INBOX_OVERRIDE } from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';+import { useAddInboxFlow } from '@core/email-link';import { Accordion } from '@kobalte/core/accordion';import ChevronDownIcon from '@phosphor/caret-down.svg';import CheckIcon from '@phosphor/check.svg';import CircleDashedIcon from '@phosphor/circle-dashed.svg';import SearchIcon from '@phosphor/magnifying-glass.svg';+import PlusIcon from '@phosphor/plus.svg';import XIcon from '@phosphor/x.svg';import SlidersHorizontalIcon from '@phosphor-icons/core/regular/sliders-horizontal.svg?component-solid';import { useContacts } from '@queries/contacts/contacts';import { Button, cn } from '@ui';import { createMemo, createSignal, For, Show } from 'solid-js';import { ConsolidatedFilterChip } from './consolidated-filter-chip';+import { useInboxPicker } from './inbox-picker';import {buildContactLabel,type FilterOption,@@ -64,8 +69,14 @@ export const MobileFilterDrawer = () => {const { consolidatedFiltersList, resetToTabDefaults } =useFilterRefinements();- const { soup, queryFilters, assigneeFilter, setAssigneeFilter } =- useSoupView();+ const {+ soup,+ queryFilters,+ assigneeFilter,+ setAssigneeFilter,+ inboxFilter,+ setInboxFilter,+ } = useSoupView();const panel = useSplitPanelOrThrow();const contacts = useContacts();const userId = useUserId();@@ -87,6 +98,34 @@ export const MobileFilterDrawer = () => {const isTasksView = () => currentView() === 'tasks';+ const picker = useInboxPicker({+ selectedIds: inboxFilter,+ setSelectedIds: setInboxFilter,+ });+ const multiInboxFlag = useFeatureFlag('enable-multi-inbox', {+ enabledOverride: ENABLE_MULTI_INBOX_OVERRIDE,+ });+ const addInbox = useAddInboxFlow();++ // Mirrors the desktop InboxSelector's visibility rule so the "Add inbox"+ // action stays discoverable with zero or one inbox connected. Also stays+ // visible while a scope is active so it can be reset even if the linked+ // inboxes drop to one.+ const showInboxSection = () =>+ currentView() === 'mail' &&+ (multiInboxFlag().enabled ||+ picker.hasMultiple() ||+ inboxFilter() !== undefined);++ const toggleInbox = (id: string) => {+ const current = picker.activeIds();+ picker.onChange(+ current.includes(id)+ ? current.filter((activeId) => activeId !== id)+ : [...current, id]+ );+ };+const VIEW_SORT_OPTIONS: Partial<Record<ListView, SortOption[]>> = {inbox: DEFAULT_SORT_OPTIONS,agents: DEFAULT_SORT_OPTIONS,@@ -109,7 +148,10 @@ export const MobileFilterDrawer = () => {const setSort = (value: SystemSortOption) => soup.sort.setAll([value]);const hasFiltersOrCategories = () =>- categories().length > 0 || isTasksView() || sortOptions().length > 0;+ categories().length > 0 ||+ isTasksView() ||+ sortOptions().length > 0 ||+ showInboxSection();const toggleFilter = (optionId: FilterOption['id']) => {const wasActive = soup.predicates.isActive(optionId);@@ -272,12 +314,122 @@ export const MobileFilterDrawer = () => {defaultValue={[categories()[0]?.id ?? 'assignee']}>{/* Filter section */}- <Show when={categories().length > 0 || isTasksView()}>+ <Show+ when={+ categories().length > 0 ||+ isTasksView() ||+ showInboxSection()+ }+ ><MobileDrawer.Label class="pt-4">Filters</MobileDrawer.Label></Show>+ <Show when={showInboxSection()}>+ <MobileDrawer.Section+ as={Accordion.Item}+ value="inboxes"+ class="mb-3"+ >+ <Accordion.Header>+ <Accordion.Trigger+ class="w-full flex bg-surface items-center justify-between p-3 text-sm text-ink hover:bg-hover transition-colors outline-none group mb-px"+ onClick={(e) =>+ scrollAccordionItemToTop(e, scrollRef())+ }+ >+ <span class="font-medium">Inboxes</span>+ <div class="flex items-center gap-2">+ <Show when={inboxFilter() !== undefined}>+ <span class="group-data-expanded:hidden size-4 flex items-center justify-center rounded-full bg-accent text-surface text-xxs font-medium leading-none">+ {picker.activeIds().length}+ </span>+ </Show>+ <ChevronDownIcon class="size-3.5 text-ink-muted transition-transform duration-200 group-data-expanded:rotate-180" />+ </div>+ </Accordion.Trigger>+ </Accordion.Header>+ <Accordion.Content>+ <For each={picker.options()}>+ {(option) => {+ const active = () =>+ picker.activeIds().includes(option.id);+ const isSole = () => {+ const ids = picker.activeIds();+ return ids.length === 1 && ids[0] === option.id;+ };+ return (+ <div class="w-full flex items-stretch bg-surface not-last:mb-px">+ <button+ type="button"+ role="checkbox"+ aria-checked={active()}+ class="flex-1 min-w-0 flex items-center gap-3 px-3 py-2.5 text-sm hover:bg-hover transition-colors text-left"+ onClick={() => toggleInbox(option.id)}+ >+ <span+ class={cn(+ 'size-4 flex items-center justify-center shrink-0 rounded border transition-colors',+ active()+ ? 'bg-accent border-accent'+ : 'border-edge'+ )}+ >+ <Show when={active()}>+ <CheckIcon class="size-2.5 text-surface" />+ </Show>+ </span>+ <Show when={option.icon}>+ {(icon) => (+ <span class="size-4 flex items-center justify-center shrink-0">+ {icon()()}+ </span>+ )}+ </Show>+ <span+ class={cn(+ 'flex-1 truncate',+ active() ? 'text-ink' : 'text-ink-muted'+ )}+ >+ {option.label}+ </span>+ </button>+ <Show when={picker.hasMultiple()}>+ <button+ type="button"+ class="shrink-0 px-3 text-xs text-ink-muted hover:text-ink hover:bg-hover transition-colors"+ aria-label={+ isSole()+ ? 'Show all inboxes'+ : `Show only ${option.label}`+ }+ onClick={() => picker.selectOnly(option.id)}+ >+ {isSole() ? 'All' : 'Only'}+ </button>+ </Show>+ </div>+ );+ }}+ </For>+ <Show when={multiInboxFlag().enabled}>+ <button+ type="button"+ class="w-full flex items-center gap-3 px-3 py-2.5 text-sm hover:bg-hover transition-colors text-left bg-surface not-last:mb-px"+ onClick={() => void addInbox()}+ >+ <span class="size-4 flex items-center justify-center shrink-0">+ <PlusIcon class="size-4 text-ink-muted" />+ </span>+ <span class="flex-1 truncate">Add inbox</span>+ </button>+ </Show>+ </Accordion.Content>+ </MobileDrawer.Section>+ </Show>+<div class="flex flex-col"><For each={categories()}>{(category) => {diff --git a/js/app/packages/core/email-link/index.ts b/js/app/packages/core/email-link/index.tsindex 27be32856a..2d289ebf06 100644--- a/js/app/packages/core/email-link/index.ts+++ b/js/app/packages/core/email-link/index.ts@@ -7,6 +7,7 @@ import {import { openEmailAuthPopup } from '@core/auth/email';import { toast } from '@core/component/Toast/Toast';+import { getNativeMobilePlatform } from '@core/util/platform';import { useInitGmailLink } from '@queries/auth';import { invalidateUserInfo } from '@queries/auth/user-info';import { invalidateEmailLinks, useEmailLinksQuery } from '@queries/email/link';@@ -16,8 +17,10 @@ import type {ResyncResponse,} from '@service-email/generated/schemas';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 { requestShareInboxConfirmation } from './share-conflict';const [emailRefetchInterval, setEmailRefetchInterval] = createSignal<number | undefined@@ -196,10 +199,81 @@ export function initAndStartEmailSync() {* Starts the add-inbox flow: fetches the Gmail link authorization URL and* navigates the browser to the OAuth consent page. The callback returns to* `/inbox-link-callback`, which provisions the new link.+ *+ * On native iOS the OAuth runs inline in an `ASWebAuthenticationSession` via+ * the Tauri auth plugin (the app never navigates away), and the link is+ * 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.*/export function useAddInboxFlow() {const initGmailLink = useInitGmailLink();+ const { query, initEmailLink } = useEmailLinks();++ const completeNativeLink = async (linkId: string, forceShare: boolean) => {+ await initEmailLink({ linkId, forceShare }).match(+ async () => {+ await query.refetch();+ toast.success('Inbox connected', { mobile: true });+ },+ async (error) => {+ if (error.tag === 'AlreadyInitialized') {+ await query.refetch();+ return;+ }+ if (error.tag === 'SharedInboxConflict' && !forceShare) {+ requestShareInboxConfirmation({+ emailAddress: error.emailAddress,+ ownerEmail: error.ownerEmail,+ onShare: () => void completeNativeLink(linkId, true),+ });+ return;+ }+ toast.failure('Failed to add inbox', { mobile: true });+ }+ );+ };++ const startNativeFlow = async () => {+ const result = await initGmailLink.mutateAsync(+ 'macro://inbox-link-callback'+ );+ if (result.isErr()) {+ toast.failure('Failed to start Gmail link flow', { mobile: true });+ return;+ }++ let auth: { success: boolean; token?: string; error?: string };+ try {+ auth = await invoke('plugin:auth|authenticate', {+ payload: {+ authUrl: result.value.authorization_url,+ callbackScheme: 'macro',+ ephemeralSession: true,+ },+ });+ } catch (error) {+ console.error('add-inbox authenticate failed', error);+ toast.failure('Failed to add inbox', { mobile: true });+ return;+ }++ if (!auth.success || !auth.token) {+ if (auth.error !== 'User canceled login') {+ toast.failure('Failed to add inbox', { mobile: true });+ }+ return;+ }++ await completeNativeLink(result.value.link_id, false);+ };+return async () => {+ if (getNativeMobilePlatform() === 'ios') {+ await startNativeFlow();+ return;+ }+const callbackUrl = `${window.location.origin}${ROUTER_BASE_CONCAT}inbox-link-callback`;const result = await initGmailLink.mutateAsync(callbackUrl);if (result.isOk()) {diff --git a/js/app/packages/core/email-link/share-conflict.ts b/js/app/packages/core/email-link/share-conflict.tsnew file mode 100644index 0000000000..ce31b8c912--- /dev/null+++ b/js/app/packages/core/email-link/share-conflict.ts@@ -0,0 +1,23 @@+import { createSignal } from 'solid-js';++export type ShareInboxConflictRequest = {+ emailAddress: string;+ ownerEmail: string;+ onShare: () => void;+};++/**+ * Pending shared-inbox confirmation for link flows that complete outside the+ * `/inbox-link-callback` route (native add-inbox). The web callback route+ * renders its own dialog because closing it also navigates away.+ */+const [shareInboxConflict, setShareInboxConflict] =+ createSignal<ShareInboxConflictRequest | null>(null);++export { shareInboxConflict };++export const requestShareInboxConfirmation = (+ request: ShareInboxConflictRequest+) => setShareInboxConflict(request);++export const dismissShareInboxConfirmation = () => setShareInboxConflict(null);diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/google.rsindex 2cf60d6492..d134f1c195 100644--- a/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs@@ -194,8 +194,21 @@ pub(in crate::api::oauth2) async fn handler(.into_response()})?;+ // Strip any stale identifiers embedded in the original_url+ // before appending fresh ones; consumers read the first+ // occurrence of each param.+ let filtered: Vec<(String, String)> = url+ .query_pairs()+ .filter(|(k, _)| k != "link_id" && k != "token")+ .map(|(k, v)| (k.into_owned(), v.into_owned()))+ .collect();+ url.query_pairs_mut().clear().extend_pairs(filtered);++ // `token` mirrors link_id for callback consumers that only+ // surface a `token` query param from the redirect URL.url.query_pairs_mut()- .append_pair("link_id", &link_id.to_string());+ .append_pair("link_id", &link_id.to_string())+ .append_pair("token", &link_id.to_string());return Ok(Redirect::to(url.as_str()).into_response());}