Rebuild email composer recipient fields as a structured chip input with person resolution and autocomplete (#22668)

# Why

The To/Cc/Bcc fields reused `FormMultiTextFieldInput`, the workflow
Tiptap tag editor, with recipients stored as a comma-separated string.
That caused every reported issue: duplicates were allowed, the field was
locked to one 32px line with a hidden horizontal scrollbar, chips did
nothing on click, `First Last <email>` could not even be typed (space
committed a tag) and was rejected by the backend when pasted, chips
could not be edited, invalid addresses only failed server-side after
pressing Send, and there was no autocomplete at all.

## The model

A recipient is `{ address, displayName? }`. Person and workspace member
are never stored in composer state; they are resolved live from the
address at render time, mirroring how `MatchParticipantService` links
`messageParticipant.handle` to `personId`/`workspaceMemberId` on the
receive side. Entities appear at the edges (autocomplete in, chip
display out); state, dedupe, validation, and send operate on addresses
only. The send path is unchanged: `SendEmailInput.to/cc/bcc` stay
comma-separated bare addresses.

# What changed

New module `activities/emails/recipients/` (the workflow editor is
untouched; its other consumers are unaffected):

- **`EmailRecipientsFieldInput`**: wrapping chip rows (up to ~3 lines,
then scroll), commit on Enter/Tab/comma/semicolon/blur, space commits
only when the buffer is already a valid email, paste parses RFC 5322
lists (names, quoted commas, semicolons, newlines), case-insensitive
dedupe with a flash on the existing chip, invalid addresses become red
chips that disable Send, double-click or keyboard editing in place with
Escape revert, Backspace select-then-delete, arrow-key chip navigation,
Ctrl/Cmd+Enter commits a pending buffer or sends when the buffer is
empty.
- **Person resolution**: chips resolve against People
(`emails.primaryEmail`, case-insensitive) and workspace members,
rendering avatar + name when known and degrading to a plain address chip
otherwise.
- **Chip menu**: person/member header, Copy email, Edit, Remove, and Add
as person for unknown addresses (creates the Person; the chip upgrades
in place).
- **Autocomplete**: blends context people (company you are composing
from, or the company behind a person/opportunity), ranked people search,
workspace members with a Team member badge, and a literal "Use this
email" row ranked first when the typed buffer is a valid address.
Suggestions exclude addresses already present in any field. Enter picks
the highlighted or top row.
- **Prefill**: replies and drafts preserve participant display names
(`getEmailDraftPrefillFromMessage`, `useReplyContext`).
- `useEmailComposerState` holds `EmailRecipient[]` per field and blocks
send on invalid recipients; the recipient-limit warning is surfaced
again in the composer.
- The Send Email engine command passes the record context so context
suggestions work from the record page action.
- `EmailsFilter` was missing from the shared `LeafFilter` union, so
nothing could filter on `emails.primaryEmail`; added (additive).
- New dependency `addressparser@1.0.1` in twenty-front, the same package
and version the server already uses to parse inbound mail headers, so
both sides parse identically. Tiny, dependency-free, browser-safe.

# Decisions and tradeoffs

- Person resolution matches on `emails.primaryEmail` only,
case-insensitively via per-address `ilike` filters (no `%` wildcards,
`%_\` escaped). `additionalEmails` is a JSONB array and not cleanly
filterable through the GraphQL filter API today; the server-side matcher
checks additional emails too, so a chip may show as a plain address even
though the send still links to the person via participant matching.
- Chip flash-on-duplicate replays its CSS animation by remounting the
chip subtree (nonce in the React key), chosen over animation-restart
hacks; the remount is invisible.
- Keyboard chip selection keeps DOM focus on the input and tracks a
virtual `selectedChipIndex` (`aria-activedescendant`) instead of roving
focus across chips: one focus point, no focus juggling, standard
combobox listbox pattern.
- `flushSync` (precedent: `Dropdown.tsx`) focuses and places the caret
after entering chip-edit mode; the alternative was a useEffect on
editing state.
- Suggestion rows `preventDefault` on mousedown so picking a suggestion
never blurs the input (blur would first commit the half-typed buffer as
a junk chip).
- Cmd/Ctrl+Enter inside a recipient field: with a non-empty buffer it
commits the buffer only; with an empty buffer it sends via an `onSubmit`
prop wired to `handleSend`. Not commit+send in one stroke: `handleSend`
holds a same-render closure over composer state, so sending in the same
event would read the pre-commit recipients. E2E also showed the side
panel's own ctrl+Enter hotkey never fires while any form field is
focused (focus-stack scoping, applies to the old composer too), which is
why the field triggers the submit itself.
- Enter with suggestions open picks the highlighted (or top) suggestion,
Gmail-style. When the typed buffer is itself a valid email, the literal
row is ranked first so Enter keeps meaning "add what I typed".
- Suggestions are disabled while editing a chip (the edit buffer holds
`Name <email>` text, a poor search query).
- Dedupe blocks within a field; across fields typed duplicates are
allowed (sometimes intentional), but suggestions exclude addresses
already present in any of To/Cc/Bcc.
- Chip menu actions never navigate: navigating the side panel (or main
view) unmounts the composer and silently destroys the draft, since
composer state is component-local with no draft persistence. "Add as
person" creates the record and shows a snackbar while the chip upgrades
in place; the person header row is informational. "Open person"
navigation should come back once drafts survive navigation.
- The reply composer gets no context record: its widget target record is
the message thread, not a person/company, and replies already prefill
participants.
- If two people share a primary email, the last fetched match wins for
chip display (no ambiguity UI).
- "Add as person" splits the display name on the first space for
firstName/lastName, the same heuristic the contact-creation manager uses
server-side.

# Deferred

- Display names on the wire (`Name <email>` in outbound headers): needs
`SendEmailInput` / `EmailComposerService.validateEmails` changes
server-side.
- Drag chips between To/Cc/Bcc; collapse-on-blur to one line with a "+N
others" summary.
- Frequency/recency ranking of suggestions from `messageParticipant`
aggregates.
- "Open person" from the chip menu, pending draft persistence across
navigation.

# Verification

Unit tests cover the parser, formatter round-trip, merge/dedupe, and the
field state machine (commit, dedupe flash, edit, cancel, keyboard
selection). Typecheck, lint, and the email module suites pass, plus the
shared and side-panel suites.

Every flow was also driven end to end with Playwright against seeded
data: prefill resolution, context and typed suggestions, keyboard
navigation and picks, dedupe flash, RFC 5322 paste, invalid chips gating
Send, wrapping, in-place editing, chip menus, clipboard copy, Add as
person with live chip upgrade, Cc/Bcc exclusions, and the Ctrl+Enter
send path (the mutation reached the server; it failed only on the seeded
account's missing refresh token, expected outside a real provider
connection).

Screenshots of each verified behavior:
https://claude.ai/code/artifact/1743f05d-422e-43d0-bbea-a34a0470c180

---
_Generated by [Claude
Code](https://claude.ai/code/session_0199wDARiw48GqVTpgWzbXWw)_

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/22668?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
This commit is contained in:
Félix Malfait
2026-07-09 13:11:09 +02:00
committed by GitHub
parent 3dd7dfde5a
commit 6897fff632
41 changed files with 2170 additions and 60 deletions
@@ -1,18 +1,40 @@
import { styled } from '@linaria/react';
import { useContext } from 'react';
import { type MouseEvent, type ReactNode, useContext } from 'react';
import { IconX } from 'twenty-ui/icon';
import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';
const StyledChip = styled.div<{ deletable: boolean; danger: boolean }>`
const StyledChip = styled.div<{
deletable: boolean;
danger: boolean;
selected: boolean;
}>`
align-items: center;
background-color: ${({ danger }) =>
danger ? themeCssVariables.color.red3 : themeCssVariables.color.blue3};
border-color: ${({ danger }) =>
danger ? themeCssVariables.color.red5 : themeCssVariables.color.blue5};
background-color: ${({ danger, selected }) =>
selected
? danger
? themeCssVariables.color.red
: themeCssVariables.color.blue
: danger
? themeCssVariables.color.red3
: themeCssVariables.color.blue3};
border-color: ${({ danger, selected }) =>
selected
? danger
? themeCssVariables.color.red
: themeCssVariables.color.blue
: danger
? themeCssVariables.color.red5
: themeCssVariables.color.blue5};
border-radius: ${themeCssVariables.border.radius.smRound};
border-style: solid;
border-width: 1px;
box-sizing: border-box;
color: ${({ danger, selected }) =>
selected
? themeCssVariables.font.color.inverted
: danger
? themeCssVariables.color.red
: themeCssVariables.color.blue};
column-gap: ${themeCssVariables.spacing[1]};
corner-shape: round;
cursor: ${({ deletable }) => (deletable ? 'pointer' : 'default')};
@@ -20,18 +42,35 @@ const StyledChip = styled.div<{ deletable: boolean; danger: boolean }>`
flex-direction: row;
flex-shrink: 0;
height: 20px;
max-width: 100%;
padding-left: ${themeCssVariables.spacing[1]};
padding-right: ${({ deletable }) =>
deletable ? '0' : themeCssVariables.spacing[1]};
user-select: none;
white-space: nowrap;
@keyframes base-chip-flash {
0%,
100% {
filter: none;
}
50% {
filter: brightness(0.85);
}
}
&[data-flashing='true'] {
animation: base-chip-flash 300ms ease-in-out 2;
}
`;
const StyledLabel = styled.span<{ danger: boolean }>`
color: ${({ danger }) =>
danger ? themeCssVariables.color.red : themeCssVariables.color.blue};
const StyledLabel = styled.span<{ maxWidth?: number }>`
line-height: 140%;
max-width: ${({ maxWidth }) =>
maxWidth === undefined ? 'none' : `${maxWidth}px`};
overflow: hidden;
text-overflow: ellipsis;
`;
const StyledDelete = styled.button<{ danger: boolean }>`
@@ -41,8 +80,7 @@ const StyledDelete = styled.button<{ danger: boolean }>`
border-bottom-right-radius: ${themeCssVariables.border.radius.smRound};
border-top-right-radius: ${themeCssVariables.border.radius.smRound};
box-sizing: border-box;
color: ${({ danger }) =>
danger ? themeCssVariables.color.red : themeCssVariables.color.blue};
color: inherit;
corner-shape: round;
cursor: pointer;
display: flex;
@@ -61,29 +99,46 @@ const StyledDelete = styled.button<{ danger: boolean }>`
`;
type BaseChipProps = {
chipId?: string;
label: string;
title?: string;
onRemove?: () => void;
onRemove?: (event: MouseEvent) => void;
removeAriaLabel?: string;
danger?: boolean;
leftIcon?: React.ReactNode;
selected?: boolean;
isFlashing?: boolean;
onDoubleClick?: () => void;
maxLabelWidth?: number;
leftIcon?: ReactNode;
};
export const BaseChip = ({
chipId,
label,
title,
onRemove,
removeAriaLabel = 'Remove',
danger = false,
selected = false,
isFlashing = false,
onDoubleClick,
maxLabelWidth,
leftIcon,
}: BaseChipProps) => {
const { theme } = useContext(ThemeContext);
const isDeletable = onRemove !== undefined;
return (
<StyledChip deletable={isDeletable} danger={danger}>
<StyledChip
id={chipId}
deletable={isDeletable}
danger={danger}
selected={selected}
data-flashing={isFlashing}
onDoubleClick={onDoubleClick}
>
{leftIcon}
<StyledLabel title={title ?? label} danger={danger}>
<StyledLabel title={title ?? label} maxWidth={maxLabelWidth}>
{label}
</StyledLabel>