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): compose new emails inside the Email view on desktop (#9501)
Peter Chinman70728fe219ca
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex da6b9386b9..53f0e551aa 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -3,6 +3,10 @@ import { useSpreadsheetAccess } from '@app/features/block-spreadsheet/primitivesimport type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';import type { CreatedCalendarEvent } from '@app/features/calendar/hooks/use-event-editor';import type { CalendarEvent } from '@app/features/calendar/types';+import {+ composePropsFromParams,+ recipientsFromLink,+} from '@app/features/email-compose/compose-params';import { HomeRouteView } from '@app/features/home/route-views';import { parseProjectRoute } from '@app/features/projects/core/route';import { useFeatureFlag } from '@app/lib/analytics/posthog';@@ -390,46 +394,15 @@ registerComponent('channel-compose', () => {});registerComponent('email-compose', (params) => {usePageViewTracking('email-compose');- // mailto: links land here as `component/[email protected],[email protected]`.+ // mailto: links land here as+ // `component/[email protected],[email protected]` on touch;+ // desktop carries `to` into its `/mail/new` route.const toParam = new URLSearchParams(window.location.search).get('to');- const paramsInitialTo = Array.isArray(params.initialTo)- ? params.initialTo.filter(- (value): value is string => typeof value === 'string'- )- : undefined;- const initialTo =- paramsInitialTo ??- toParam- ?.split(',')- .map((e) => e.trim())- .filter(Boolean);- const draftID =- typeof params.draftID === 'string' ? params.draftID : undefined;- const initialInboxId =- typeof params.initialInboxId === 'string'- ? params.initialInboxId- : undefined;- const initialSubject =- typeof params.initialSubject === 'string'- ? params.initialSubject- : undefined;- const initialBodyText =- typeof params.initialBodyText === 'string'- ? params.initialBodyText- : undefined;- const initialAttachments = Array.isArray(params.initialAttachments)- ? params.initialAttachments.filter(- (value): value is File => value instanceof File- )- : undefined;+ const props = composePropsFromParams(params);return (<EmailCompose- draftId={draftID}- initialTo={initialTo}- initialInboxId={initialInboxId}- initialSubject={initialSubject}- initialBodyText={initialBodyText}- initialAttachments={initialAttachments}+ {...props}+ initialTo={props.initialTo ?? recipientsFromLink(toParam)}/>);});diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.tsindex 3b74bd995c..76432c79c6 100644--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts@@ -17,6 +17,7 @@ import {} from '@app/features/drive-view/primitives/drive-route';import { driveDocumentBlockType } from '@app/features/drive-view/primitives/drive-route-schema';import { driveSearch } from '@app/features/drive-view/primitives/drive-search';+import { composeDraftSearch } from '@app/features/email-compose/compose-route-draft';import { URL_PARAMS as EMAIL_URL_PARAMS } from '@app/features/email-thread/core/location';import { EMAIL_DETAIL_SEARCH_NAMESPACE } from '@app/features/email-view/email-route';import {@@ -123,6 +124,11 @@ function redirectLegacyRoutes(.with({ type: 'component', id: CALENDAR_VIEW_ID }, () =>calendarPath(getPreferredCalendarPeriodView()))+ // Desktop writes a new email beside the Email list; touch keeps the+ // full-screen composer.+ .with({ type: 'component', id: 'email-compose' }, () =>+ isTouch ? undefined : '/mail/new'+ ).with({ type: 'component' }, ({ id }) =>routes.byId.has(`view-${id}`) ? `/${id}` : undefined)@@ -217,6 +223,11 @@ function migrateLegacySearch({namespace: EMAIL_DETAIL_SEARCH_NAMESPACE,fields: [[EMAIL_URL_PARAMS.messageId, 'messageId']] as const,}))+ // A `component/email-compose?to=` link names its recipients.+ .with('mail-compose', () => ({+ namespace: composeDraftSearch.namespace,+ fields: [['to', 'to']] as const,+ })).when((id) => id === 'channels-channel' || homeChannel,() => ({diff --git a/apps/web/src/features/email-compose/compose-params.ts b/apps/web/src/features/email-compose/compose-params.tsnew file mode 100644index 0000000000..ad343ebb21--- /dev/null+++ b/apps/web/src/features/email-compose/compose-params.ts@@ -0,0 +1,50 @@+import type { ComponentProps } from 'solid-js';+import type { EmailCompose } from './email-compose';++type EmailComposeProps = ComponentProps<typeof EmailCompose>;++function stringParam(value: unknown): string | undefined {+ return typeof value === 'string' ? value : undefined;+}++/**+ * Recipients a link names as `[email protected],[email protected]`, as mailto:+ * links do.+ */+export function recipientsFromLink(+ value: string | null | undefined+): string[] | undefined {+ const recipients = value+ ?.split(',')+ .map((recipient) => recipient.trim())+ .filter(Boolean);+ return recipients?.length ? recipients : undefined;+}++/**+ * The composer's options from the params a new email opened with. Callers pass+ * them in memory, so a value of the wrong type is dropped rather than trusted.+ */+export function composePropsFromParams(+ params: Record<string, unknown> | undefined+): EmailComposeProps {+ const initialTo = Array.isArray(params?.initialTo)+ ? params.initialTo.filter(+ (value): value is string => typeof value === 'string'+ )+ : undefined;+ const initialAttachments = Array.isArray(params?.initialAttachments)+ ? params.initialAttachments.filter(+ (value): value is File => value instanceof File+ )+ : undefined;++ return {+ draftId: stringParam(params?.draftID),+ initialTo,+ initialInboxId: stringParam(params?.initialInboxId),+ initialSubject: stringParam(params?.initialSubject),+ initialBodyText: stringParam(params?.initialBodyText),+ initialAttachments,+ };+}diff --git a/apps/web/src/features/email-compose/compose-route-draft.ts b/apps/web/src/features/email-compose/compose-route-draft.tsindex 9b20eb90fc..62bffeaa81 100644--- a/apps/web/src/features/email-compose/compose-route-draft.ts+++ b/apps/web/src/features/email-compose/compose-route-draft.ts@@ -1,10 +1,13 @@import { createSearchParams } from '@app/lib/split-router';import { z } from 'zod';+import { recipientsFromLink } from './compose-params';export const composeDraftSearch = {namespace: 'email-compose',- schema: z.object({ draft: z.string() }),- defaults: { draft: '' },+ // `to` holds the recipients a `?to=` link opened the composer with; a link+ // can repeat it.+ schema: z.object({ draft: z.string(), to: z.array(z.string()) }),+ defaults: { draft: '', to: [] as string[] },};/** The compose route's draft, kept in its URL so a reload reopens it. */@@ -12,6 +15,7 @@ export function createComposeRouteDraft() {const [search, setSearch] = createSearchParams(composeDraftSearch);return {draftId: () => search.draft || undefined,+ linkedRecipients: () => recipientsFromLink(search.to.join(',')),record(draftId: string | undefined) {if ((draftId ?? '') === search.draft) return;setSearch({ draft: draftId }, { history: 'replace' });diff --git a/apps/web/src/features/email-compose/email-compose.tsx b/apps/web/src/features/email-compose/email-compose.tsxindex 99984ca673..efab7bff96 100644--- a/apps/web/src/features/email-compose/email-compose.tsx+++ b/apps/web/src/features/email-compose/email-compose.tsx@@ -16,6 +16,7 @@ export function EmailCompose(<EmailComposeView{...props}draftId={draftId}+ initialTo={props.initialTo ?? route.linkedRecipients()}context={composeContext}host={host}/>diff --git a/apps/web/src/features/email-view/components/EmailComposeRouteView.tsx b/apps/web/src/features/email-view/components/EmailComposeRouteView.tsxnew file mode 100644index 0000000000..f29e62b403--- /dev/null+++ b/apps/web/src/features/email-view/components/EmailComposeRouteView.tsx@@ -0,0 +1,40 @@+import { ViewShell } from '@app/components/view-shell';+import { composePropsFromParams } from '@app/features/email-compose/compose-params';+import { EmailCompose } from '@app/features/email-compose/email-compose';+import { t } from '@app/lib/i18n';+import { useEntryProps } from '@app/lib/split-router';+import { usePageViewTracking } from '@components/app/split-layout/split-router/app-route-shell';+import ArrowLeftIcon from '@phosphor/arrow-left.svg';+import { Button } from '@ui';+import { useEmailView } from '../email-view-context';++/**+ * A new email inside the Email view, in the list's place beside the Email+ * sidebar. Back returns to the list.+ */+export function EmailComposeRouteView() {+ usePageViewTracking('email-compose');+ const { closeThread } = useEmailView();+ const props = composePropsFromParams(+ useEntryProps<Record<string, unknown>>()+ );++ return (+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">+ <ViewShell.TopBar>+ <Button+ variant="ghost"+ size="icon-md"+ tooltip={t('commands.goBack')}+ aria-label={t('commands.goBack')}+ onClick={closeThread}+ >+ <ArrowLeftIcon class="size-4" />+ </Button>+ </ViewShell.TopBar>+ <div class="relative min-h-0 min-w-0 flex-1">+ <EmailCompose {...props} />+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/email-view/compose-route.test.ts b/apps/web/src/features/email-view/compose-route.test.tsnew file mode 100644index 0000000000..6717218257--- /dev/null+++ b/apps/web/src/features/email-view/compose-route.test.ts@@ -0,0 +1,131 @@+import {+ createRoutesManifest,+ decodePane,+ type Entry,+ type SplitRoutes,+} from '@app/lib/split-router';+import { paneRoute } from '@app/routes/app-route';+import {+ appRoute,+ emailComposeRoute,+ emailSplitRoute,+ emailThreadRoute,+ legacyContentRoute,+ notFoundRoute,+} from '@app/routes/routes';+import { createAppSplitRouterMiddleware } from '@components/app/split-layout/split-router/app-middleware';+import { describe, expect, it, vi } from 'vitest';++vi.mock('@components/app/split-layout/componentRegistry', () => ({+ resolveComponent: vi.fn(() => ({ type: 'mock-component' })),+}));+vi.mock('@service-storage/websocket', () => ({+ storageWS: { reconnectIfDisconnected: vi.fn() },+ createWebSocketJob: vi.fn(),+}));+vi.mock('@service-connection/websocket', () => ({+ ws: { addEventListener: vi.fn(), send: vi.fn() },+ state: () => 'closed',+ createConnectionBlockWebsocketEffect: vi.fn(),+ createConnectionWebsocketEffect: vi.fn(),+}));++const routes = createRoutesManifest({+ definitions: [+ {+ ...appRoute,+ children: [+ {+ ...emailSplitRoute,+ children: [emailComposeRoute, emailThreadRoute],+ },+ legacyContentRoute,+ notFoundRoute,+ ],+ },+ ],+ defaultRoute: () => paneRoute({ id: emailSplitRoute.id, params: {} }),+} satisfies SplitRoutes);++const legacyCompose: Entry = {+ id: 'entry',+ location: {+ route: paneRoute({+ id: legacyContentRoute.id,+ params: { type: 'component', id: 'email-compose' },+ }),+ },+};++const newEmail: Entry = {+ id: 'entry',+ location: {+ route: paneRoute(+ { id: emailSplitRoute.id, params: {} },+ { id: emailComposeRoute.id, params: {} }+ ),+ },+};++function run(+ to: Entry,+ options: { touch?: boolean; path: string; externalSearch?: string }+) {+ for (const handler of createAppSplitRouterMiddleware({+ isTouchDevice: () => options.touch ?? false,+ })) {+ const result = handler({+ routes,+ from: undefined,+ to,+ path: options.path,+ cause: options.externalSearch ? 'external' : 'navigate',+ externalSearch: options.externalSearch,+ signal: new AbortController().signal,+ redirect: (path) => ({ type: 'redirect', to: path }),+ cancel: () => ({ type: 'cancel' }),+ });+ if (result instanceof Promise) throw new Error('Unexpected async');+ if (result) return result;+ }+ return undefined;+}++describe('new email in the Email view', () => {+ it('opens a new email in the Email view on desktop', () => {+ expect(run(legacyCompose, { path: '/component/email-compose' })).toEqual({+ type: 'redirect',+ to: '/mail/new',+ });+ });++ it('keeps the full-screen composer on touch', () => {+ expect(+ run(legacyCompose, { touch: true, path: '/component/email-compose' })+ ).toBeUndefined();+ });++ it('keeps the recipients a `?to=` link names', () => {+ const result = run(newEmail, {+ path: '/mail/new',+ });+ if (result?.type !== 'redirect') throw new Error('Expected a redirect');+ const url = new URL(result.to, window.location.origin);+ expect(url.pathname).toBe('/mail/new');+ expect(url.searchParams.getAll('s0.email-compose.to')).toEqual([+ '[email protected]',+ ]);+ });++ it('reads /mail/new as a new email, not a thread', () => {+ expect(decodePane(routes, ['mail', 'new'])?.matches.at(-1)?.id).toBe(+ emailComposeRoute.id+ );+ expect(decodePane(routes, ['mail', 'thread-1'])?.matches.at(-1)).toEqual({+ id: emailThreadRoute.id,+ params: { threadId: 'thread-1' },+ });+ });+});diff --git a/apps/web/src/features/email-view/email-view-context.test.tsx b/apps/web/src/features/email-view/email-view-context.test.tsxindex b528a65de4..0e93b8f94d 100644--- a/apps/web/src/features/email-view/email-view-context.test.tsx+++ b/apps/web/src/features/email-view/email-view-context.test.tsx@@ -49,6 +49,7 @@ vi.mock('@app/lib/split-router', async (importOriginal) => ({...(await importOriginal<typeof import('@app/lib/split-router')>()),useNavigate: () => mocks.navigate,useRouteParams: () => mocks.useRouteParams(),+ useMatches: () => () => [],createSearchParams: () => [{get tab() {diff --git a/apps/web/src/features/email-view/email-view-context.tsx b/apps/web/src/features/email-view/email-view-context.tsxindex 0c729c634d..d942386436 100644--- a/apps/web/src/features/email-view/email-view-context.tsx+++ b/apps/web/src/features/email-view/email-view-context.tsx@@ -6,17 +6,23 @@ import {listOwnedSlotName,} from '@app/components/list';import { setSidebarSectionCollapsed } from '@app/components/view-shell';+import { composeDraftSearch } from '@app/features/email-compose/compose-route-draft';import { normalizeFacetSelection } from '@app/features/soup';import { registerListNavigationSource } from '@app/features/soup/collection/list-navigation-source';import { makePersistedState } from '@app/lib/persistence';import {createSearchParams,+ useMatches,useNavigate,useRouteParams,} from '@app/lib/split-router';import { beginInteraction } from '@app/observability/flow';import { usePreference } from '@app/preferences/use-preference';-import { emailSplitRoute, emailThreadRoute } from '@app/routes/routes';+import {+ emailComposeRoute,+ emailSplitRoute,+ emailThreadRoute,+} from '@app/routes/routes';import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import {@@ -114,6 +120,8 @@ export type EmailViewContext = {) => void) => void;selectedThread: Accessor<EmailThreadTarget | undefined>;+ /** A new email is open in the view (desktop). */+ composing: Accessor<boolean>;/** Returns false when inline detail is unavailable so the caller opens a split instead. */openThread: (thread: EmailThreadTarget,@@ -137,6 +145,7 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<const panel = useSplitPanelOrThrow();const navigate = useNavigate();const routeParams = useRouteParams(emailThreadRoute);+ const matches = useMatches();const [tabSearch] = createSearchParams(emailTabSearch);const selectPreview = createPreviewSelectionGuard();const userId = useUserId();@@ -248,6 +257,9 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<return typeof threadId === 'string' ? { id: threadId } : undefined;});+ const composing = () =>+ matches().some((match) => match.id === emailComposeRoute.id);+const opensInline = (options?: EntityDetailNavigationOptions) => {const event = options?.event;return (@@ -261,6 +273,8 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<{ route: emailSplitRoute, params: {} },{search: {+ // A new email's draft stays with its own entry.+ [composeDraftSearch.namespace]: {},[emailTabSearch.namespace]: emailTabSearchCodec.serialize({tab: state.tab,}),@@ -291,6 +305,7 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<{replace: options?.replace,search: {+ [composeDraftSearch.namespace]: {},[emailDetailSearch.namespace]: {},[emailTabSearch.namespace]: emailTabSearchCodec.serialize({tab: state.tab,@@ -481,6 +496,7 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<list,registerListActivationHandler,selectedThread,+ composing,openThread,closeThread,isSidebarSectionOpen,diff --git a/apps/web/src/features/email-view/email-view.tsx b/apps/web/src/features/email-view/email-view.tsxindex 90c20980d9..cf6268507a 100644--- a/apps/web/src/features/email-view/email-view.tsx+++ b/apps/web/src/features/email-view/email-view.tsx@@ -124,7 +124,9 @@ function EmailDesktopLayout(props: {focusList: () => void;setListPane: (pane: EmailListPane | undefined) => void;}) {- const { readingPane } = useEmailView();+ const { readingPane, composing } = useEmailView();+ // A new email takes the list's place, so the reading pane folds away.+ const readerBeside = () => readingPane() && !composing();const [storedListWidth, setListWidth] = usePreference('macro:pref:email:reading-pane-list-width',{ default: LIST_WIDTH.default }@@ -139,7 +141,7 @@ function EmailDesktopLayout(props: {resizableaside={{ preserveDuringResize: false }}main={- readingPane()+ readerBeside()? {preferredWidth: 640,width: listWidth(),@@ -155,7 +157,7 @@ function EmailDesktopLayout(props: {max: 4000,whenNarrow: 'hide',}}- detailOpen={readingPane()}+ detailOpen={readerBeside()}><ViewShell.Aside><EmailSidebar />@@ -219,6 +221,7 @@ function EmailViewRoot() {state,setTab,selectedThread,+ composing,list: listController,readingPane,setReadingPane,@@ -242,10 +245,11 @@ function EmailViewRoot() {tab: () => state.tab,setTab,// Beside the reading pane the list stays on screen with a thread open;- // without it an open thread replaces the list.+ // without it a thread replaces the list, as a new email always does.listHasKeyboard: () => {const pane = listPane();- return pane ? !pane.readerHasKeyboard() : selectedThread() === undefined;+ if (pane) return !pane.readerHasKeyboard();+ return selectedThread() === undefined && !composing();},hasSelection: () => listController.selection.count() > 0,});diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsxindex 7f3e4ed086..1b7ee9be18 100644--- a/apps/web/src/routes/app-router-view.tsx+++ b/apps/web/src/routes/app-router-view.tsx@@ -51,6 +51,7 @@ import {DriveCallRouteView,DriveDetailView,DriveRouteView,+ EmailComposeRouteView,EmailDetailRouteView,FoldersRouteView,FormRespondRoutePage,@@ -118,6 +119,7 @@ import {driveSplitRoute,driveTabDocumentRoute,driveTabRoute,+ emailComposeRoute,emailSignupCallbackRoute,emailSplitRoute,emailThreadRoute,@@ -372,6 +374,10 @@ export function AppRouterView() {component={MailRouteView}loading={EmailViewSkeleton}>+ <Route+ definition={emailComposeRoute}+ component={EmailComposeRouteView}+ /><Routedefinition={emailThreadRoute}component={EmailDetailRouteView}diff --git a/apps/web/src/routes/lazy-route-views.ts b/apps/web/src/routes/lazy-route-views.tsindex 9735c05ae2..8be626462b 100644--- a/apps/web/src/routes/lazy-route-views.ts+++ b/apps/web/src/routes/lazy-route-views.ts@@ -55,6 +55,10 @@ export const DriveRouteView = lazyNamed(() => import('@app/features/drive-view/route-views'),'DriveRouteView');+export const EmailComposeRouteView = lazyNamed(+ () => import('@app/features/email-view/components/EmailComposeRouteView'),+ 'EmailComposeRouteView'+);export const EmailDetailRouteView = lazyNamed(() => import('@app/features/email-view/components/EmailDetailView'),'EmailDetailRouteView'diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.tsindex 214e6f52a5..b83b04a687 100644--- a/apps/web/src/routes/routes.ts+++ b/apps/web/src/routes/routes.ts@@ -508,6 +508,14 @@ export const agentsViewRoute = defineRoute({claim: () => ({ namespace: 'component', id: 'agents' }),});+/** A new email, composed beside the list on desktop. */+export const emailComposeRoute = defineRoute({+ id: 'mail-compose',+ path: 'new',+ // Each open is a fresh composer, even in a Mail view already composing.+ remountKey: (_params, { entryId }) => entryId,+});+export const emailThreadRoute = defineRoute({id: 'mail-thread',path: ':threadId',diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 4c26e9c3f5..952ceac93a 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -600,6 +600,15 @@ Opening a saved draft from **Drafts** shows the title menu beside Back, sincethe composer has no subject line above it, and keeps the applicable headercontrols. Verify these remainavailable when returning to Drafts and reopening the draft.+On desktop a new email opens inside the Email view at `/app/mail/new`, from+Email's **New**, the app's New menu, a `mailto:` link, a calendar event's+guest email, or the agent's send-email card: the composer takes the list's+place beside the Email sidebar, and the reading pane folds away while it is+open. Its Back arrow returns to the list. Replies stay in their thread. Touch+keeps the full-screen composer. Check with the reading pane on and off that+the sidebar stays usable while composing, that Back and sidebar tabs return+to the list without the draft in its URL, that reloading keeps the draft, and+that a second **New** starts an empty composer.**Delete** in the title menu moves the thread to Trash and returns to the samefiltered list. Its toast offers **Undo** to restore the email.**Sender → Signal**, **Sender → Noise** and **Block Sender**, and the senderdiff --git a/docs/architecture/email.md b/docs/architecture/email.mdindex ef50a7e005..cca6261ec2 100644--- a/docs/architecture/email.md+++ b/docs/architecture/email.md@@ -59,7 +59,9 @@ may import a block package, `@core/block`, or block-related signal modules.supplied contexts. It imports no production entry point for a nestedmessage or composer.- `email-compose/email-compose.tsx` supplies the production compose context and split-host- callbacks to `views/email-compose.tsx`. Inline replies use+ callbacks to `views/email-compose.tsx`. Desktop mounts it in the Email view's+ `mail-compose` route (`email-view/components/EmailComposeRouteView.tsx`);+ touch keeps the `email-compose` component split. Inline replies use`views/reply-input.tsx` with explicit capabilities and a reply session.`email-thread/views/thread-reply-input.tsx` owns the keyed reply lifetime;`email-compose/primitives/reply-composer.ts` owns the compose workflow.