Skip to content

The open alternative to Salesforce, designed for AI.

Add email approval review (#28691)

Raphaël Bosi35d68da9b07a
diff --git a/packages/twenty-front/src/modules/activities/components/ComposerFieldRow.tsx b/packages/twenty-front/src/modules/activities/components/ComposerFieldRow.tsx
index f2135714cf3..85023b52226 100644
--- a/packages/twenty-front/src/modules/activities/components/ComposerFieldRow.tsx
+++ b/packages/twenty-front/src/modules/activities/components/ComposerFieldRow.tsx
@@ -10,6 +10,7 @@ const NESTED_CONTROL_SELECTOR = doNotTranslate(
type ComposerFieldRowProps = {
label: string;
children: ReactNode;
+ isLabelVisible?: boolean;
trailing?: ReactNode;
hasDivider?: boolean;
onClick?: MouseEventHandler<HTMLDivElement>;
@@ -18,6 +19,7 @@ type ComposerFieldRowProps = {
export const ComposerFieldRow = ({
label,
children,
+ isLabelVisible = true,
trailing,
hasDivider,
onClick,
@@ -42,7 +44,8 @@ export const ComposerFieldRow = ({
return (
<FormFieldRow
- label={label}
+ label={isLabelVisible ? label : undefined}
+ aria-label={label}
hasDivider={hasDivider}
isHoverable={isDefined(onClick)}
onClick={isDefined(onClick) ? handleClick : undefined}
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx
index c3f9784a412..e469654e78d 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx
@@ -6,6 +6,7 @@ import { type UploadErrorHandler } from '@/advanced-text-editor/types/UploadErro
import { type UploadedFile } from '@/advanced-text-editor/types/UploadedFile';
import { type UploadedImage } from '@/advanced-text-editor/types/UploadedImage';
import { serializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeAdvancedTextEditorDocument';
+import { syncAdvancedTextEditorState } from '@/advanced-text-editor/utils/syncAdvancedTextEditorState';
import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';
import { type VariablePickerComponent } from '@/ui/input/types/VariablePickerComponent';
import { useFullScreenModal } from '@/ui/layout/fullscreen/hooks/useFullScreenModal';
@@ -17,8 +18,9 @@ import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentTyp
import { css } from '@linaria/core';
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
+import { isUndefined } from '@sniptt/guards';
import { type Editor } from '@tiptap/core';
-import { type ComponentType, useEffect, useId, useState } from 'react';
+import { type ComponentType, useCallback, useId, useState } from 'react';
import { flushSync } from 'react-dom';
import { isDefined } from 'twenty-shared/utils';
import { doNotTranslate } from 'twenty-shared/i18n';
@@ -96,7 +98,9 @@ type FormAdvancedTextFieldInputProps = {
label?: string;
error?: string;
hint?: string;
- defaultValue: string | undefined | null;
+ defaultValue?: string | null;
+ value?: string | null;
+ 'aria-label'?: string;
onChange?: (value: string) => void;
readonly?: boolean;
placeholder?: string;
@@ -118,6 +122,8 @@ export const FormAdvancedTextFieldInput = ({
error,
hint,
defaultValue,
+ value,
+ 'aria-label': ariaLabel,
placeholder,
onChange,
readonly,
@@ -136,6 +142,7 @@ export const FormAdvancedTextFieldInput = ({
const { chrome, variant, minHeight: profileMinHeight } = profile;
const editorMinHeight = minHeight ?? profileMinHeight;
+ const accessibleLabel = ariaLabel ?? label;
const isFullScreenEnabled = enableFullScreen ?? profile.enableFullScreen;
const instanceId = useId();
@@ -155,7 +162,16 @@ export const FormAdvancedTextFieldInput = ({
profile,
placeholder: placeholder,
readonly,
- defaultValue,
+ defaultValue: isUndefined(value) ? defaultValue : value,
+ editorProps: {
+ attributes: {
+ 'aria-multiline': 'true',
+ role: 'textbox',
+ ...(isDefined(accessibleLabel)
+ ? { 'aria-label': accessibleLabel }
+ : {}),
+ },
+ },
onUpdate: (editor) => {
onChange?.(serializeAdvancedTextEditorDocument(editor));
},
@@ -180,14 +196,6 @@ export const FormAdvancedTextFieldInput = ({
onFileUploadError,
});
- useEffect(() => {
- onEditorReady?.(editor);
-
- return () => {
- onEditorReady?.(null);
- };
- }, [editor, onEditorReady]);
-
const handleFullScreenChange = (isFullScreenOpen: boolean) => {
flushSync(() => {
setIsFullScreen(isFullScreenOpen);
@@ -228,6 +236,29 @@ export const FormAdvancedTextFieldInput = ({
hasClosePageButton: !isMobile,
});
+ const handleEditorReady = useCallback(
+ (container: HTMLDivElement | null) => {
+ onEditorReady?.(isDefined(container) ? editor : null);
+ },
+ [editor, onEditorReady],
+ );
+
+ const handleEditorContainerChange = useCallback(
+ (container: HTMLDivElement | null) => {
+ if (!isDefined(container) || !isDefined(editor)) {
+ return;
+ }
+
+ syncAdvancedTextEditorState({
+ editor,
+ value,
+ readonly,
+ parseLegacyDocument: profile.parseLegacyDocument,
+ });
+ },
+ [editor, value, readonly, profile.parseLegacyDocument],
+ );
+
if (!isDefined(editor)) {
return null;
}
@@ -251,6 +282,7 @@ export const FormAdvancedTextFieldInput = ({
return (
<>
<StyledAdvancedTextFieldContainerWrapper
+ ref={handleEditorReady}
hasFieldChrome={chrome === 'field'}
>
<FormFieldInputContainer
@@ -264,6 +296,7 @@ export const FormAdvancedTextFieldInput = ({
<StyledAdvancedTextFieldFieldContainer>
<StyledAdvancedTextFieldInnerContainer
+ ref={handleEditorContainerChange}
hasFieldChrome={chrome === 'field'}
>
{!isFullScreen && (
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/FormAdvancedTextFieldInput.stories.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/FormAdvancedTextFieldInput.stories.tsx
index fedf426028c..b5536bd25b9 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/FormAdvancedTextFieldInput.stories.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/FormAdvancedTextFieldInput.stories.tsx
@@ -207,17 +207,33 @@ export const Interactive: Story = {
...DEFAULT_PROPS,
label: 'Interactive Field',
placeholder: 'Start typing to see the editor in action...',
+ onEditorReady: fn(),
},
- play: async ({ canvasElement }) => {
+ play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
expect(await canvas.findByText('Interactive Field')).toBeVisible();
const editor = await canvas.findByRole('textbox');
expect(editor).toBeVisible();
+ expect(args.onEditorReady).toHaveBeenCalledTimes(1);
await userEvent.click(editor);
await userEvent.type(editor, 'Hello World!');
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Expand to full screen' }),
+ );
+
+ const fullScreenEditor = await body.findByRole('textbox');
+
+ await expect(fullScreenEditor).toHaveTextContent('Hello World!');
+ await userEvent.type(fullScreenEditor, ' Still working.');
+ await userEvent.click(body.getByRole('button', { name: 'Close page' }));
+ await expect(await canvas.findByRole('textbox')).toHaveTextContent(
+ 'Hello World! Still working.',
+ );
+ await expect(args.onEditorReady).toHaveBeenCalledTimes(1);
},
};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/syncAdvancedTextEditorState.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/syncAdvancedTextEditorState.ts
new file mode 100644
index 00000000000..a595dcceecd
--- /dev/null
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/syncAdvancedTextEditorState.ts
@@ -0,0 +1,45 @@
+import { isUndefined } from '@sniptt/guards';
+import { type Editor } from '@tiptap/core';
+
+import { type AdvancedTextEditorLegacyDocumentParser } from '@/advanced-text-editor/types/AdvancedTextEditorLegacyDocumentParser';
+import { deserializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/deserializeAdvancedTextEditorDocument';
+import { serializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeAdvancedTextEditorDocument';
+
+export const syncAdvancedTextEditorState = ({
+ editor,
+ value,
+ readonly,
+ parseLegacyDocument,
+}: {
+ editor: Editor;
+ value: string | null | undefined;
+ readonly: boolean | undefined;
+ parseLegacyDocument?: AdvancedTextEditorLegacyDocumentParser;
+}) => {
+ if (editor.isDestroyed) {
+ return;
+ }
+
+ const isEditable = !readonly;
+
+ if (editor.isEditable !== isEditable) {
+ editor.setEditable(isEditable, false);
+ }
+
+ if (isUndefined(value)) {
+ return;
+ }
+
+ const serializedDocument = value ?? '';
+
+ if (serializeAdvancedTextEditorDocument(editor) === serializedDocument) {
+ return;
+ }
+
+ const content = deserializeAdvancedTextEditorDocument({
+ serializedDocument,
+ parseLegacyDocument,
+ });
+
+ editor.commands.setContent(content, { emitUpdate: false });
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatApprovalConfirmation.tsx b/packages/twenty-front/src/modules/ai/components/AiChatApprovalConfirmation.tsx
index 93b194c7d07..8daa18ba34b 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatApprovalConfirmation.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatApprovalConfirmation.tsx
@@ -1,5 +1,6 @@
import { styled } from '@linaria/react';
import { Plural, useLingui } from '@lingui/react/macro';
+import { type ReactNode } from 'react';
import { Button } from 'twenty-ui/primitives/input';
import { AlertDialog } from 'twenty-ui/primitives/surfaces';
import { themeCssVariables } from 'twenty-ui/theme';
@@ -28,6 +29,7 @@ type AiChatApprovalConfirmationProps = {
onConfirm: () => void;
onCancel: () => void;
disabled?: boolean;
+ selectionSummary?: ReactNode;
};
export const AiChatApprovalConfirmation = ({
@@ -35,6 +37,7 @@ export const AiChatApprovalConfirmation = ({
onConfirm,
onCancel,
disabled = false,
+ selectionSummary,
}: AiChatApprovalConfirmationProps) => {
const { t } = useLingui();
const cardCount = cards.length;
@@ -69,7 +72,8 @@ export const AiChatApprovalConfirmation = ({
/>
</AlertDialog.Title>
<AlertDialog.Description>
- {t`${selectedCount} records selected · ${skippedCount} records skipped`}
+ {selectionSummary ??
+ t`${selectedCount} records selected · ${skippedCount} records skipped`}
</AlertDialog.Description>
</AlertDialog.Header>
<AlertDialog.Body>
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailConfirmation.tsx b/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailConfirmation.tsx
new file mode 100644
index 00000000000..7f15d75583d
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailConfirmation.tsx
@@ -0,0 +1,37 @@
+import { Plural } from '@lingui/react/macro';
+
+import { AiChatApprovalConfirmation } from '@/ai/components/AiChatApprovalConfirmation';
+import { type AiChatApprovalReviewEmail } from '@/ai/types/AiChatApprovalReviewEmail';
+
+type AiChatApprovalEmailConfirmationProps = {
+ emails: readonly AiChatApprovalReviewEmail[];
+ onConfirm: () => void;
+ onCancel: () => void;
+ disabled?: boolean;
+};
+
+export const AiChatApprovalEmailConfirmation = ({
+ emails,
+ onConfirm,
+ onCancel,
+ disabled = false,
+}: AiChatApprovalEmailConfirmationProps) => (
+ <AiChatApprovalConfirmation
+ cards={emails.map((email) => ({
+ id: email.id,
+ title: email.draft.subject,
+ selectedCount: 1,
+ skippedCount: 0,
+ }))}
+ selectionSummary={
+ <Plural
+ value={emails.length}
+ one="# email selected · 0 emails skipped"
+ other="# emails selected · 0 emails skipped"
+ />
+ }
+ onConfirm={onConfirm}
+ onCancel={onCancel}
+ disabled={disabled}
+ />
+);
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailReview.tsx b/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailReview.tsx
new file mode 100644
index 00000000000..79b57d554e7
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailReview.tsx
@@ -0,0 +1,108 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { Button, Input } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { ComposerFieldRow } from '@/activities/components/ComposerFieldRow';
+import { INLINE_EMAIL_BODY_EDITOR_PROFILE } from '@/activities/emails/editor/constants/InlineEmailBodyEditorProfile';
+import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
+import { AiChatEmailRecipientsRow } from '@/ai/components/internal/AiChatEmailRecipientsRow';
+import { type AiChatApprovalReviewEmailDraft } from '@/ai/types/AiChatApprovalReviewEmailDraft';
+
+const StyledEmail = styled.div`
+ background: ${themeCssVariables.background.primary};
+ border: 1px solid ${themeCssVariables.border.color.medium};
+ border-radius: ${themeCssVariables.border.radius.sm};
+ min-width: 0;
+`;
+
+const StyledBody = styled.div`
+ padding: ${themeCssVariables.spacing[1]} ${themeCssVariables.spacing[2]};
+`;
+
+type AiChatApprovalEmailReviewProps = {
+ draft: AiChatApprovalReviewEmailDraft;
+ onDraftChange: (draft: AiChatApprovalReviewEmailDraft) => void;
+ disabled?: boolean;
+};
+
+export const AiChatApprovalEmailReview = ({
+ draft,
+ onDraftChange,
+ disabled = false,
+}: AiChatApprovalEmailReviewProps) => {
+ const { t } = useLingui();
+ const isCcBccShown =
+ draft.isCcBccExpanded ||
+ isNonEmptyArray(draft.cc) ||
+ isNonEmptyArray(draft.bcc);
+
+ const updateDraft = (changes: Partial<AiChatApprovalReviewEmailDraft>) => {
+ if (disabled) {
+ return;
+ }
+
+ onDraftChange({ ...draft, ...changes });
+ };
+
+ return (
+ <StyledEmail>
+ <AiChatEmailRecipientsRow
+ label={t`To`}
+ isLabelVisible={false}
+ recipients={draft.to}
+ disabled={disabled}
+ onChange={(to) => updateDraft({ to })}
+ trailing={
+ !isCcBccShown && (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={disabled}
+ onClick={() => updateDraft({ isCcBccExpanded: true })}
+ >
+ {t`Cc/Bcc`}
+ </Button>
+ )
+ }
+ />
+ {isCcBccShown && (
+ <>
+ <AiChatEmailRecipientsRow
+ label={t`Cc`}
+ recipients={draft.cc}
+ disabled={disabled}
+ onChange={(cc) => updateDraft({ cc })}
+ />
+ <AiChatEmailRecipientsRow
+ label={t`Bcc`}
+ recipients={draft.bcc}
+ disabled={disabled}
+ onChange={(bcc) => updateDraft({ bcc })}
+ />
+ </>
+ )}
+ <ComposerFieldRow label={t`Subject`} isLabelVisible={false}>
+ <Input
+ variant="plain"
+ aria-label={t`Subject`}
+ placeholder={t`Subject`}
+ value={draft.subject}
+ disabled={disabled}
+ onChange={(event) => updateDraft({ subject: event.target.value })}
+ />
+ </ComposerFieldRow>
+ <StyledBody role="group" aria-label={t`Body`}>
+ <FormAdvancedTextFieldInput
+ value={draft.body}
+ aria-label={t`Body`}
+ onChange={(body) => updateDraft({ body })}
+ readonly={disabled}
+ placeholder={t`Write the email`}
+ profile={INLINE_EMAIL_BODY_EDITOR_PROFILE}
+ />
+ </StyledBody>
+ </StyledEmail>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailReviewDeck.tsx b/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailReviewDeck.tsx
new file mode 100644
index 00000000000..65a102518ee
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailReviewDeck.tsx
@@ -0,0 +1,88 @@
+import { Plural, useLingui } from '@lingui/react/macro';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { IconMail } from 'twenty-ui/icon';
+
+import { AiChatApprovalEmailReview } from '@/ai/components/AiChatApprovalEmailReview';
+import { AiChatApprovalReviewDeck } from '@/ai/components/AiChatApprovalReviewDeck';
+import { type AiChatApprovalReviewCard } from '@/ai/types/AiChatApprovalReviewCard';
+import { type AiChatApprovalReviewEmail } from '@/ai/types/AiChatApprovalReviewEmail';
+import { type AiChatApprovalReviewEmailDraft } from '@/ai/types/AiChatApprovalReviewEmailDraft';
+
+const EMAIL_REVIEW_ICON_SIZE = 16;
+
+type AiChatApprovalEmailReviewDeckProps = {
+ emails: readonly AiChatApprovalReviewEmail[];
+ activeIndex: number;
+ onActiveIndexChange: (index: number) => void;
+ onDraftChange: (change: {
+ emailId: string;
+ draft: AiChatApprovalReviewEmailDraft;
+ }) => void;
+ onRequestApproval: (emailIds: string[]) => void;
+ onSkip: (emailId: string) => void;
+ disabled?: boolean;
+};
+
+export const AiChatApprovalEmailReviewDeck = ({
+ emails,
+ activeIndex,
+ onActiveIndexChange,
+ onDraftChange,
+ onRequestApproval,
+ onSkip,
+ disabled = false,
+}: AiChatApprovalEmailReviewDeckProps) => {
+ const { t } = useLingui();
+ const pendingEmailCount = emails.filter(
+ (email) => email.status === 'pending',
+ ).length;
+ const cards: AiChatApprovalReviewCard[] = emails.map((email, index) => {
+ const remainingDraftCount = emails
+ .slice(index + 1)
+ .filter((draft) => draft.status === 'pending').length;
+
+ return {
+ id: email.id,
+ title: t`Send email`,
+ icon: <IconMail size={EMAIL_REVIEW_ICON_SIZE} />,
+ approveLabel: t`Send`,
+ denyLabel: t`Skip`,
+ selectedCount: 1,
+ isApprovalDisabled: !isNonEmptyArray(email.draft.to),
+ skippedCount: 0,
+ status: email.status,
+ outcomeMessage: email.outcomeMessage,
+ progress: email.progress,
+ hint: isNonEmptyArray(email.draft.to) ? (
+ <Plural
+ value={remainingDraftCount}
+ _0="No more drafts after this one"
+ one="# more draft after this one"
+ other="# more drafts after this one"
+ />
+ ) : (
+ t`Add a recipient before sending`
+ ),
+ content: (
+ <AiChatApprovalEmailReview
+ key={email.id}
+ draft={email.draft}
+ disabled={disabled || email.status !== 'pending'}
+ onDraftChange={(draft) => onDraftChange({ emailId: email.id, draft })}
+ />
+ ),
+ };
+ });
+
+ return (
+ <AiChatApprovalReviewDeck
+ cards={cards}
+ activeIndex={activeIndex}
+ onActiveIndexChange={onActiveIndexChange}
+ onRequestApproval={onRequestApproval}
+ onDeny={onSkip}
+ disabled={disabled}
+ approveAllLabel={t`Send all ${pendingEmailCount}`}
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatApprovalReviewDeck.tsx b/packages/twenty-front/src/modules/ai/components/AiChatApprovalReviewDeck.tsx
index 83520d1f78a..efc3efb00cd 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatApprovalReviewDeck.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatApprovalReviewDeck.tsx
@@ -101,6 +101,7 @@ type AiChatApprovalReviewDeckProps = {
onRequestApproval: (cardIds: string[]) => void;
onDeny: (cardId: string) => void;
disabled?: boolean;
+ approveAllLabel?: string;
};
export const AiChatApprovalReviewDeck = ({
@@ -110,6 +111,7 @@ export const AiChatApprovalReviewDeck = ({
onRequestApproval,
onDeny,
disabled = false,
+ approveAllLabel,
}: AiChatApprovalReviewDeckProps) => {
const { t } = useLingui();
const activeCard = cards[activeIndex];
@@ -123,7 +125,14 @@ export const AiChatApprovalReviewDeck = ({
const hasSelectedItems = pendingCards.some((card) => card.selectedCount > 0);
const isActiveCardPending = activeCard.status === 'pending';
const canApproveActiveCard =
- !disabled && isActiveCardPending && activeCard.selectedCount > 0;
+ !disabled &&
+ isActiveCardPending &&
+ !activeCard.isApprovalDisabled &&
+ activeCard.selectedCount > 0;
+ const canApproveAll =
+ !disabled &&
+ hasSelectedItems &&
+ pendingCards.every((card) => !card.isApprovalDisabled);
const pendingCardCount = pendingCards.length;
const nextTitles = cards
.filter((card, index) => index > activeIndex && card.status === 'pending')
@@ -196,16 +205,16 @@ export const AiChatApprovalReviewDeck = ({
disabled={disabled || !isActiveCardPending}
onClick={() => onDeny(activeCard.id)}
>
- {t`Deny`}
+ {activeCard.denyLabel ?? t`Deny`}
</Button>
{pendingCardCount > 1 && (
<Button
size="sm"
variant="outline"
- disabled={disabled || !hasSelectedItems}
+ disabled={!canApproveAll}
onClick={() => onRequestApproval(pendingCardIds)}
>
- {t`Approve all ${pendingCardCount}`}
+ {approveAllLabel ?? t`Approve all ${pendingCardCount}`}
</Button>
)}
<Button
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailControlledExample.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailControlledExample.tsx
new file mode 100644
index 00000000000..a5c8c6a420d
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailControlledExample.tsx
@@ -0,0 +1,72 @@
+import { styled } from '@linaria/react';
+import { useState } from 'react';
+import { Button } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { serializeJsonContentAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeJsonContentAsAdvancedTextEditorDocument';
+import { AiChatApprovalEmailReview } from '@/ai/components/AiChatApprovalEmailReview';
+import { AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES } from '@/ai/components/__stories__/aiChatApprovalEmailReviewFixtures';
+
+const REPLACEMENT_BODY = serializeJsonContentAsAdvancedTextEditorDocument({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'This replacement comes from the caller.' },
+ ],
+ },
+ ],
+});
+
+const StyledExample = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[3]};
+ min-width: 0;
+`;
+
+const StyledControls = styled.div`
+ display: flex;
+ flex-wrap: wrap;
+ gap: ${themeCssVariables.spacing[2]};
+`;
+
+export const AiChatApprovalEmailControlledExample = () => {
+ const [draft, setDraft] = useState(() =>
+ structuredClone(AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES[0].draft),
+ );
+ const [disabled, setDisabled] = useState(false);
+
+ return (
+ <StyledExample>
+ <AiChatApprovalEmailReview
+ draft={draft}
+ disabled={disabled}
+ onDraftChange={setDraft}
+ />
+ <StyledControls>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() =>
+ setDraft((currentDraft) => ({
+ ...currentDraft,
+ subject: 'Replacement from the caller',
+ body: REPLACEMENT_BODY,
+ }))
+ }
+ >
+ Replace draft
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => setDisabled((currentDisabled) => !currentDisabled)}
+ >
+ {disabled ? 'Unlock review' : 'Lock review'}
+ </Button>
+ </StyledControls>
+ </StyledExample>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailReviewDeck.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailReviewDeck.stories.tsx
new file mode 100644
index 00000000000..a785b390c0b
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailReviewDeck.stories.tsx
@@ -0,0 +1,406 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { AiChatApprovalEmailControlledExample } from '@/ai/components/__stories__/AiChatApprovalEmailControlledExample';
+import { AiChatApprovalEmailReviewExample } from '@/ai/components/__stories__/AiChatApprovalEmailReviewExample';
+import { AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES } from '@/ai/components/__stories__/aiChatApprovalEmailReviewFixtures';
+import { type AiChatApprovalReviewEmail } from '@/ai/types/AiChatApprovalReviewEmail';
+import { type AiChatApprovalReviewStatus } from '@/ai/types/AiChatApprovalReviewStatus';
+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';
+import { RootDecorator } from '~/testing/decorators/RootDecorator';
+
+const EMAIL_REVIEW_STATUSES: readonly AiChatApprovalReviewStatus[] = [
+ 'pending',
+ 'running',
+ 'success',
+ 'failed',
+ 'blocked',
+ 'uncertain',
+ 'skipped',
+];
+
+const EMAIL_REVIEW_STATUS_LABELS = {
+ pending: 'Pending',
+ running: 'Running',
+ success: 'Succeeded',
+ failed: 'Failed',
+ blocked: 'Blocked',
+ uncertain: 'Outcome unknown',
+ skipped: 'Skipped',
+};
+
+const getBodyEditor = (canvasElement: HTMLElement) =>
+ within(canvasElement).findByRole('textbox', { name: 'Body' });
+
+const meta = {
+ title: 'Modules/AI/AiChatApprovalEmailReviewDeck',
+ component: AiChatApprovalEmailReviewExample,
+ decorators: [ComponentDecorator, MemoryRouterDecorator, RootDecorator],
+ parameters: { container: { width: 688 }, argos: { fitToContent: false } },
+ args: { onApprove: fn(), onSkip: fn() },
+} satisfies Meta<typeof AiChatApprovalEmailReviewExample>;
+
+export default meta;
+
+type Story = StoryObj<typeof meta>;
+
+export const Default: Story = {};
+
+export const RetainedDraftEdits: Story = {
+ play: async ({ args, canvasElement }) => {
+ const canvas = within(canvasElement);
+ const screen = within(canvasElement.ownerDocument.body);
+ const subject = canvas.getByRole('textbox', { name: 'Subject' });
+
+ await userEvent.clear(subject);
+ await userEvent.type(subject, 'Revised demo follow-up');
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Remove [email protected]' }),
+ );
+ await userEvent.type(
+ canvas.getByRole('textbox', { name: 'Add a recipient to To' }),
+ '[email protected]{Enter}',
+ );
+ await userEvent.click(canvas.getByRole('button', { name: 'Cc/Bcc' }));
+ await userEvent.type(
+ canvas.getByRole('textbox', { name: 'Add a recipient to Cc' }),
+ '[email protected]{Enter}',
+ );
+
+ const bodyEditor = await getBodyEditor(canvasElement);
+
+ await userEvent.clear(bodyEditor);
+ await userEvent.type(bodyEditor, 'Updated walkthrough for Brian and Joe.');
+ await userEvent.type(
+ canvas.getByRole('textbox', { name: 'Add a recipient to Bcc' }),
+ );
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Next approval' }),
+ );
+
+ const secondSubject = canvas.getByRole('textbox', { name: 'Subject' });
+
+ await userEvent.clear(secondSubject);
+ await userEvent.type(secondSubject, 'Revised reporting walkthrough');
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Previous approval' }),
+ );
+
+ await expect(canvas.getByRole('textbox', { name: 'Subject' })).toHaveValue(
+ 'Revised demo follow-up',
+ );
+ await expect(canvas.getByText('[email protected]')).toBeVisible();
+ await expect(canvas.getByText('[email protected]')).toBeVisible();
+ await expect(canvas.getByText('[email protected]')).toBeVisible();
+ await expect(canvas.queryByText('Joe Gebbia')).not.toBeInTheDocument();
+ await expect(await getBodyEditor(canvasElement)).toHaveTextContent(
+ 'Updated walkthrough for Brian and Joe.',
+ );
+ await userEvent.click(canvas.getByRole('button', { name: 'Send all 3' }));
+
+ const confirmation = await screen.findByRole('alertdialog');
+
+ await expect(
+ within(confirmation).getByText('3 emails selected · 0 emails skipped'),
+ ).toBeVisible();
+ await expect(
+ within(confirmation).getByText('Checking in before the rollout'),
+ ).toBeVisible();
+ await expect(args.onApprove).not.toHaveBeenCalled();
+ await userEvent.click(
+ within(confirmation).getByRole('button', { name: 'Cancel' }),
+ );
+ await expect(canvas.getByRole('textbox', { name: 'Subject' })).toHaveValue(
+ 'Revised demo follow-up',
+ );
+ await userEvent.click(canvas.getByRole('button', { name: 'Send all 3' }));
+ await userEvent.click(
+ within(await screen.findByRole('alertdialog')).getByRole('button', {
+ name: 'Confirm approval',
+ }),
+ );
+
+ await expect(args.onApprove).toHaveBeenCalledTimes(1);
+ await expect(args.onApprove).toHaveBeenCalledWith({
+ emails: [
+ expect.objectContaining({
+ id: 'demo-follow-up',
+ draft: expect.objectContaining({
+ subject: 'Revised demo follow-up',
+ to: [
+ { address: '[email protected]', displayName: 'Brian Chesky' },
+ { address: '[email protected]' },
+ ],
+ cc: [{ address: '[email protected]' }],
+ bcc: [{ address: '[email protected]' }],
+ body: expect.stringContaining(
+ 'Updated walkthrough for Brian and Joe.',
+ ),
+ isCcBccExpanded: true,
+ }),
+ }),
+ expect.objectContaining({
+ id: 'reporting-walkthrough',
+ draft: expect.objectContaining({
+ subject: 'Revised reporting walkthrough',
+ }),
+ }),
+ expect.objectContaining({ id: 'rollout-check-in' }),
+ ],
+ });
+ },
+};
+
+export const IndividualApproval: Story = {
+ play: async ({ args, canvasElement }) => {
+ const canvas = within(canvasElement);
+ const screen = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Send' }));
+
+ const confirmation = await screen.findByRole('alertdialog');
+
+ await expect(
+ within(confirmation).getByText('1 email selected · 0 emails skipped'),
+ ).toBeVisible();
+ await expect(args.onApprove).not.toHaveBeenCalled();
+ await userEvent.click(
+ within(confirmation).getByRole('button', { name: 'Confirm approval' }),
+ );
+ await expect(args.onApprove).toHaveBeenCalledWith({
+ emails: [AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES[0]],
+ });
+ await expect(canvas.getByText('Succeeded')).toBeVisible();
+ await expect(canvas.getByRole('button', { name: 'Send' })).toBeDisabled();
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Next approval' }),
+ );
+ await expect(canvas.getByRole('textbox', { name: 'Subject' })).toHaveValue(
+ 'Pipeline reporting walkthrough',
+ );
+ await expect(canvas.getByRole('button', { name: 'Send' })).toBeEnabled();
+ await expect(canvas.getByRole('button', { name: 'Skip' })).toBeEnabled();
+ await expect(args.onSkip).not.toHaveBeenCalled();
+ await expect(
+ canvas.getByRole('button', { name: 'Send all 2' }),
+ ).toBeEnabled();
+ await userEvent.click(canvas.getByRole('button', { name: 'Send all 2' }));
+ await userEvent.click(
+ within(await screen.findByRole('alertdialog')).getByRole('button', {
+ name: 'Confirm approval',
+ }),
+ );
+ await expect(args.onApprove).toHaveBeenLastCalledWith({
+ emails: AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES.slice(1),
+ });
+ await expect(args.onApprove).toHaveBeenCalledTimes(2);
+ },
+};
+
+export const SkipIsolation: Story = {
+ play: async ({ args, canvasElement }) => {
+ const canvas = within(canvasElement);
+ const screen = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Skip' }));
+ await expect(args.onSkip).toHaveBeenCalledWith('demo-follow-up');
+ await expect(canvas.getByText('Skipped')).toBeVisible();
+ await expect(args.onApprove).not.toHaveBeenCalled();
+ await expect(canvas.getByRole('button', { name: 'Send' })).toBeDisabled();
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Next approval' }),
+ );
+ await expect(canvas.getByRole('button', { name: 'Send' })).toBeEnabled();
+ await userEvent.click(canvas.getByRole('button', { name: 'Send all 2' }));
+ await userEvent.click(
+ within(await screen.findByRole('alertdialog')).getByRole('button', {
+ name: 'Confirm approval',
+ }),
+ );
+ await expect(args.onApprove).toHaveBeenCalledWith({
+ emails: AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES.slice(1),
+ });
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Previous approval' }),
+ );
+ await expect(canvas.getByText('Skipped')).toBeVisible();
+ },
+};
+
+export const Outcomes: Story = {
+ args: {
+ initialEmails: EMAIL_REVIEW_STATUSES.map<AiChatApprovalReviewEmail>(
+ (status) => ({
+ ...AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES[0],
+ id: `email-${status}`,
+ status,
+ outcomeMessage: `Fixture outcome: ${status}.`,
+ progress: status === 'running' ? { completed: 0, total: 1 } : undefined,
+ }),
+ ),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ for (const status of EMAIL_REVIEW_STATUSES) {
+ const editor = await getBodyEditor(canvasElement);
+ const isPending = status === 'pending';
+
+ await waitFor(() =>
+ expect(editor).toHaveAttribute(
+ 'contenteditable',
+ isPending ? 'true' : 'false',
+ ),
+ );
+
+ if (isPending) {
+ await expect(
+ canvas.getByRole('button', { name: 'Send' }),
+ ).toBeEnabled();
+ }
+
+ if (!isPending) {
+ await expect(
+ canvas.getByText(EMAIL_REVIEW_STATUS_LABELS[status]),
+ ).toBeVisible();
+ await expect(
+ canvas.getByRole('textbox', { name: 'Subject' }),
+ ).toBeDisabled();
+ await expect(
+ canvas.getByRole('button', { name: 'Send' }),
+ ).toBeDisabled();
+ await expect(
+ canvas.getByRole('button', { name: 'Skip' }),
+ ).toBeDisabled();
+ await expect(
+ canvas.queryByRole('textbox', { name: 'Add a recipient to To' }),
+ ).not.toBeInTheDocument();
+ await expect(
+ canvas.queryByRole('button', { name: 'Remove [email protected]' }),
+ ).not.toBeInTheDocument();
+ }
+
+ if (status === 'running') {
+ await expect(
+ canvas.getByRole('progressbar', { name: 'Action progress' }),
+ ).toHaveAttribute('aria-valuenow', '0');
+ }
+
+ if (status !== 'skipped') {
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Next approval' }),
+ );
+ }
+ }
+ },
+};
+
+export const MissingRecipient: Story = {
+ args: {
+ initialEmails: AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES.map((email) =>
+ email.id === 'demo-follow-up'
+ ? { ...email, draft: { ...email.draft, to: [] } }
+ : email,
+ ),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(canvas.getByRole('button', { name: 'Send' })).toBeDisabled();
+ await expect(
+ canvas.getByRole('button', { name: 'Send all 3' }),
+ ).toBeDisabled();
+ await expect(canvas.getByRole('button', { name: 'Skip' })).toBeEnabled();
+ await userEvent.type(
+ canvas.getByRole('textbox', { name: 'Add a recipient to To' }),
+ '[email protected]{Enter}',
+ );
+ await expect(canvas.getByRole('button', { name: 'Send' })).toBeEnabled();
+ await expect(
+ canvas.getByRole('button', { name: 'Send all 3' }),
+ ).toBeEnabled();
+ },
+};
+
+export const Empty: Story = {
+ args: { initialEmails: [] },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(canvas.getByText('No actions to review')).toBeVisible();
+ await expect(canvas.queryByRole('button')).not.toBeInTheDocument();
+ },
+};
+
+export const Single: Story = {
+ args: { initialEmails: AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES.slice(0, 1) },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(
+ canvas.queryByRole('button', { name: 'Next approval' }),
+ ).not.toBeInTheDocument();
+ await expect(
+ canvas.queryByRole('button', { name: 'Previous approval' }),
+ ).not.toBeInTheDocument();
+ await expect(canvas.queryByText(/Send all/)).not.toBeInTheDocument();
+ await expect(
+ canvas.getByText('No more drafts after this one'),
+ ).toBeVisible();
+ await expect(canvas.getByRole('button', { name: 'Send' })).toBeEnabled();
+ },
+};
+
+export const Narrow: Story = {
+ parameters: { container: { width: 320 } },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const review = canvas.getByRole('region', { name: 'Approval review' });
+
+ await expect(await getBodyEditor(canvasElement)).toBeVisible();
+ await expect(review.scrollWidth).toBeLessThanOrEqual(review.clientWidth);
+ await userEvent.click(canvas.getByRole('button', { name: 'Cc/Bcc' }));
+ await expect(
+ canvas.getByRole('textbox', { name: 'Add a recipient to Bcc' }),
+ ).toBeVisible();
+ await expect(review.scrollWidth).toBeLessThanOrEqual(review.clientWidth);
+ },
+};
+
+export const ControlledBodyAndReadOnly: Story = {
+ render: () => <AiChatApprovalEmailControlledExample />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const editor = await getBodyEditor(canvasElement);
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Replace draft' }),
+ );
+ await waitFor(() =>
+ expect(editor).toHaveTextContent(
+ 'This replacement comes from the caller.',
+ ),
+ );
+ await expect(canvas.getByRole('textbox', { name: 'Subject' })).toHaveValue(
+ 'Replacement from the caller',
+ );
+ await userEvent.click(canvas.getByRole('button', { name: 'Lock review' }));
+ await waitFor(() =>
+ expect(editor).toHaveAttribute('contenteditable', 'false'),
+ );
+ await expect(
+ canvas.getByRole('textbox', { name: 'Subject' }),
+ ).toBeDisabled();
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Unlock review' }),
+ );
+ await waitFor(() =>
+ expect(editor).toHaveAttribute('contenteditable', 'true'),
+ );
+ await userEvent.type(editor, ' Editable again.');
+ await userEvent.keyboard('{ArrowLeft}XY');
+ await expect(editor).toHaveTextContent('Editable againXY.');
+ },
+};
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailReviewExample.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailReviewExample.tsx
new file mode 100644
index 00000000000..52f135b1f69
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailReviewExample.tsx
@@ -0,0 +1,123 @@
+import { styled } from '@linaria/react';
+import { useState } from 'react';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { AiChatApprovalEmailConfirmation } from '@/ai/components/AiChatApprovalEmailConfirmation';
+import { AiChatApprovalEmailReviewDeck } from '@/ai/components/AiChatApprovalEmailReviewDeck';
+import { AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES } from '@/ai/components/__stories__/aiChatApprovalEmailReviewFixtures';
+import { type AiChatApprovalEmailReviewSnapshot } from '@/ai/components/__stories__/AiChatApprovalEmailReviewSnapshot';
+import { type AiChatApprovalReviewEmail } from '@/ai/types/AiChatApprovalReviewEmail';
+import { type AiChatApprovalReviewEmailDraft } from '@/ai/types/AiChatApprovalReviewEmailDraft';
+
+const StyledExample = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[3]};
+ min-width: 0;
+`;
+
+type AiChatApprovalEmailReviewExampleProps = {
+ initialEmails?: readonly AiChatApprovalReviewEmail[];
+ initialActiveIndex?: number;
+ disabled?: boolean;
+ onApprove: (snapshot: AiChatApprovalEmailReviewSnapshot) => void;
+ onSkip: (emailId: string) => void;
+};
+
+export const AiChatApprovalEmailReviewExample = ({
+ initialEmails = AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES,
+ initialActiveIndex = 0,
+ disabled = false,
+ onApprove,
+ onSkip,
+}: AiChatApprovalEmailReviewExampleProps) => {
+ const [emails, setEmails] = useState(() => structuredClone(initialEmails));
+ const [activeIndex, setActiveIndex] = useState(initialActiveIndex);
+ const [confirmation, setConfirmation] =
+ useState<AiChatApprovalEmailReviewSnapshot | null>(null);
+
+ const handleDraftChange = ({
+ emailId,
+ draft,
+ }: {
+ emailId: string;
+ draft: AiChatApprovalReviewEmailDraft;
+ }) => {
+ setEmails((currentEmails) =>
+ currentEmails.map((email) =>
+ email.id === emailId ? { ...email, draft } : email,
+ ),
+ );
+ };
+
+ const handleRequestApproval = (emailIds: string[]) => {
+ const selectedEmails = emails.filter(
+ (email) => email.status === 'pending' && emailIds.includes(email.id),
+ );
+
+ if (!isNonEmptyArray(selectedEmails)) {
+ return;
+ }
+
+ setConfirmation({ emails: structuredClone(selectedEmails) });
+ };
+
+ const handleConfirm = () => {
+ if (!isDefined(confirmation)) {
+ return;
+ }
+
+ onApprove(confirmation);
+ setEmails((currentEmails) =>
+ currentEmails.map<AiChatApprovalReviewEmail>((email) =>
+ confirmation.emails.some(
+ (selectedEmail) => selectedEmail.id === email.id,
+ )
+ ? {
+ ...email,
+ status: 'success',
+ outcomeMessage: 'Fixture approval completed.',
+ }
+ : email,
+ ),
+ );
+ setConfirmation(null);
+ };
+
+ const handleSkip = (emailId: string) => {
+ setEmails((currentEmails) =>
+ currentEmails.map<AiChatApprovalReviewEmail>((email) =>
+ email.id === emailId
+ ? {
+ ...email,
+ status: 'skipped',
+ outcomeMessage: 'Fixture email was skipped.',
+ }
+ : email,
+ ),
+ );
+ onSkip(emailId);
+ };
+
+ return (
+ <StyledExample>
+ <AiChatApprovalEmailReviewDeck
+ emails={emails}
+ activeIndex={activeIndex}
+ onActiveIndexChange={setActiveIndex}
+ onDraftChange={handleDraftChange}
+ onRequestApproval={handleRequestApproval}
+ onSkip={handleSkip}
+ disabled={disabled || isDefined(confirmation)}
+ />
+ {isDefined(confirmation) && (
+ <AiChatApprovalEmailConfirmation
+ emails={confirmation.emails}
+ onConfirm={handleConfirm}
+ onCancel={() => setConfirmation(null)}
+ />
+ )}
+ </StyledExample>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailReviewSnapshot.ts b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailReviewSnapshot.ts
new file mode 100644
index 00000000000..f4d881612c0
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalEmailReviewSnapshot.ts
@@ -0,0 +1,5 @@
+import { type AiChatApprovalReviewEmail } from '@/ai/types/AiChatApprovalReviewEmail';
+
+export type AiChatApprovalEmailReviewSnapshot = {
+ emails: AiChatApprovalReviewEmail[];
+};
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/aiChatApprovalEmailReviewFixtures.ts b/packages/twenty-front/src/modules/ai/components/__stories__/aiChatApprovalEmailReviewFixtures.ts
new file mode 100644
index 00000000000..c2180e1eeb7
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/aiChatApprovalEmailReviewFixtures.ts
@@ -0,0 +1,72 @@
+import { serializeJsonContentAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeJsonContentAsAdvancedTextEditorDocument';
+import { type AiChatApprovalReviewEmail } from '@/ai/types/AiChatApprovalReviewEmail';
+
+const serializeParagraphs = (paragraphs: string[]) =>
+ serializeJsonContentAsAdvancedTextEditorDocument({
+ type: 'doc',
+ content: paragraphs.map((text) => ({
+ type: 'paragraph',
+ content: [{ type: 'text', text }],
+ })),
+ });
+
+export const AI_CHAT_APPROVAL_EMAIL_REVIEW_FIXTURES: readonly AiChatApprovalReviewEmail[] =
+ [
+ {
+ id: 'demo-follow-up',
+ status: 'pending',
+ draft: {
+ to: [
+ { address: '[email protected]', displayName: 'Brian Chesky' },
+ { address: '[email protected]', displayName: 'Joe Gebbia' },
+ ],
+ cc: [],
+ bcc: [],
+ isCcBccExpanded: false,
+ subject: 'Following up on Tuesday’s demo',
+ body: serializeParagraphs([
+ 'Hi Brian and Joe,',
+ 'Thanks again for the demo on Tuesday. You mentioned the ops team wanted to see how pipeline reporting works before the rollout, so I put together a short walkthrough.',
+ 'Would Thursday at 2pm work for a 20 minute call?',
+ 'Sarah',
+ ]),
+ },
+ },
+ {
+ id: 'reporting-walkthrough',
+ status: 'pending',
+ draft: {
+ to: [{ address: '[email protected]', displayName: 'Grace Hopper' }],
+ cc: [{ address: '[email protected]', displayName: 'Ada Lovelace' }],
+ bcc: [],
+ isCcBccExpanded: true,
+ subject: 'Pipeline reporting walkthrough',
+ body: serializeParagraphs([
+ 'Hi Grace,',
+ 'Here is the reporting walkthrough we discussed. Please let me know which views would help your team.',
+ 'Sarah',
+ ]),
+ },
+ },
+ {
+ id: 'rollout-check-in',
+ status: 'pending',
+ draft: {
+ to: [
+ {
+ address: '[email protected]',
+ displayName: 'Katherine Johnson',
+ },
+ ],
+ cc: [],
+ bcc: [],
+ isCcBccExpanded: false,
+ subject: 'Checking in before the rollout',
+ body: serializeParagraphs([
+ 'Hi Katherine,',
+ 'Do you have everything you need for the rollout? I can share a short setup guide before our next call.',
+ 'Sarah',
+ ]),
+ },
+ },
+ ];
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatToolCallApprovalEmailCard.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatToolCallApprovalEmailCard.test.tsx
index 7bf9bdcae2d..119d89298e9 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatToolCallApprovalEmailCard.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatToolCallApprovalEmailCard.test.tsx
@@ -27,14 +27,18 @@ jest.mock(
() => ({
FormAdvancedTextFieldInput: ({
defaultValue,
+ value,
onChange,
}: {
- defaultValue: string;
+ defaultValue?: string;
+ value?: string;
onChange: (value: string) => void;
}) => (
<textarea
aria-label="Email body"
- defaultValue={JSON.parse(defaultValue).content[0].content[0].text}
+ defaultValue={
+ JSON.parse(value ?? defaultValue ?? '').content[0].content[0].text
+ }
onChange={(event) =>
onChange(
JSON.stringify({
diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatEmailRecipientsRow.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatEmailRecipientsRow.tsx
index 838ff341494..cdecbf64e0b 100644
--- a/packages/twenty-front/src/modules/ai/components/internal/AiChatEmailRecipientsRow.tsx
+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatEmailRecipientsRow.tsx
@@ -1,33 +1,34 @@
-import { css } from '@linaria/core';
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
-import { type KeyboardEvent, useState } from 'react';
+import { isNonEmptyString } from '@sniptt/guards';
+import { type KeyboardEvent, type ReactNode, useState } from 'react';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
import { LightIconButton } from 'twenty-ui/components/input';
import { IconX } from 'twenty-ui/icon';
import { Chip } from 'twenty-ui/primitives/data-display';
import { Input } from 'twenty-ui/primitives/input';
import { themeCssVariables } from 'twenty-ui/theme';
+import { ComposerFieldRow } from '@/activities/components/ComposerFieldRow';
import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRecipient';
import { parseEmailRecipients } from '@/activities/emails/recipients/utils/parseEmailRecipients';
+const RECIPIENT_INPUT_MIN_WIDTH_PX = 80;
+
const StyledRow = styled.div`
align-items: center;
display: flex;
+ flex: 1;
flex-wrap: wrap;
gap: ${themeCssVariables.spacing[1]};
min-height: 28px;
+ min-width: 0;
`;
-const StyledRowLabel = styled.span`
- color: ${themeCssVariables.font.color.tertiary};
- font-size: ${themeCssVariables.font.size.sm};
- width: 32px;
-`;
-
-const RECIPIENT_INPUT_CLASS_NAME = css`
- flex: 1 0 80px;
- min-width: 80px;
+const StyledInputContainer = styled.div`
+ flex: 1 0 ${RECIPIENT_INPUT_MIN_WIDTH_PX}px;
+ min-width: 0;
`;
type AiChatEmailRecipientsRowProps = {
@@ -35,6 +36,8 @@ type AiChatEmailRecipientsRowProps = {
recipients: EmailRecipient[];
disabled: boolean;
onChange: (recipients: EmailRecipient[]) => void;
+ trailing?: ReactNode;
+ isLabelVisible?: boolean;
};
export const AiChatEmailRecipientsRow = ({
@@ -42,11 +45,17 @@ export const AiChatEmailRecipientsRow = ({
recipients,
disabled,
onChange,
+ trailing,
+ isLabelVisible = true,
}: AiChatEmailRecipientsRowProps) => {
const { t } = useLingui();
const [draftRecipient, setDraftRecipient] = useState('');
const addDraftRecipients = () => {
+ if (disabled) {
+ return;
+ }
+
const addedRecipients = parseEmailRecipients(draftRecipient).filter(
({ address }) =>
!recipients.some((recipient) => recipient.address === address),
@@ -54,7 +63,7 @@ export const AiChatEmailRecipientsRow = ({
setDraftRecipient('');
- if (addedRecipients.length > 0) {
+ if (isNonEmptyArray(addedRecipients)) {
onChange([...recipients, ...addedRecipients]);
}
};
@@ -69,53 +78,62 @@ export const AiChatEmailRecipientsRow = ({
if (
event.key === 'Backspace' &&
- draftRecipient.length === 0 &&
- recipients.length > 0
+ !isNonEmptyString(draftRecipient) &&
+ isNonEmptyArray(recipients)
) {
onChange(recipients.slice(0, -1));
}
};
return (
- <StyledRow>
- <StyledRowLabel>{label}</StyledRowLabel>
- {recipients.map(({ address }) => (
- <Chip
- key={address}
- variant="soft"
- endElement={
- disabled ? undefined : (
- <LightIconButton
- size="xs"
- aria-label={t`Remove ${address}`}
- onClick={() =>
- onChange(
- recipients.filter(
- (recipient) => recipient.address !== address,
- ),
- )
- }
- >
- <IconX />
- </LightIconButton>
- )
- }
- >
- {address}
- </Chip>
- ))}
- {!disabled && (
- <Input
- variant="plain"
- className={RECIPIENT_INPUT_CLASS_NAME}
- aria-label={t`Add a recipient to ${label}`}
- placeholder={recipients.length === 0 ? t`Add recipient` : undefined}
- value={draftRecipient}
- onChange={(event) => setDraftRecipient(event.target.value)}
- onKeyDown={handleKeyDown}
- onBlur={addDraftRecipients}
- />
- )}
- </StyledRow>
+ <ComposerFieldRow
+ label={label}
+ isLabelVisible={isLabelVisible}
+ trailing={trailing}
+ >
+ <StyledRow>
+ {recipients.map(({ address, displayName }) => (
+ <Chip
+ key={address}
+ variant="soft"
+ endElement={
+ disabled ? undefined : (
+ <LightIconButton
+ size="xs"
+ aria-label={t`Remove ${address}`}
+ onClick={() =>
+ onChange(
+ recipients.filter(
+ (recipient) => recipient.address !== address,
+ ),
+ )
+ }
+ >
+ <IconX />
+ </LightIconButton>
+ )
+ }
+ title={address}
+ >
+ {isNonEmptyString(displayName) ? displayName : address}
+ </Chip>
+ ))}
+ {!disabled && (
+ <StyledInputContainer>
+ <Input
+ variant="plain"
+ aria-label={t`Add a recipient to ${label}`}
+ placeholder={
+ !isNonEmptyArray(recipients) ? t`Add recipient` : undefined
+ }
+ value={draftRecipient}
+ onChange={(event) => setDraftRecipient(event.target.value)}
+ onKeyDown={handleKeyDown}
+ onBlur={addDraftRecipients}
+ />
+ </StyledInputContainer>
+ )}
+ </StyledRow>
+ </ComposerFieldRow>
);
};
diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatToolCallApprovalEmailCard.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatToolCallApprovalEmailCard.tsx
index d44e475d03d..594fbd4e308 100644
--- a/packages/twenty-front/src/modules/ai/components/internal/AiChatToolCallApprovalEmailCard.tsx
+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatToolCallApprovalEmailCard.tsx
@@ -1,42 +1,29 @@
-import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
import { isString } from '@sniptt/guards';
import { type JSONContent } from '@tiptap/core';
import { useState } from 'react';
import { type ProposedToolCall } from 'twenty-shared/ai';
import {
+ isNonEmptyArray,
isPlainObject,
parseCanonicalTipTapJsonDocument,
} from 'twenty-shared/utils';
-import { LightButton } from 'twenty-ui/components/input';
import { IconDeviceFloppy, IconSend, IconTrash } from 'twenty-ui/icon';
-import { Button, Input } from 'twenty-ui/primitives/input';
-import { themeCssVariables } from 'twenty-ui/theme';
+import { Button } from 'twenty-ui/primitives/input';
import { parseEmailRecipients } from '@/activities/emails/recipients/utils/parseEmailRecipients';
import { serializeEmailRecipients } from '@/activities/emails/recipients/utils/serializeEmailRecipients';
-import { INLINE_EMAIL_BODY_EDITOR_PROFILE } from '@/activities/emails/editor/constants/InlineEmailBodyEditorProfile';
-import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';
import { serializeJsonContentAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeJsonContentAsAdvancedTextEditorDocument';
-import { AiChatEmailRecipientsRow } from '@/ai/components/internal/AiChatEmailRecipientsRow';
+import { AiChatApprovalEmailReview } from '@/ai/components/AiChatApprovalEmailReview';
import { AiChatToolCallApprovalCardLayout } from '@/ai/components/internal/AiChatToolCallApprovalCardLayout';
import { useAnswerToolCallApproval } from '@/ai/hooks/useAnswerToolCallApproval';
+import { type AiChatApprovalReviewEmailDraft } from '@/ai/types/AiChatApprovalReviewEmailDraft';
const EMAIL_TOOL_NAMES = {
send: 'send_email',
draft: 'draft_email',
} as const;
-const StyledSubjectContainer = styled.div`
- border-bottom: 1px solid ${themeCssVariables.border.color.light};
- padding: ${themeCssVariables.spacing[1]} 0;
-`;
-
-const StyledRecipientToggles = styled.div`
- display: flex;
- gap: ${themeCssVariables.spacing[1]};
-`;
-
const readRecipients = (toolArguments: Record<string, unknown>) => {
const recipients = isPlainObject(toolArguments.recipients)
? toolArguments.recipients
@@ -70,17 +57,21 @@ export const AiChatToolCallApprovalEmailCard = ({
const approval = useAnswerToolCallApproval({ toolCallId, proposal });
const { pendingResponse, isAnswering, approve, reject } = approval;
- const initialRecipients = readRecipients(proposal.arguments);
- const [to, setTo] = useState(initialRecipients.to);
- const [cc, setCc] = useState(initialRecipients.cc);
- const [bcc, setBcc] = useState(initialRecipients.bcc);
- // Kept once shown, so removing the last recipient doesn't hide the field.
- const [isCcShown, setIsCcShown] = useState(cc.length > 0);
- const [isBccShown, setIsBccShown] = useState(bcc.length > 0);
- const [subject, setSubject] = useState(
- isString(proposal.arguments.subject) ? proposal.arguments.subject : '',
- );
- const [body, setBody] = useState<unknown>(proposal.arguments.body);
+ const [originalBody] = useState<unknown>(() => proposal.arguments.body);
+ const serializedOriginalBody = serializeEmailBody(originalBody);
+ const [draft, setDraft] = useState<AiChatApprovalReviewEmailDraft>(() => {
+ const recipients = readRecipients(proposal.arguments);
+
+ return {
+ ...recipients,
+ subject: isString(proposal.arguments.subject)
+ ? proposal.arguments.subject
+ : '',
+ body: serializedOriginalBody,
+ isCcBccExpanded:
+ isNonEmptyArray(recipients.cc) || isNonEmptyArray(recipients.bcc),
+ };
+ });
const runnableToolNames = [
proposal.toolName,
@@ -89,22 +80,21 @@ export const AiChatToolCallApprovalEmailCard = ({
const canSend = runnableToolNames.includes(EMAIL_TOOL_NAMES.send);
const canSaveDraft = runnableToolNames.includes(EMAIL_TOOL_NAMES.draft);
- const handleBodyChange = (serializedBody: string) => {
- setBody(parseCanonicalTipTapJsonDocument(serializedBody) ?? serializedBody);
- };
-
const approveWith = (toolName: string) => {
approve({
toolName,
arguments: {
...proposal.arguments,
recipients: {
- to: serializeEmailRecipients(to),
- cc: serializeEmailRecipients(cc),
- bcc: serializeEmailRecipients(bcc),
+ to: serializeEmailRecipients(draft.to),
+ cc: serializeEmailRecipients(draft.cc),
+ bcc: serializeEmailRecipients(draft.bcc),
},
- subject,
- body,
+ subject: draft.subject,
+ body:
+ draft.body === serializedOriginalBody
+ ? originalBody
+ : (parseCanonicalTipTapJsonDocument(draft.body) ?? draft.body),
},
});
};
@@ -149,7 +139,7 @@ export const AiChatToolCallApprovalEmailCard = ({
variant="solid"
color="accent"
startIcon={<IconSend />}
- disabled={isAnswering || to.length === 0}
+ disabled={isAnswering || !isNonEmptyArray(draft.to)}
loading={pendingToolName === EMAIL_TOOL_NAMES.send}
onClick={() => approveWith(EMAIL_TOOL_NAMES.send)}
>
@@ -159,64 +149,10 @@ export const AiChatToolCallApprovalEmailCard = ({
</>
}
>
- <AiChatEmailRecipientsRow
- label={t`To`}
- recipients={to}
+ <AiChatApprovalEmailReview
+ draft={draft}
+ onDraftChange={setDraft}
disabled={isAnswering}
- onChange={setTo}
- />
- {(!isCcShown || !isBccShown) && (
- <StyledRecipientToggles>
- {!isCcShown && (
- <LightButton
- disabled={isAnswering}
- onClick={() => setIsCcShown(true)}
- >
- {t`Cc`}
- </LightButton>
- )}
- {!isBccShown && (
- <LightButton
- disabled={isAnswering}
- onClick={() => setIsBccShown(true)}
- >
- {t`Bcc`}
- </LightButton>
- )}
- </StyledRecipientToggles>
- )}
- {isCcShown && (
- <AiChatEmailRecipientsRow
- label={t`Cc`}
- recipients={cc}
- disabled={isAnswering}
- onChange={setCc}
- />
- )}
- {isBccShown && (
- <AiChatEmailRecipientsRow
- label={t`Bcc`}
- recipients={bcc}
- disabled={isAnswering}
- onChange={setBcc}
- />
- )}
- <StyledSubjectContainer>
- <Input
- variant="plain"
- aria-label={t`Subject`}
- placeholder={t`Subject`}
- value={subject}
- disabled={isAnswering}
- onChange={(event) => setSubject(event.target.value)}
- />
- </StyledSubjectContainer>
- <FormAdvancedTextFieldInput
- defaultValue={serializeEmailBody(proposal.arguments.body)}
- onChange={handleBodyChange}
- readonly={isAnswering}
- placeholder={t`Write the email`}
- profile={INLINE_EMAIL_BODY_EDITOR_PROFILE}
/>
</AiChatToolCallApprovalCardLayout>
);
diff --git a/packages/twenty-front/src/modules/ai/types/AiChatApprovalReviewCard.ts b/packages/twenty-front/src/modules/ai/types/AiChatApprovalReviewCard.ts
index 99b1cb0c772..451bcf43eeb 100644
--- a/packages/twenty-front/src/modules/ai/types/AiChatApprovalReviewCard.ts
+++ b/packages/twenty-front/src/modules/ai/types/AiChatApprovalReviewCard.ts
@@ -7,9 +7,11 @@ export type AiChatApprovalReviewCard = AiChatApprovalReviewSummary & {
icon: ReactNode;
content: ReactNode;
approveLabel: string;
+ denyLabel?: string;
status: AiChatApprovalReviewStatus;
isDestructive?: boolean;
- hint?: string;
+ isApprovalDisabled?: boolean;
+ hint?: ReactNode;
outcomeMessage?: string;
progress?: { completed: number; total: number };
};
diff --git a/packages/twenty-front/src/modules/ai/types/AiChatApprovalReviewEmail.ts b/packages/twenty-front/src/modules/ai/types/AiChatApprovalReviewEmail.ts
new file mode 100644
index 00000000000..138b3cff9fb
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/types/AiChatApprovalReviewEmail.ts
@@ -0,0 +1,10 @@
+import { type AiChatApprovalReviewEmailDraft } from '@/ai/types/AiChatApprovalReviewEmailDraft';
+import { type AiChatApprovalReviewStatus } from '@/ai/types/AiChatApprovalReviewStatus';
+
+export type AiChatApprovalReviewEmail = {
+ id: string;
+ draft: AiChatApprovalReviewEmailDraft;
+ status: AiChatApprovalReviewStatus;
+ outcomeMessage?: string;
+ progress?: { completed: number; total: number };
+};
diff --git a/packages/twenty-front/src/modules/ai/types/AiChatApprovalReviewEmailDraft.ts b/packages/twenty-front/src/modules/ai/types/AiChatApprovalReviewEmailDraft.ts
new file mode 100644
index 00000000000..f8afb0a5102
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/types/AiChatApprovalReviewEmailDraft.ts
@@ -0,0 +1,10 @@
+import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRecipient';
+
+export type AiChatApprovalReviewEmailDraft = {
+ to: EmailRecipient[];
+ cc: EmailRecipient[];
+ bcc: EmailRecipient[];
+ subject: string;
+ body: string;
+ isCcBccExpanded: boolean;
+};