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-compose): commit the typed recipient and hide automated suggestions (#8799)

teo0e2130a0a6aa
diff --git a/apps/web/src/features/email-compose/primitives/email-composer.test.ts b/apps/web/src/features/email-compose/primitives/email-composer.test.ts
index a0cbc42471..bb6ed6d261 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.test.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.test.ts
@@ -354,6 +354,74 @@ describe('standalone compose controller', () => {
}
});
+ const colleague = {
+ kind: 'custom',
+ data: {
+ email: '[email protected]',
+ invalid: false,
+ },
+ } as const;
+ type Composer = ReturnType<typeof mountEmailComposer>;
+ const sendRequirements = [
+ {
+ type: 'no_recipient',
+ leaveUnmet: (root: Composer) => {
+ root.edit('Ready to send');
+ root.state.context.setRecipients('to', []);
+ },
+ meet: (root: Composer) =>
+ root.state.context.setRecipients('to', [colleague]),
+ },
+ {
+ type: 'no_message',
+ leaveUnmet: (root: Composer) => root.state.context.setSubject('Review'),
+ meet: (root: Composer) => root.edit('Ready to send'),
+ },
+ {
+ type: 'no_subject',
+ leaveUnmet: (root: Composer) => root.edit('Ready to send', ''),
+ meet: (root: Composer) => root.state.context.setSubject('Review'),
+ },
+ ] as const;
+
+ it.each(
+ (['GMAIL', 'OUTLOOK'] as const).flatMap((provider) =>
+ sendRequirements.map((requirement) => ({ provider, ...requirement }))
+ )
+ )(
+ 'clears the $type error in a $provider inbox as soon as the draft meets it',
+ async ({ provider, leaveUnmet, meet, type }) => {
+ const context = createComposeContext();
+ context.accounts.inboxes = () => [
+ {
+ id: 'inbox',
+ email_address: '[email protected]',
+ provider,
+ settings: {},
+ },
+ ];
+ const root = mountEmailComposer(context);
+ try {
+ leaveUnmet(root);
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(root.state.context.validationError(type)).toBeDefined();
+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();
+
+ meet(root);
+ expect(root.state.context.validationError(type)).toBeUndefined();
+
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();
+ } finally {
+ root.dispose();
+ }
+ }
+ );
+
it('keeps a picked time local and preserves it when explicit scheduling fails', async () => {
const context = createComposeContext();
const root = mountEmailComposer(context);
diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.ts
index 3947663e9b..19dc759666 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts
@@ -731,8 +731,35 @@ export function createEmailComposer(props: EmailComposerOptions) {
// --- Send ---
- const [validationError, setValidationError] =
- createSignal<ComposeValidationError | null>(null);
+ const sendRequirements: {
+ error: ComposeValidationError;
+ met: () => boolean;
+ }[] = [
+ {
+ error: {
+ type: 'no_recipient',
+ message: 'Please select at least one recipient',
+ },
+ met: () => form.recipients().to.length > 0,
+ },
+ {
+ error: { type: 'no_message', message: 'Please enter a message' },
+ met: () => !!content().trim(),
+ },
+ {
+ error: { type: 'no_subject', message: 'Please enter a subject' },
+ met: () => !!form.subject()?.trim(),
+ },
+ {
+ error: {
+ type: 'no_link',
+ message: 'Unable to find linked email account. Select a sending inbox.',
+ },
+ met: () => !!link(),
+ },
+ ];
+ const [refusedRequirement, setRefusedRequirement] =
+ createSignal<(typeof sendRequirements)[number]>();
// Snapshot the form before any watermark so an undo can reopen it as it was.
const rememberForUndo = (draftId: string, inboxId: string) => {
@@ -864,43 +891,12 @@ export function createEmailComposer(props: EmailComposerOptions) {
sendLocked()
)
return;
- setValidationError(null);
-
+ const refused = sendRequirements.find((requirement) => !requirement.met());
+ setRefusedRequirement(refused);
const currentEditor = editor();
const currentLink = link();
const recipients = form.recipients();
-
- if (!recipients.to.length) {
- setValidationError({
- type: 'no_recipient',
- message: 'Please select at least one recipient',
- });
- return;
- }
-
- if (!content().trim()) {
- setValidationError({
- type: 'no_message',
- message: 'Please enter a message',
- });
- return;
- }
-
- if (!form.subject()?.trim()) {
- setValidationError({
- type: 'no_subject',
- message: 'Please enter a subject',
- });
- return;
- }
-
- if (!currentLink) {
- setValidationError({
- type: 'no_link',
- message: 'Unable to find linked email account. Select a sending inbox.',
- });
- return;
- }
+ if (refused || !currentLink) return;
const offline = sendRefusalBeforeSave(
props.connectivity,
@@ -1523,10 +1519,9 @@ export function createEmailComposer(props: EmailComposerOptions) {
// Validation
validationError: (type) => {
- if (type === 'no_link' && link()) return undefined;
- const error = validationError();
- if (error?.type === type) return error;
- return undefined;
+ const refused = refusedRequirement();
+ if (refused?.error.type !== type || refused.met()) return undefined;
+ return refused.error;
},
// Recipients
diff --git a/apps/web/src/lib/core/component/RecipientSelector.ranking.test.tsx b/apps/web/src/lib/core/component/RecipientSelector.ranking.test.tsx
new file mode 100644
index 0000000000..d5088c02ba
--- /dev/null
+++ b/apps/web/src/lib/core/component/RecipientSelector.ranking.test.tsx
@@ -0,0 +1,223 @@
+import type { CombinedRecipientItem, WithCustomUserInput } from '@core/user';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { createSignal, type JSX } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { RecipientSelector } from './RecipientSelector';
+
+vi.mock('@core/context/user', () => ({
+ useEmail: () => () => '[email protected]',
+ useUserId: () => () => 'macro|[email protected]',
+}));
+vi.mock('@core/user/dmActivity', () => ({
+ useAugmentUserWithDmActivity: () => (user: unknown) => user,
+}));
+vi.mock('@core/component/HoverCard', () => ({
+ HoverCard: (props: { trigger: JSX.Element }) => <>{props.trigger}</>,
+}));
+vi.mock('@core/component/UserIcon', () => ({ UserIcon: () => null }));
+// jsdom has no layout, so the virtualized list would render no options.
+vi.mock('virtua/solid', async () => {
+ const { For } = await import('solid-js');
+ return {
+ VList: (props: {
+ data: unknown[];
+ children: (item: unknown) => JSX.Element;
+ }) => <For each={props.data}>{props.children}</For>,
+ };
+});
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: vi.fn(),
+ });
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+// Sending inboxes on domains other than the Macro login's.
+const inboxes = [
+ { provider: 'Gmail', address: '[email protected]' },
+ { provider: 'Outlook', address: '[email protected]' },
+] as const;
+
+const recent = new Date(Date.now() - 60 * 60 * 1000);
+
+const contact = (email: string, name: string): CombinedRecipientItem => ({
+ kind: 'contact',
+ id: `macro|${email}`,
+ data: { id: `macro|${email}`, email, name, type: 'extracted' },
+});
+
+const user = (
+ email: string,
+ name: string,
+ lastInteraction?: Date
+): CombinedRecipientItem => ({
+ kind: 'user',
+ id: `macro|${email}`,
+ data: { id: `macro|${email}`, email, name, lastInteraction },
+});
+
+function renderSelector(options: CombinedRecipientItem[], selfEmail: string) {
+ const [selected, setSelected] = createSignal<WithCustomUserInput[]>([]);
+ render(() => (
+ <RecipientSelector
+ options={() => options}
+ selfEmail={selfEmail}
+ selectedOptions={selected()}
+ setSelectedOptions={setSelected}
+ openOnFocus={false}
+ />
+ ));
+ const input = screen.getByRole<HTMLInputElement>('combobox');
+ return {
+ input,
+ selectedEmails: () =>
+ selected().flatMap((option) =>
+ 'email' in option.data ? [option.data.email] : []
+ ),
+ async suggestions() {
+ await screen.findByRole('listbox');
+ return screen.getAllByRole('option').map((o) => o.textContent ?? '');
+ },
+ };
+}
+
+it.each(inboxes)(
+ 'commits the exact known address typed in a $provider inbox on Enter',
+ async ({ address }) => {
+ const selector = renderSelector(
+ [
+ user('[email protected]', 'Teo QA', recent),
+ contact('[email protected]', 'Teo Snyder'),
+ ],
+ address
+ );
+ fireEvent.input(selector.input, { target: { value: '[email protected]' } });
+ await selector.suggestions();
+ fireEvent.keyDown(selector.input, { key: 'Enter' });
+
+ await waitFor(() =>
+ expect(selector.selectedEmails()).toEqual(['[email protected]'])
+ );
+ }
+);
+
+it.each(inboxes)(
+ 'commits a typed address no one is saved under in a $provider inbox on Enter',
+ async ({ address }) => {
+ const selector = renderSelector(
+ [user('[email protected]', 'Teo QA', recent)],
+ address
+ );
+ fireEvent.input(selector.input, { target: { value: '[email protected]' } });
+ await selector.suggestions();
+ fireEvent.keyDown(selector.input, { key: 'Enter' });
+
+ await waitFor(() =>
+ expect(selector.selectedEmails()).toEqual(['[email protected]'])
+ );
+ }
+);
+
+it.each(inboxes)(
+ 'suggests a contact whose name starts with the query near the top in a $provider inbox',
+ async ({ address }) => {
+ const selector = renderSelector(
+ [
+ user('[email protected]', 'Eric Ngabo', recent),
+ user('[email protected]', 'Ligaba Tesfaye', recent),
+ user('[email protected]', 'Gabriel Ortiz', recent),
+ contact('[email protected]', 'Omegabus Lines'),
+ contact('[email protected]', 'Vagabond Cafe'),
+ contact('[email protected]', 'Gab Rowan'),
+ ],
+ address
+ );
+ fireEvent.input(selector.input, { target: { value: 'gab' } });
+
+ const position = (await selector.suggestions()).findIndex((text) =>
+ text.includes('[email protected]')
+ );
+ expect(position).toBeGreaterThanOrEqual(0);
+ expect(position).toBeLessThan(3);
+ }
+);
+
+it.each(inboxes)(
+ 'lists colleagues on the $provider sending domain first',
+ async ({ address }) => {
+ const domain = address.split('@')[1];
+ const selector = renderSelector(
+ [
+ user('[email protected]', 'Sam Lee'),
+ contact(`riley@${domain}`, 'Riley Park'),
+ ],
+ address
+ );
+ fireEvent.keyDown(selector.input, { key: 'ArrowDown' });
+
+ const [first] = await selector.suggestions();
+ expect(first).toContain(`riley@${domain}`);
+ }
+);
+
+const automated = [
+ contact('[email protected]', 'Code Host'),
+ contact('[email protected]', 'Mail Delivery Subsystem'),
+ contact('[email protected]', 'Postmaster'),
+ contact('[email protected]', 'List Bounces'),
+ contact('[email protected]', 'Vendor Billing'),
+ contact('[email protected]', 'Shop Orders'),
+];
+
+it.each(inboxes)(
+ 'leaves automated addresses out of $provider suggestions',
+ async ({ address }) => {
+ const selector = renderSelector(
+ [...automated, contact('[email protected]', 'Nora Jones')],
+ address
+ );
+ fireEvent.input(selector.input, { target: { value: 'example' } });
+
+ const suggestions = await selector.suggestions();
+ expect(suggestions.join(' ')).toContain('Nora Jones');
+ for (const { data } of automated)
+ expect(suggestions.join(' ')).not.toContain(
+ 'email' in data ? data.email : ''
+ );
+ }
+);
+
+it.each(inboxes)(
+ 'adds an automated address typed in full in a $provider inbox',
+ async ({ address }) => {
+ const selector = renderSelector(automated, address);
+ fireEvent.input(selector.input, {
+ target: { value: '[email protected]' },
+ });
+ await selector.suggestions();
+ fireEvent.keyDown(selector.input, { key: 'Enter' });
+
+ await waitFor(() =>
+ expect(selector.selectedEmails()).toEqual(['[email protected]'])
+ );
+ }
+);
diff --git a/apps/web/src/lib/core/component/RecipientSelector.tsx b/apps/web/src/lib/core/component/RecipientSelector.tsx
index edfd79c508..e19967beb1 100644
--- a/apps/web/src/lib/core/component/RecipientSelector.tsx
+++ b/apps/web/src/lib/core/component/RecipientSelector.tsx
@@ -70,6 +70,7 @@ function ChipWithUserTooltip(props: {
function RecipientChip(props: {
icon?: JSX.Element;
label: string;
+ address?: string;
onRemove: () => void;
draggable?: boolean;
onDragStart?: (e: DragEvent) => void;
@@ -84,6 +85,9 @@ function RecipientChip(props: {
>
<Show when={props.icon}>{props.icon}</Show>
<p class="text-sm whitespace-nowrap">{truncateString(props.label, 20)}</p>
+ <Show when={props.address}>
+ {(address) => <span class="sr-only">{address()}</span>}
+ </Show>
<XIcon
class="size-5 hover:bg-hover hover:text-failure p-1 rounded-full"
onClick={props.onRemove}
@@ -127,6 +131,17 @@ function getRecipientOptionEmail(
}
}
+// Notification, bounce and no-reply mailboxes only crowd the suggestions.
+// Typing one in full still offers it as a typed address.
+function isAutomatedAddress(email: string) {
+ const local = email.split('@')[0];
+ return (
+ /^(?:notifications|mailer-daemon|postmaster|bounce)(?:[+._-]|$)/i.test(
+ local
+ ) || /(?:no[._-]?reply|do[._-]?not[._-]?reply)/i.test(local)
+ );
+}
+
function getRecipientOptionName(option: CombinedRecipientItem) {
switch (option.kind) {
case 'user':
@@ -192,6 +207,53 @@ function getRecipientOptionTextValue(option: CombinedRecipientItem) {
}
}
+const RECIPIENT_MATCH_ORDER = [
+ 'address',
+ 'address-start',
+ 'word-start',
+ 'other',
+] as const;
+type RecipientMatch = (typeof RECIPIENT_MATCH_ORDER)[number];
+
+const WORD_BREAK = /[^\p{L}\p{N}]+/u;
+
+function recipientMatch(
+ option: CombinedRecipientItem,
+ query: string,
+ queryWords: string[]
+): RecipientMatch {
+ const email = getRecipientOptionEmail(option)?.toLowerCase();
+ if (email === query) return 'address';
+ if (email && query.includes('@') && email.startsWith(query))
+ return 'address-start';
+ const words = getRecipientOptionTextValue(option)
+ .toLowerCase()
+ .split(WORD_BREAK);
+ if (queryWords.every((part) => words.some((word) => word.startsWith(part))))
+ return 'word-start';
+ return 'other';
+}
+
+// Fuzzy search scores every hit alike, leaving recency and length to decide
+// what Enter commits. Stronger matches go first; the search order breaks ties.
+function rankRecipientMatches<T extends CombinedRecipientItem>(
+ found: T[],
+ query: string
+): T[] {
+ const normalized = query.trim().toLowerCase();
+ if (!normalized) return found;
+ const queryWords = normalized.split(WORD_BREAK).filter(Boolean);
+ return found
+ .map((option) => ({
+ option,
+ rank: RECIPIENT_MATCH_ORDER.indexOf(
+ recipientMatch(option, normalized, queryWords)
+ ),
+ }))
+ .sort((a, b) => a.rank - b.rank)
+ .map(({ option }) => option);
+}
+
type RecipientComboboxItemProps = CollectionNode<CombinedRecipientItem> & {
inviteExternalEmails?: boolean;
};
@@ -485,15 +547,11 @@ export function RecipientSelector<K extends CombinedRecipientKind>(
(props.triedToSubmit?.() ?? false) && props.selectedOptions.length === 0
);
- const currentUserEmail = useEmail();
- const currentUserDomain = createMemo(() => {
- const email = currentUserEmail();
- return email ? email.split('@')[1] : undefined;
- });
+ const selfDomain = createMemo(() => selfEmail()?.split('@')[1]);
const baseRecipientSearchConfig =
FreshSearchPresets.baseUserSearch<CombinedRecipientItem>(
- currentUserDomain,
+ selfDomain,
getRecipientOptionEmail
);
@@ -552,6 +610,15 @@ export function RecipientSelector<K extends CombinedRecipientKind>(
const item = option as CombinedRecipientItem;
const email = getRecipientOptionEmail(item);
+ if (
+ item.kind === 'contact' &&
+ email &&
+ isAutomatedAddress(email) &&
+ !selectedEmails().has(email.toLowerCase())
+ ) {
+ continue;
+ }
+
if (!props.includeSelf) {
const emailLower = email?.toLowerCase();
const matchesSelf =
@@ -599,8 +666,7 @@ export function RecipientSelector<K extends CombinedRecipientKind>(
const searched = searchTerm
? recipientSearch(raw, searchTerm).map((item) => item.item)
: sorted;
-
- const allOptions = [...searched, ...customUsers()];
+ const typed: CombinedRecipientItem[] = [];
// Only add custom input if it doesn't match an existing email
if (
@@ -615,11 +681,13 @@ export function RecipientSelector<K extends CombinedRecipientKind>(
invalid: !EmailValidator.validate(currentUserInput),
};
- const customEntity = recipientEntityMapper('custom')(customUserInput);
- allOptions.push(customEntity);
+ typed.push(recipientEntityMapper('custom')(customUserInput));
}
- return allOptions as CombinedRecipientItem<K>[];
+ return [
+ ...rankRecipientMatches([...searched, ...typed], searchTerm),
+ ...customUsers(),
+ ] as CombinedRecipientItem<K>[];
});
const visibleOptionKeys = createMemo(
@@ -752,6 +820,11 @@ export function RecipientSelector<K extends CombinedRecipientKind>(
/>
}
label={displayText() ?? ''}
+ address={
+ displayText() === email
+ ? undefined
+ : email
+ }
onRemove={() => state.remove(option)}
draggable={!!props.onChipDragStart}
onDragStart={(e) =>
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index 57e5d51d10..8db38fc78b 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -618,6 +618,17 @@ placeholder: Forward keeps its recipients, and Reply turns it into a reply
without the forwarded message. A reply quoting a message that was itself
forwarded stays a reply. Collapsed content is named: **Show forwarded message**
on a forward, **Show quoted text** on a reply.
+Check recipient suggestions from a Gmail and an Outlook inbox. Typing a full
+address and pressing Enter commits that address, ahead of longer matches such
+as `[email protected]`, whether or not it is a saved contact. A name or
+address word that starts with the query ranks above recent substring matches
+(`gab` finds Gab Rowan). Opened empty, the list puts colleagues on the sending
+inbox's domain first. A chip shows the name and its hover card the address.
+Press Send with To empty, then add a recipient: the error clears at once, as a
+missing message or subject error does once filled in. Suggestions leave out
+automated addresses (`notifications@`, `mailer-daemon@`, `postmaster@`,
+`bounce@` and no-reply or do-not-reply addresses); typing one in full still adds
+it. Reply on a bounce goes to its sender, as for any other message.
When checking draft autosave, edit the body of a draft with uploaded or forwarded
attachments, wait for the save, and reopen it; the attachments should remain visible.
In a long thread, scroll away from the bottom while a draft save is pending.