The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add merge proposal review (#28863)
Raphaël Bosif834323caec7
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailReviewDeck.tsx b/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailReviewDeck.tsxindex 65a102518ee..6d38b593c13 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailReviewDeck.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatApprovalEmailReviewDeck.tsx@@ -33,9 +33,6 @@ export const AiChatApprovalEmailReviewDeck = ({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)@@ -82,7 +79,9 @@ export const AiChatApprovalEmailReviewDeck = ({onRequestApproval={onRequestApproval}onDeny={onSkip}disabled={disabled}- approveAllLabel={t`Send all ${pendingEmailCount}`}+ getApproveAllLabel={(pendingEmailCount) =>+ t`Send all ${pendingEmailCount}`+ }/>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatApprovalMergeReview.tsx b/packages/twenty-front/src/modules/ai/components/AiChatApprovalMergeReview.tsxnew file mode 100644index 00000000000..25ddd8f85fc--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatApprovalMergeReview.tsx@@ -0,0 +1,89 @@+import { useLingui } from '@lingui/react/macro';+import { IconArrowMerge } from 'twenty-ui/icon';++import { AiChatApprovalMergeReviewContent } from '@/ai/components/AiChatApprovalMergeReviewContent';+import { AiChatApprovalReviewDeck } from '@/ai/components/AiChatApprovalReviewDeck';+import { type AiChatApprovalMergePair } from '@/ai/types/AiChatApprovalMergePair';+import { type AiChatApprovalReviewCard } from '@/ai/types/AiChatApprovalReviewCard';++const MERGE_REVIEW_ICON_SIZE = 16;++type AiChatApprovalMergeReviewProps = {+ pairs: readonly AiChatApprovalMergePair[];+ activeIndex: number;+ onActiveIndexChange: (index: number) => void;+ onTabChange: (selection: {+ pairId: string;+ tab: AiChatApprovalMergePair['activeTab'];+ }) => void;+ onPriorityRecordChange: (selection: {+ pairId: string;+ priorityRecordId: string;+ }) => void;+ onRequestMerge: (pairIds: string[]) => void;+ onSkip: (pairId: string) => void;+ disabled?: boolean;+};++export const AiChatApprovalMergeReview = ({+ pairs,+ activeIndex,+ onActiveIndexChange,+ onTabChange,+ onPriorityRecordChange,+ onRequestMerge,+ onSkip,+ disabled = false,+}: AiChatApprovalMergeReviewProps) => {+ const { t } = useLingui();+ const cards: AiChatApprovalReviewCard[] = pairs.map((pair) => {+ const hasValidPriorityRecord = pair.sources.some(+ (source) => source.id === pair.priorityRecordId,+ );+ const isWaitingForPriorityRecord =+ pair.status === 'pending' && !hasValidPriorityRecord;++ return {+ id: pair.id,+ title: pair.title,+ icon: <IconArrowMerge size={MERGE_REVIEW_ICON_SIZE} />,+ approveLabel: t`Merge`,+ denyLabel: t`Skip`,+ hint: isWaitingForPriorityRecord+ ? t`Choose a source record to keep`+ : t`The priority record keeps its identity`,+ selectedCount: pair.sources.length,+ isApprovalDisabled: !hasValidPriorityRecord,+ skippedCount: 0,+ status: pair.status,+ outcomeMessage: pair.outcomeMessage,+ progress: pair.progress,+ content: (+ <AiChatApprovalMergeReviewContent+ pair={pair}+ onTabChange={(tab) => onTabChange({ pairId: pair.id, tab })}+ onPriorityRecordChange={(priorityRecordId) =>+ onPriorityRecordChange({ pairId: pair.id, priorityRecordId })+ }+ disabled={disabled || pair.status !== 'pending'}+ />+ ),+ };+ });++ return (+ <AiChatApprovalReviewDeck+ cards={cards}+ activeIndex={activeIndex}+ onActiveIndexChange={onActiveIndexChange}+ onRequestApproval={onRequestMerge}+ onDeny={onSkip}+ getApproveAllLabel={(pendingPairCount) =>+ t`Merge all ${pendingPairCount}`+ }+ previousLabel={t`Previous pair`}+ nextLabel={t`Next pair`}+ disabled={disabled}+ />+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatApprovalMergeReviewContent.tsx b/packages/twenty-front/src/modules/ai/components/AiChatApprovalMergeReviewContent.tsxnew file mode 100644index 00000000000..ef01fcc5fcb--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatApprovalMergeReviewContent.tsx@@ -0,0 +1,213 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import { isDefined } from 'twenty-shared/utils';+import { IconArrowMerge, IconSettings } from 'twenty-ui/icon';+import { Avatar, Chip } from 'twenty-ui/primitives/data-display';+import { Tabs } from 'twenty-ui/primitives/navigation';+import { themeCssVariables } from 'twenty-ui/theme';++import { type AiChatApprovalMergePair } from '@/ai/types/AiChatApprovalMergePair';+import { MergePrioritySettings } from '@/object-record/record-merge/components/MergePrioritySettings';+import { getPositionNumberIcon } from '@/object-record/record-merge/utils/getPositionNumberIcon';+import { getPositionWordLabel } from '@/object-record/record-merge/utils/getPositionWordLabel';++const MERGE_REVIEW_ICON_SIZE = 16;+const MERGE_REVIEW_HEADER_HEIGHT = 40;+const TAB_FOCUS_RING_OUTSET = 3;+const SOURCE_TAB_VALUES = ['first', 'second'] as const;++const StyledReview = styled.div`+ background: ${themeCssVariables.background.primary};+ border: 1px solid ${themeCssVariables.border.color.light};+ border-radius: ${themeCssVariables.border.radius.sm};+ min-width: 0;+`;++const StyledHeader = styled.div`+ align-items: center;+ background: ${themeCssVariables.background.secondary};+ border-bottom: 1px solid ${themeCssVariables.border.color.light};+ display: flex;+ flex-wrap: wrap;+ gap: ${themeCssVariables.spacing[2]};+ min-height: ${MERGE_REVIEW_HEADER_HEIGHT}px;+ padding: 0 ${themeCssVariables.spacing[3]};+`;++const StyledName = styled.div`+ color: ${themeCssVariables.font.color.primary};+ flex: 1;+ font-size: ${themeCssVariables.font.size.lg};+ font-weight: ${themeCssVariables.font.weight.semiBold};+ min-width: 0;+ overflow-wrap: anywhere;+`;++const StyledSubtitle = styled.span`+ color: ${themeCssVariables.font.color.tertiary};+ font-size: ${themeCssVariables.font.size.md};+ overflow-wrap: anywhere;+`;++const StyledSources = styled.div`+ align-items: center;+ display: flex;+ flex-wrap: wrap;+ gap: ${themeCssVariables.spacing[2]};+ padding: ${themeCssVariables.spacing[2]} ${themeCssVariables.spacing[3]};+`;++const StyledTabsScrollContainer = styled.div`+ margin: -${TAB_FOCUS_RING_OUTSET}px 0;+ overflow-x: auto;+ padding: ${TAB_FOCUS_RING_OUTSET}px 0;+`;++const StyledTabsList = styled.div`+ min-width: max-content;+ padding: 0 ${themeCssVariables.spacing[2]};+`;++const StyledContent = styled.div`+ padding: ${themeCssVariables.spacing[4]};+`;++const StyledFields = styled.div`+ background: ${themeCssVariables.background.secondary};+ border: 1px solid ${themeCssVariables.border.color.medium};+ border-radius: ${themeCssVariables.border.radius.sm};+ min-width: 0;+ padding: ${themeCssVariables.spacing[1]};+`;++type AiChatApprovalMergeReviewContentProps = {+ pair: Pick<+ AiChatApprovalMergePair,+ 'id' | 'sources' | 'priorityRecordId' | 'activeTab' | 'preview'+ >;+ onTabChange: (tab: AiChatApprovalMergePair['activeTab']) => void;+ onPriorityRecordChange: (recordId: string) => void;+ disabled?: boolean;+};++export const AiChatApprovalMergeReviewContent = ({+ pair,+ onTabChange,+ onPriorityRecordChange,+ disabled = false,+}: AiChatApprovalMergeReviewContentProps) => {+ const { t } = useLingui();+ const priorityRecordIndex = pair.sources.findIndex(+ ({ id }) => id === pair.priorityRecordId,+ );+ const priorityRecord = pair.sources[priorityRecordIndex];+ const displayedRecord = {+ preview: priorityRecord,+ first: pair.sources[0],+ second: pair.sources[1],+ settings: priorityRecord,+ }[pair.activeTab];++ return (+ <StyledReview>+ <StyledHeader>+ {isDefined(displayedRecord) && (+ <>+ <Avatar+ name={displayedRecord.name}+ src={displayedRecord.avatarUrl}+ icon={displayedRecord.avatarIcon}+ shape="square"+ size="lg"+ />+ <StyledName>{displayedRecord.name}</StyledName>+ <StyledSubtitle>{displayedRecord.subtitle}</StyledSubtitle>+ </>+ )}+ </StyledHeader>+ <StyledSources role="group" aria-label={t`Source records`}>+ {pair.sources.map(({ id, name }, index) => {+ const positionLabel = getPositionWordLabel(index);++ return (+ <Chip+ key={id}+ variant="soft"+ endElement={+ id === pair.priorityRecordId ? t`Survives` : undefined+ }+ endElementDivider+ >+ {t`${positionLabel}: ${name}`}+ </Chip>+ );+ })}+ </StyledSources>+ <Tabs.Root value={pair.activeTab} onValueChange={onTabChange}>+ <StyledTabsScrollContainer>+ <Tabs.List+ aria-label={t`Merge review tabs`}+ render={<StyledTabsList />}+ >+ <Tabs.Tab+ value="preview"+ size="compact"+ startIcon={<IconArrowMerge size={MERGE_REVIEW_ICON_SIZE} />}+ >{t`Merge preview`}</Tabs.Tab>+ {pair.sources.map((source, index) => {+ const Icon = getPositionNumberIcon(index);++ return (+ <Tabs.Tab+ key={source.id}+ value={SOURCE_TAB_VALUES[index]}+ size="compact"+ startIcon={<Icon size={MERGE_REVIEW_ICON_SIZE} />}+ >+ {getPositionWordLabel(index)}+ </Tabs.Tab>+ );+ })}+ <Tabs.Tab+ value="settings"+ size="compact"+ startIcon={<IconSettings size={MERGE_REVIEW_ICON_SIZE} />}+ >{t`Settings`}</Tabs.Tab>+ <Tabs.Indicator />+ </Tabs.List>+ </StyledTabsScrollContainer>+ <Tabs.Panel value="preview">+ {isDefined(priorityRecord) && (+ <StyledContent>+ <StyledFields>{pair.preview}</StyledFields>+ </StyledContent>+ )}+ </Tabs.Panel>+ {pair.sources.map((source, index) => (+ <Tabs.Panel key={source.id} value={SOURCE_TAB_VALUES[index]}>+ <StyledContent>+ <StyledFields>{source.content}</StyledFields>+ </StyledContent>+ </Tabs.Panel>+ ))}+ <Tabs.Panel value="settings">+ <StyledContent>+ <MergePrioritySettings+ selectedRecordCount={pair.sources.length}+ priorityRecordIndex={priorityRecordIndex}+ onPriorityRecordIndexChange={(index) => {+ const source = pair.sources[index];++ if (isDefined(source)) {+ onPriorityRecordChange(source.id);+ }+ }}+ dropdownId={`merge-review-priority-${pair.id}`}+ disabled={disabled}+ />+ </StyledContent>+ </Tabs.Panel>+ </Tabs.Root>+ </StyledReview>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatApprovalReviewDeck.tsx b/packages/twenty-front/src/modules/ai/components/AiChatApprovalReviewDeck.tsxindex efc3efb00cd..5dc985caae9 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatApprovalReviewDeck.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatApprovalReviewDeck.tsx@@ -100,8 +100,10 @@ type AiChatApprovalReviewDeckProps = {onActiveIndexChange: (index: number) => void;onRequestApproval: (cardIds: string[]) => void;onDeny: (cardId: string) => void;+ getApproveAllLabel?: (pendingCardCount: number) => string;+ previousLabel?: string;+ nextLabel?: string;disabled?: boolean;- approveAllLabel?: string;};export const AiChatApprovalReviewDeck = ({@@ -110,8 +112,10 @@ export const AiChatApprovalReviewDeck = ({onActiveIndexChange,onRequestApproval,onDeny,+ getApproveAllLabel,+ previousLabel,+ nextLabel,disabled = false,- approveAllLabel,}: AiChatApprovalReviewDeckProps) => {const { t } = useLingui();const activeCard = cards[activeIndex];@@ -177,8 +181,8 @@ export const AiChatApprovalReviewDeck = ({disabled={disabled}onIndexChange={onActiveIndexChange}positionText={`${activeIndex + 1}/${cards.length}`}- previousLabel={t`Previous approval`}- nextLabel={t`Next approval`}+ previousLabel={previousLabel ?? t`Previous approval`}+ nextLabel={nextLabel ?? t`Next approval`}/>)}</StyledHeader>@@ -214,7 +218,8 @@ export const AiChatApprovalReviewDeck = ({disabled={!canApproveAll}onClick={() => onRequestApproval(pendingCardIds)}>- {approveAllLabel ?? t`Approve all ${pendingCardCount}`}+ {getApproveAllLabel?.(pendingCardCount) ??+ t`Approve all ${pendingCardCount}`}</Button>)}<Buttondiff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeFixture.ts b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeFixture.tsnew file mode 100644index 00000000000..3235b6b065a--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeFixture.ts@@ -0,0 +1,26 @@+import { type ReactNode } from 'react';++type MergeFieldValues = {+ url: string;+ owner: string;+ address: string;+ isIdealCustomer: boolean;+ revenue: string;+ linkedin: string;+ twitter: string;+};++type MergeSourceFixture = {+ id: string;+ name: string;+ subtitle: string;+ avatarIcon?: ReactNode;+ fields: MergeFieldValues;+};++export type AiChatApprovalMergeFixture = {+ id: string;+ title: string;+ sources: readonly [MergeSourceFixture, MergeSourceFixture];+ previews: Record<string, MergeFieldValues>;+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReview.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReview.stories.tsxnew file mode 100644index 00000000000..9adba5eb7b3--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReview.stories.tsx@@ -0,0 +1,412 @@+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 { AiChatApprovalMergeReview } from '@/ai/components/AiChatApprovalMergeReview';+import { AiChatApprovalMergeReviewExample } from '@/ai/components/__stories__/AiChatApprovalMergeReviewExample';+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';+import { RootDecorator } from '~/testing/decorators/RootDecorator';++const meta = {+ title: 'Modules/AI/AiChatApprovalMergeReview',+ component: AiChatApprovalMergeReviewExample,+ decorators: [ComponentDecorator, MemoryRouterDecorator, RootDecorator],+ parameters: { container: { width: 728 }, argos: { fitToContent: false } },+ args: { onMerge: fn(), onSkip: fn() },+} satisfies Meta<typeof AiChatApprovalMergeReviewExample>;++export default meta;++type Story = StoryObj<typeof meta>;++export const Pending: Story = {};++export const SourceRecords: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const sources = within(+ canvas.getByRole('group', { name: 'Source records' }),+ );++ await expect(sources.getByText('First: Google')).toBeVisible();+ await expect(sources.getByText('Second: Google Inc.')).toBeVisible();+ await expect(canvas.getByText('Survives')).toBeVisible();+ await expect(+ canvas.getByRole('button', { name: 'Previous pair' }),+ ).toBeDisabled();+ await userEvent.click(canvas.getByRole('tab', { name: 'First' }));++ const firstSource = within(canvas.getByRole('tabpanel'));++ await expect(+ firstSource.getByRole('link', { name: 'google.com' }),+ ).toBeVisible();+ await expect(firstSource.getByText('Tim Apple')).toBeVisible();+ await userEvent.click(canvas.getByRole('tab', { name: 'Second' }));++ const secondSource = within(canvas.getByRole('tabpanel'));++ await expect(+ canvas.getByText('Google Inc.', { exact: true }),+ ).toBeVisible();+ await expect(canvas.getByText('Survives')).toBeVisible();+ await expect(+ secondSource.getByRole('link', { name: 'about.google' }),+ ).toBeVisible();+ await expect(secondSource.getByText('Sundar Pichai')).toBeVisible();+ await expect(+ secondSource.queryByText('1600 Amphitheatre Pkwy'),+ ).not.toBeInTheDocument();+ await userEvent.click(canvas.getByRole('tab', { name: 'Merge preview' }));+ await expect(canvas.getByText('Google', { exact: true })).toBeVisible();+ await expect(canvas.getByText('Survives')).toBeVisible();+ await expect(+ within(canvas.getByRole('tabpanel')).getByText('1600 Amphitheatre Pkwy'),+ ).toBeVisible();+ },+};++export const RetainedChoicesAndSingleMerge: Story = {+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(canvas.getByRole('tab', { name: 'Settings' }));+ await userEvent.click(+ canvas.getByRole('button', { name: 'First record holds priority' }),+ );+ await userEvent.click(+ await body.findByRole('option', { name: 'Second record holds priority' }),+ );+ await expect(+ canvas.getByRole('button', { name: 'Second record holds priority' }),+ ).toBeVisible();+ await userEvent.click(canvas.getByRole('button', { name: 'Next pair' }));+ await expect(+ canvas.getByRole('tab', { name: 'Merge preview' }),+ ).toHaveAttribute('aria-selected', 'true');+ await userEvent.click(canvas.getByRole('tab', { name: 'First' }));+ await userEvent.click(+ canvas.getByRole('button', { name: 'Previous pair' }),+ );+ await expect(canvas.getByRole('tab', { name: 'Settings' })).toHaveAttribute(+ 'aria-selected',+ 'true',+ );+ await expect(+ canvas.getByRole('button', { name: 'Second record holds priority' }),+ ).toBeVisible();+ await userEvent.click(canvas.getByRole('tab', { name: 'Merge preview' }));+ await expect(+ canvas.getByText('Google Inc.', { exact: true }),+ ).toBeVisible();+ await expect(canvas.getByText('Survives')).toBeVisible();+ await expect(+ within(canvas.getByRole('tabpanel')).getByRole('link', {+ name: 'about.google',+ }),+ ).toBeVisible();+ await expect(+ within(canvas.getByRole('tabpanel')).getByText('1600 Amphitheatre Pkwy'),+ ).toBeVisible();+ await userEvent.click(canvas.getByRole('button', { name: 'Next pair' }));+ await expect(canvas.getByRole('tab', { name: 'First' })).toHaveAttribute(+ 'aria-selected',+ 'true',+ );+ await userEvent.click(+ canvas.getByRole('button', { name: 'Previous pair' }),+ );+ await expect(+ canvas.getByRole('tab', { name: 'Merge preview' }),+ ).toHaveAttribute('aria-selected', 'true');+ const nextPair = canvas.getByRole('button', { name: 'Next pair' });+ const skip = canvas.getByRole('button', { name: 'Skip' });++ await userEvent.click(canvas.getByRole('button', { name: 'Merge' }));++ const dialog = await body.findByRole('alertdialog');+ const confirmation = within(dialog);++ await expect(+ confirmation.getByRole('heading', { name: 'Approve 1 action?' }),+ ).toBeVisible();+ await expect(+ confirmation.getByText('2 records selected · 0 records skipped'),+ ).toBeVisible();+ await expect(+ confirmation.getByText('Merge Google and Google Inc.'),+ ).toBeVisible();+ await expect(nextPair).toBeDisabled();+ await expect(skip).toBeDisabled();+ await expect(args.onMerge).not.toHaveBeenCalled();+ await userEvent.click(confirmation.getByRole('button', { name: 'Cancel' }));+ await waitFor(() =>+ expect(body.queryByRole('alertdialog')).not.toBeInTheDocument(),+ );+ await expect(+ canvas.getByText('Google Inc.', { exact: true }),+ ).toBeVisible();+ await userEvent.click(canvas.getByRole('button', { name: 'Merge' }));+ await userEvent.click(+ within(await body.findByRole('alertdialog')).getByRole('button', {+ name: 'Confirm approval',+ }),+ );+ await expect(args.onMerge).toHaveBeenCalledWith({+ pairs: [+ {+ pairId: 'merge-google',+ priorityRecordId: 'google-inc',+ sourceRecordIds: ['google', 'google-inc'],+ },+ ],+ });+ await waitFor(() =>+ expect(body.queryByRole('alertdialog')).not.toBeInTheDocument(),+ );+ await expect(canvas.getByText('Succeeded')).toBeVisible();+ await expect(canvas.getByRole('button', { name: 'Merge' })).toBeDisabled();+ await userEvent.click(canvas.getByRole('button', { name: 'Next pair' }));+ await expect(canvas.getByRole('button', { name: 'Merge' })).toBeEnabled();+ await expect(canvas.getByRole('tab', { name: 'First' })).toHaveAttribute(+ 'aria-selected',+ 'true',+ );+ await expect(args.onSkip).not.toHaveBeenCalled();+ },+};++export const SkipCurrentPair: Story = {+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(canvas.getByRole('button', { name: 'Skip' }));+ await expect(args.onSkip).toHaveBeenCalledWith('merge-google');+ await expect(args.onMerge).not.toHaveBeenCalled();+ await expect(canvas.getByText('Skipped')).toBeVisible();+ await expect(canvas.getByRole('button', { name: 'Merge' })).toBeDisabled();+ await expect(+ canvas.getByRole('button', { name: 'Merge all 3' }),+ ).toBeEnabled();+ await userEvent.click(canvas.getByRole('button', { name: 'Next pair' }));+ await expect(canvas.getByText('Stripe', { exact: true })).toBeVisible();+ await expect(canvas.getByRole('button', { name: 'Merge' })).toBeEnabled();+ await expect(canvas.getByRole('button', { name: 'Skip' })).toBeEnabled();+ },+};++export const MergeAllPendingPairs: Story = {+ args: {+ initialStatuses: { 'merge-airbnb': 'blocked', 'merge-linear': 'success' },+ initialPriorityRecordIds: { 'merge-stripe': 'stripe-inc' },+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(canvas.getByRole('tab', { name: 'Settings' }));+ await userEvent.click(+ canvas.getByRole('button', { name: 'First record holds priority' }),+ );+ await userEvent.click(+ await body.findByRole('option', { name: 'Second record holds priority' }),+ );+ await userEvent.click(canvas.getByRole('button', { name: 'Merge all 2' }));++ const confirmation = within(await body.findByRole('alertdialog'));++ await expect(+ confirmation.getByRole('heading', { name: 'Approve 2 actions?' }),+ ).toBeVisible();+ await expect(confirmation.getAllByRole('listitem')).toHaveLength(2);+ await expect(+ confirmation.getByText('Merge Google and Google Inc.'),+ ).toBeVisible();+ await expect(+ confirmation.getByText('Merge Stripe and Stripe Inc.'),+ ).toBeVisible();+ await expect(+ confirmation.getByText('4 records selected · 0 records skipped'),+ ).toBeVisible();+ await expect(args.onMerge).not.toHaveBeenCalled();+ await userEvent.click(+ confirmation.getByRole('button', { name: 'Confirm approval' }),+ );+ await expect(args.onMerge).toHaveBeenCalledWith({+ pairs: [+ {+ pairId: 'merge-google',+ priorityRecordId: 'google-inc',+ sourceRecordIds: ['google', 'google-inc'],+ },+ {+ pairId: 'merge-stripe',+ priorityRecordId: 'stripe-inc',+ sourceRecordIds: ['stripe', 'stripe-inc'],+ },+ ],+ });+ await expect(+ canvas.queryByRole('button', { name: /Merge all/ }),+ ).not.toBeInTheDocument();+ },+};++export const KeyboardTabs: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const previewTab = canvas.getByRole('tab', { name: 'Merge preview' });++ await userEvent.click(previewTab);+ await userEvent.keyboard('{ArrowRight}');+ await expect(canvas.getByRole('tab', { name: 'First' })).toHaveFocus();+ await expect(canvas.getByRole('tab', { name: 'First' })).toHaveAttribute(+ 'aria-selected',+ 'false',+ );+ await userEvent.keyboard('{Enter}');+ await expect(canvas.getByRole('tab', { name: 'First' })).toHaveAttribute(+ 'aria-selected',+ 'true',+ );+ await userEvent.keyboard('{End}');+ await expect(canvas.getByRole('tab', { name: 'Settings' })).toHaveFocus();+ await userEvent.keyboard('{Enter}');+ await expect(canvas.getByRole('tab', { name: 'Settings' })).toHaveAttribute(+ 'aria-selected',+ 'true',+ );+ },+};++export const InvalidPriorityRequiresSource: Story = {+ args: {+ initialPriorityRecordIds: { 'merge-google': 'synthetic-preview-id' },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await expect(+ canvas.getByText('Choose a source record to keep'),+ ).toBeVisible();+ await expect(canvas.queryByText('Survives')).not.toBeInTheDocument();+ await expect(canvas.getByRole('button', { name: 'Merge' })).toBeDisabled();+ await expect(canvas.getByRole('button', { name: 'Skip' })).toBeEnabled();+ await expect(+ canvas.getByRole('button', { name: 'Merge all 4' }),+ ).toBeDisabled();+ await userEvent.click(canvas.getByRole('tab', { name: 'Settings' }));+ await userEvent.click(+ canvas.getByRole('button', { name: 'No record holds priority' }),+ );+ await userEvent.click(+ await body.findByRole('option', { name: 'First record holds priority' }),+ );+ await expect(canvas.getByRole('button', { name: 'Merge' })).toBeEnabled();+ await expect(+ canvas.getByRole('button', { name: 'Merge all 4' }),+ ).toBeEnabled();+ await expect(canvas.getByText('Google', { exact: true })).toBeVisible();+ await expect(canvas.getByText('Survives')).toBeVisible();+ await expect(+ canvas.queryByText('Choose a source record to keep'),+ ).not.toBeInTheDocument();+ },+};++export const Running: Story = {+ args: { initialStatus: 'running', initialActiveTab: 'settings' },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByRole('button', { name: 'Skip' })).toBeDisabled();+ await expect(canvas.getByRole('button', { name: 'Merge' })).toBeDisabled();+ await expect(canvas.getByText('First record holds priority')).toBeVisible();+ await expect(+ canvas.queryByRole('button', { name: /record holds priority/ }),+ ).not.toBeInTheDocument();+ await expect(+ canvas.getByRole('progressbar', { name: 'Action progress' }),+ ).toHaveAttribute('aria-valuenow', '1');+ },+};++export const Success: Story = { args: { initialStatus: 'success' } };+export const Failed: Story = { args: { initialStatus: 'failed' } };+export const Blocked: Story = { args: { initialStatus: 'blocked' } };+export const Uncertain: Story = { args: { initialStatus: 'uncertain' } };+export const Skipped: Story = { args: { initialStatus: 'skipped' } };++export const MixedOutcomes: Story = {+ args: {+ initialStatuses: {+ 'merge-google': 'success',+ 'merge-stripe': 'failed',+ 'merge-airbnb': 'blocked',+ 'merge-linear': 'uncertain',+ },+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ for (const label of ['Succeeded', 'Failed', 'Blocked', 'Outcome unknown']) {+ await expect(canvas.getByText(label)).toBeVisible();+ await expect(+ canvas.getByRole('button', { name: 'Merge' }),+ ).toBeDisabled();+ await expect(canvas.getByRole('button', { name: 'Skip' })).toBeDisabled();++ if (label !== 'Outcome unknown') {+ await userEvent.click(+ canvas.getByRole('button', { name: 'Next pair' }),+ );+ }+ }++ await expect(+ canvas.getByRole('button', { name: 'Next pair' }),+ ).toBeDisabled();+ await expect(args.onMerge).not.toHaveBeenCalled();+ await expect(args.onSkip).not.toHaveBeenCalled();+ },+};++export const Narrow: Story = {+ parameters: { container: { width: 360 } },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const card = canvas.getByRole('group', { name: 'Merge 2 companies' });++ await expect(card.scrollWidth).toBeLessThanOrEqual(card.clientWidth);+ await expect(canvas.getByRole('button', { name: 'Merge' })).toBeVisible();+ await expect(canvas.getByRole('button', { name: 'Skip' })).toBeVisible();+ await userEvent.click(canvas.getByRole('tab', { name: 'Settings' }));+ await expect(+ canvas.getByRole('button', { name: 'First record holds priority' }),+ ).toBeVisible();+ },+};++export const Empty: Story = {+ render: () => (+ <AiChatApprovalMergeReview+ pairs={[]}+ activeIndex={0}+ onActiveIndexChange={fn()}+ onTabChange={fn()}+ onPriorityRecordChange={fn()}+ onRequestMerge={fn()}+ onSkip={fn()}+ />+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByRole('status')).toHaveTextContent(+ 'No actions to review',+ );+ await expect(canvas.queryByRole('button')).not.toBeInTheDocument();+ },+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReviewExample.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReviewExample.tsxnew file mode 100644index 00000000000..6d79dc86c6e--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReviewExample.tsx@@ -0,0 +1,174 @@+import { useLingui } from '@lingui/react/macro';+import { useState } from 'react';+import { isDefined } from 'twenty-shared/utils';++import { AiChatApprovalConfirmation } from '@/ai/components/AiChatApprovalConfirmation';+import { AiChatApprovalMergeReview } from '@/ai/components/AiChatApprovalMergeReview';+import { type AiChatApprovalMergeFixture } from '@/ai/components/__stories__/AiChatApprovalMergeFixture';+import { AiChatApprovalMergeReviewFields } from '@/ai/components/__stories__/AiChatApprovalMergeReviewFields';+import { type AiChatApprovalMergeReviewSnapshot } from '@/ai/components/__stories__/AiChatApprovalMergeReviewSnapshot';+import { AI_CHAT_APPROVAL_MERGE_FIXTURES } from '@/ai/components/__stories__/aiChatApprovalMergeFixtures';+import { type AiChatApprovalMergePair } from '@/ai/types/AiChatApprovalMergePair';+import { type AiChatApprovalMergeSourceRecord } from '@/ai/types/AiChatApprovalMergeSourceRecord';+import { type AiChatApprovalReviewStatus } from '@/ai/types/AiChatApprovalReviewStatus';++const createSourceRecord = (+ source: AiChatApprovalMergeFixture['sources'][number],+): AiChatApprovalMergeSourceRecord => ({+ id: source.id,+ name: source.name,+ subtitle: source.subtitle,+ avatarIcon: source.avatarIcon,+ content: <AiChatApprovalMergeReviewFields fields={source.fields} />,+});++const mapMergeFixturesById = <TValue,>(+ getValue: (fixture: AiChatApprovalMergeFixture) => TValue,+): Record<string, TValue> =>+ Object.fromEntries(+ AI_CHAT_APPROVAL_MERGE_FIXTURES.map((fixture) => [+ fixture.id,+ getValue(fixture),+ ]),+ );++type AiChatApprovalMergeReviewExampleProps = {+ initialStatus?: AiChatApprovalReviewStatus;+ initialStatuses?: Record<string, AiChatApprovalReviewStatus>;+ initialActiveIndex?: number;+ initialPriorityRecordIds?: Record<string, string>;+ initialActiveTab?: AiChatApprovalMergePair['activeTab'];+ onMerge: (snapshot: AiChatApprovalMergeReviewSnapshot) => void;+ onSkip: (pairId: string) => void;+};++export const AiChatApprovalMergeReviewExample = ({+ initialStatus = 'pending',+ initialStatuses,+ initialActiveIndex = 0,+ initialPriorityRecordIds,+ initialActiveTab = 'preview',+ onMerge,+ onSkip,+}: AiChatApprovalMergeReviewExampleProps) => {+ const { t } = useLingui();+ const [activeIndex, setActiveIndex] = useState(initialActiveIndex);+ const [statuses, setStatuses] = useState(() =>+ mapMergeFixturesById(({ id }) => initialStatuses?.[id] ?? initialStatus),+ );+ const [priorityRecordIds, setPriorityRecordIds] = useState(() =>+ mapMergeFixturesById(+ ({ id, sources }) => initialPriorityRecordIds?.[id] ?? sources[0].id,+ ),+ );+ const [activeTabs, setActiveTabs] = useState(() =>+ mapMergeFixturesById(() => initialActiveTab),+ );+ const [confirmation, setConfirmation] =+ useState<AiChatApprovalMergeReviewSnapshot | null>(null);++ const handleRequestMerge = (pairIds: string[]) => {+ setConfirmation({+ pairs: AI_CHAT_APPROVAL_MERGE_FIXTURES.filter(+ ({ id }) => pairIds.includes(id) && statuses[id] === 'pending',+ ).map(({ id, sources }) => ({+ pairId: id,+ priorityRecordId: priorityRecordIds[id],+ sourceRecordIds: [sources[0].id, sources[1].id],+ })),+ });+ };++ const handleConfirm = () => {+ if (!isDefined(confirmation)) {+ return;+ }++ onMerge(confirmation);+ setStatuses((currentStatuses) => ({+ ...currentStatuses,+ ...Object.fromEntries(+ confirmation.pairs.map(({ pairId }) => [pairId, 'success']),+ ),+ }));+ setConfirmation(null);+ };++ const handleSkip = (pairId: string) => {+ setStatuses((currentStatuses) => ({+ ...currentStatuses,+ [pairId]: 'skipped',+ }));+ onSkip(pairId);+ };++ const pairs: AiChatApprovalMergePair[] = AI_CHAT_APPROVAL_MERGE_FIXTURES.map(+ (fixture) => {+ const priorityRecordId = priorityRecordIds[fixture.id];+ const previewFields = fixture.previews[priorityRecordId];+ const status = statuses[fixture.id];++ return {+ id: fixture.id,+ title: fixture.title,+ sources: [+ createSourceRecord(fixture.sources[0]),+ createSourceRecord(fixture.sources[1]),+ ],+ priorityRecordId,+ activeTab: activeTabs[fixture.id],+ preview: isDefined(previewFields) ? (+ <AiChatApprovalMergeReviewFields fields={previewFields} />+ ) : null,+ status,+ outcomeMessage:+ status === 'uncertain'+ ? t`Check the merge result before trying again`+ : undefined,+ progress: status === 'running' ? { completed: 1, total: 2 } : undefined,+ };+ },+ );++ return (+ <>+ <AiChatApprovalMergeReview+ pairs={pairs}+ activeIndex={activeIndex}+ onActiveIndexChange={setActiveIndex}+ onTabChange={({ pairId, tab }) =>+ setActiveTabs((currentTabs) => ({ ...currentTabs, [pairId]: tab }))+ }+ onPriorityRecordChange={({ pairId, priorityRecordId }) =>+ setPriorityRecordIds((currentPriorities) => ({+ ...currentPriorities,+ [pairId]: priorityRecordId,+ }))+ }+ onRequestMerge={handleRequestMerge}+ onSkip={handleSkip}+ disabled={isDefined(confirmation)}+ />+ {isDefined(confirmation) && (+ <AiChatApprovalConfirmation+ cards={confirmation.pairs.map(({ pairId }) => {+ const fixture = AI_CHAT_APPROVAL_MERGE_FIXTURES.find(+ ({ id }) => id === pairId,+ );+ const firstSourceName = fixture?.sources[0].name;+ const secondSourceName = fixture?.sources[1].name;++ return {+ id: pairId,+ title: t`Merge ${firstSourceName} and ${secondSourceName}`,+ selectedCount: 2,+ skippedCount: 0,+ };+ })}+ onConfirm={handleConfirm}+ onCancel={() => setConfirmation(null)}+ />+ )}+ </>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReviewFields.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReviewFields.tsxnew file mode 100644index 00000000000..110d1f220d5--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReviewFields.tsx@@ -0,0 +1,124 @@+import { styled } from '@linaria/react';+import { DetailsRow } from 'twenty-ui/components/data-display';+import {+ IconBrandLinkedin,+ IconBrandX,+ IconCurrencyDollar,+ IconLink,+ IconMap,+ IconTarget,+ IconUserCircle,+} from 'twenty-ui/icon';+import { Avatar, Chip } from 'twenty-ui/primitives/data-display';+import { themeCssVariables } from 'twenty-ui/theme';++import { type AiChatApprovalMergeFixture } from '@/ai/components/__stories__/AiChatApprovalMergeFixture';+import { BooleanDisplay } from '@/ui/field/display/components/BooleanDisplay';+import { LinkDisplay } from '@/ui/field/display/components/LinkDisplay';+import { TextDisplay } from '@/ui/field/display/components/TextDisplay/TextDisplay';++const MERGE_FIELD_ICON_SIZE = 14;+const MERGE_FIELD_LABEL_WIDTH = 112;++const StyledFields = styled.dl`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[2]};+ margin: 0;+ min-width: 0;+`;++const StyledValue = styled.div`+ align-items: center;+ display: flex;+ font-size: ${themeCssVariables.font.size.md};+ min-width: 0;+`;++const StyledOwner = styled.span`+ align-items: center;+ display: inline-flex;+ gap: ${themeCssVariables.spacing[1]};+ min-width: 0;+`;++type AiChatApprovalMergeReviewFieldsProps = {+ fields: AiChatApprovalMergeFixture['sources'][number]['fields'];+};++export const AiChatApprovalMergeReviewFields = ({+ fields,+}: AiChatApprovalMergeReviewFieldsProps) => (+ <StyledFields>+ <DetailsRow+ label="URL"+ labelWidth={MERGE_FIELD_LABEL_WIDTH}+ startIcon={<IconLink size={MERGE_FIELD_ICON_SIZE} />}+ >+ <StyledValue>+ <LinkDisplay value={{ url: fields.url }} />+ </StyledValue>+ </DetailsRow>+ <DetailsRow+ label="Account Owner"+ labelWidth={MERGE_FIELD_LABEL_WIDTH}+ startIcon={<IconUserCircle size={MERGE_FIELD_ICON_SIZE} />}+ >+ <StyledValue>+ <StyledOwner>+ <Avatar name={fields.owner} size="sm" shape="circle" />+ <TextDisplay text={fields.owner} />+ </StyledOwner>+ </StyledValue>+ </DetailsRow>+ <DetailsRow+ label="Address"+ labelWidth={MERGE_FIELD_LABEL_WIDTH}+ startIcon={<IconMap size={MERGE_FIELD_ICON_SIZE} />}+ >+ <StyledValue>+ <TextDisplay text={fields.address} />+ </StyledValue>+ </DetailsRow>+ <DetailsRow+ label="ICP"+ labelWidth={MERGE_FIELD_LABEL_WIDTH}+ startIcon={<IconTarget size={MERGE_FIELD_ICON_SIZE} />}+ >+ <StyledValue>+ <BooleanDisplay value={fields.isIdealCustomer} />+ </StyledValue>+ </DetailsRow>+ <DetailsRow+ label="Revenue"+ labelWidth={MERGE_FIELD_LABEL_WIDTH}+ startIcon={<IconCurrencyDollar size={MERGE_FIELD_ICON_SIZE} />}+ >+ <StyledValue>+ <TextDisplay text={fields.revenue} />+ </StyledValue>+ </DetailsRow>+ <DetailsRow+ label="Linkedin"+ labelWidth={MERGE_FIELD_LABEL_WIDTH}+ startIcon={<IconBrandLinkedin size={MERGE_FIELD_ICON_SIZE} />}+ >+ <StyledValue>+ <LinkDisplay+ value={{ url: fields.linkedin, label: 'linkedin.com/company...' }}+ />+ </StyledValue>+ </DetailsRow>+ <DetailsRow+ label="Twitter"+ labelWidth={MERGE_FIELD_LABEL_WIDTH}+ startIcon={<IconBrandX size={MERGE_FIELD_ICON_SIZE} />}+ >+ <StyledValue>+ <Chip variant="outline" shape="round">+ {fields.twitter}+ </Chip>+ </StyledValue>+ </DetailsRow>+ </StyledFields>+);diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReviewSnapshot.ts b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReviewSnapshot.tsnew file mode 100644index 00000000000..e20c138c03c--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatApprovalMergeReviewSnapshot.ts@@ -0,0 +1,7 @@+export type AiChatApprovalMergeReviewSnapshot = {+ pairs: {+ pairId: string;+ priorityRecordId: string;+ sourceRecordIds: readonly [string, string];+ }[];+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/aiChatApprovalMergeFixtures.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/aiChatApprovalMergeFixtures.tsxnew file mode 100644index 00000000000..30a4248412e--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/aiChatApprovalMergeFixtures.tsx@@ -0,0 +1,225 @@+import { IconGoogle } from 'twenty-ui/icon';++import { type AiChatApprovalMergeFixture } from '@/ai/components/__stories__/AiChatApprovalMergeFixture';++export const AI_CHAT_APPROVAL_MERGE_FIXTURES: readonly AiChatApprovalMergeFixture[] =+ [+ {+ id: 'merge-google',+ title: 'Merge 2 companies',+ sources: [+ {+ id: 'google',+ name: 'Google',+ subtitle: 'Created 4 hours ago',+ avatarIcon: <IconGoogle size={24} />,+ fields: {+ url: 'google.com',+ owner: 'Tim Apple',+ address: '1600 Amphitheatre Pkwy',+ isIdealCustomer: true,+ revenue: '$350B',+ linkedin: 'linkedin.com/company/google',+ twitter: '@google',+ },+ },+ {+ id: 'google-inc',+ name: 'Google Inc.',+ subtitle: 'Created 2 days ago',+ avatarIcon: <IconGoogle size={24} />,+ fields: {+ url: 'about.google',+ owner: 'Sundar Pichai',+ address: '',+ isIdealCustomer: true,+ revenue: '$348B',+ linkedin: 'linkedin.com/company/google',+ twitter: '@google',+ },+ },+ ],+ previews: {+ google: {+ url: 'google.com',+ owner: 'Tim Apple',+ address: '1600 Amphitheatre Pkwy',+ isIdealCustomer: true,+ revenue: '$350B',+ linkedin: 'linkedin.com/company/google',+ twitter: '@google',+ },+ 'google-inc': {+ url: 'about.google',+ owner: 'Sundar Pichai',+ address: '1600 Amphitheatre Pkwy',+ isIdealCustomer: true,+ revenue: '$348B',+ linkedin: 'linkedin.com/company/google',+ twitter: '@google',+ },+ },+ },+ {+ id: 'merge-stripe',+ title: 'Merge 2 companies',+ sources: [+ {+ id: 'stripe',+ name: 'Stripe',+ subtitle: 'Created 1 day ago',+ fields: {+ url: 'stripe.com',+ owner: 'Patrick Collison',+ address: '354 Oyster Point Blvd',+ isIdealCustomer: true,+ revenue: '$16B',+ linkedin: 'linkedin.com/company/stripe',+ twitter: '@stripe',+ },+ },+ {+ id: 'stripe-inc',+ name: 'Stripe Inc.',+ subtitle: 'Created 3 days ago',+ fields: {+ url: 'stripe.com',+ owner: 'John Collison',+ address: 'The One Building, Dublin',+ isIdealCustomer: true,+ revenue: '$15B',+ linkedin: 'linkedin.com/company/stripe',+ twitter: '@stripe',+ },+ },+ ],+ previews: {+ stripe: {+ url: 'stripe.com',+ owner: 'Patrick Collison',+ address: '354 Oyster Point Blvd',+ isIdealCustomer: true,+ revenue: '$16B',+ linkedin: 'linkedin.com/company/stripe',+ twitter: '@stripe',+ },+ 'stripe-inc': {+ url: 'stripe.com',+ owner: 'John Collison',+ address: 'The One Building, Dublin',+ isIdealCustomer: true,+ revenue: '$15B',+ linkedin: 'linkedin.com/company/stripe',+ twitter: '@stripe',+ },+ },+ },+ {+ id: 'merge-airbnb',+ title: 'Merge 2 companies',+ sources: [+ {+ id: 'airbnb',+ name: 'Airbnb',+ subtitle: 'Created 2 days ago',+ fields: {+ url: 'airbnb.com',+ owner: 'Brian Chesky',+ address: '888 Brannan St',+ isIdealCustomer: false,+ revenue: '$11B',+ linkedin: 'linkedin.com/company/airbnb',+ twitter: '@airbnb',+ },+ },+ {+ id: 'airbnb-inc',+ name: 'Airbnb Inc.',+ subtitle: 'Created 5 days ago',+ fields: {+ url: 'airbnb.com',+ owner: 'Nathan Blecharczyk',+ address: '888 Brannan St',+ isIdealCustomer: false,+ revenue: '$10B',+ linkedin: 'linkedin.com/company/airbnb',+ twitter: '@airbnb',+ },+ },+ ],+ previews: {+ airbnb: {+ url: 'airbnb.com',+ owner: 'Brian Chesky',+ address: '888 Brannan St',+ isIdealCustomer: false,+ revenue: '$11B',+ linkedin: 'linkedin.com/company/airbnb',+ twitter: '@airbnb',+ },+ 'airbnb-inc': {+ url: 'airbnb.com',+ owner: 'Nathan Blecharczyk',+ address: '888 Brannan St',+ isIdealCustomer: false,+ revenue: '$10B',+ linkedin: 'linkedin.com/company/airbnb',+ twitter: '@airbnb',+ },+ },+ },+ {+ id: 'merge-linear',+ title: 'Merge 2 companies',+ sources: [+ {+ id: 'linear',+ name: 'Linear',+ subtitle: 'Created 3 days ago',+ fields: {+ url: 'linear.app',+ owner: 'Karri Saarinen',+ address: 'San Francisco',+ isIdealCustomer: true,+ revenue: '$100M',+ linkedin: 'linkedin.com/company/linear',+ twitter: '@linear',+ },+ },+ {+ id: 'linear-orbit',+ name: 'Linear Orbit',+ subtitle: 'Created 1 week ago',+ fields: {+ url: 'linear.app',+ owner: 'Jori Lallo',+ address: 'San Francisco',+ isIdealCustomer: true,+ revenue: '$90M',+ linkedin: 'linkedin.com/company/linear',+ twitter: '@linear',+ },+ },+ ],+ previews: {+ linear: {+ url: 'linear.app',+ owner: 'Karri Saarinen',+ address: 'San Francisco',+ isIdealCustomer: true,+ revenue: '$100M',+ linkedin: 'linkedin.com/company/linear',+ twitter: '@linear',+ },+ 'linear-orbit': {+ url: 'linear.app',+ owner: 'Jori Lallo',+ address: 'San Francisco',+ isIdealCustomer: true,+ revenue: '$90M',+ linkedin: 'linkedin.com/company/linear',+ twitter: '@linear',+ },+ },+ },+ ];diff --git a/packages/twenty-front/src/modules/ai/types/AiChatApprovalMergePair.ts b/packages/twenty-front/src/modules/ai/types/AiChatApprovalMergePair.tsnew file mode 100644index 00000000000..ae87a35ae33--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatApprovalMergePair.ts@@ -0,0 +1,19 @@+import { type ReactNode } from 'react';++import { type AiChatApprovalMergeSourceRecord } from '@/ai/types/AiChatApprovalMergeSourceRecord';+import { type AiChatApprovalReviewStatus } from '@/ai/types/AiChatApprovalReviewStatus';++export type AiChatApprovalMergePair = {+ id: string;+ title: string;+ sources: readonly [+ AiChatApprovalMergeSourceRecord,+ AiChatApprovalMergeSourceRecord,+ ];+ priorityRecordId: string;+ activeTab: 'preview' | 'first' | 'second' | 'settings';+ preview: ReactNode;+ status: AiChatApprovalReviewStatus;+ outcomeMessage?: string;+ progress?: { completed: number; total: number };+};diff --git a/packages/twenty-front/src/modules/ai/types/AiChatApprovalMergeSourceRecord.ts b/packages/twenty-front/src/modules/ai/types/AiChatApprovalMergeSourceRecord.tsnew file mode 100644index 00000000000..d2a1b5258e3--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatApprovalMergeSourceRecord.ts@@ -0,0 +1,10 @@+import { type ReactNode } from 'react';++export type AiChatApprovalMergeSourceRecord = {+ id: string;+ name: string;+ avatarUrl?: string;+ avatarIcon?: ReactNode;+ subtitle?: string;+ content: ReactNode;+};diff --git a/packages/twenty-front/src/modules/object-record/record-merge/components/MergePrioritySettings.tsx b/packages/twenty-front/src/modules/object-record/record-merge/components/MergePrioritySettings.tsxnew file mode 100644index 00000000000..349d2a05db1--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-merge/components/MergePrioritySettings.tsx@@ -0,0 +1,67 @@+import { styled } from '@linaria/react';+import { t } from '@lingui/core/macro';+import { Section } from 'twenty-ui/components/layout';+import { themeCssVariables } from 'twenty-ui/theme';++import { getPositionNumberIcon } from '@/object-record/record-merge/utils/getPositionNumberIcon';+import { getPositionWordLabel } from '@/object-record/record-merge/utils/getPositionWordLabel';+import { Select } from '@/ui/input/components/Select';++const MISSING_PRIORITY_RECORD_INDEX = -1;++const StyledSectionContainer = styled.div`+ padding: ${themeCssVariables.spacing[2]};+ width: auto;+`;++type MergePrioritySettingsProps = {+ selectedRecordCount: number;+ priorityRecordIndex: number;+ onPriorityRecordIndexChange: (index: number) => void;+ dropdownId: string;+ disabled?: boolean;+};++export const MergePrioritySettings = ({+ selectedRecordCount,+ priorityRecordIndex,+ onPriorityRecordIndexChange,+ dropdownId,+ disabled = false,+}: MergePrioritySettingsProps) => {+ const priorityOptions = Array.from(+ { length: selectedRecordCount },+ (_, index) => {+ const positionLabel = getPositionWordLabel(index);++ return {+ value: index,+ label: t`${positionLabel} record holds priority`,+ Icon: getPositionNumberIcon(index),+ };+ },+ );++ if (selectedRecordCount === 0) {+ return null;+ }++ return (+ <StyledSectionContainer>+ <Section.Root>+ <Select+ dropdownId={dropdownId}+ options={priorityOptions}+ value={priorityRecordIndex}+ emptyOption={{+ value: MISSING_PRIORITY_RECORD_INDEX,+ label: t`No record holds priority`,+ }}+ onChange={onPriorityRecordIndexChange}+ label={t`Fields conflicts`}+ disabled={disabled}+ />+ </Section.Root>+ </StyledSectionContainer>+ );+};diff --git a/packages/twenty-front/src/modules/object-record/record-merge/components/MergeSettingsTab.tsx b/packages/twenty-front/src/modules/object-record/record-merge/components/MergeSettingsTab.tsxindex 52e329cf45d..dc1e67491fd 100644--- a/packages/twenty-front/src/modules/object-record/record-merge/components/MergeSettingsTab.tsx+++ b/packages/twenty-front/src/modules/object-record/record-merge/components/MergeSettingsTab.tsx@@ -1,52 +1,18 @@+import { MergePrioritySettings } from '@/object-record/record-merge/components/MergePrioritySettings';import { useMergeRecordsSelectedRecords } from '@/object-record/record-merge/hooks/useMergeRecordsSelectedRecords';import { useMergeRecordsSettings } from '@/object-record/record-merge/hooks/useMergeRecordsSettings';-import { getPositionNumberIcon } from '@/object-record/record-merge/utils/getPositionNumberIcon';-import { getPositionWordLabel } from '@/object-record/record-merge/utils/getPositionWordLabel';-import { Select } from '@/ui/input/components/Select';-import { styled } from '@linaria/react';-import { t } from '@lingui/core/macro';-import { Section } from 'twenty-ui/components/layout';-import { themeCssVariables } from 'twenty-ui/theme';--const StyledSectionContainer = styled.div`- padding: ${themeCssVariables.spacing[2]};- width: auto;-`;export const MergeSettingsTab = () => {const { mergeSettings, updatePriorityRecordIndex } =useMergeRecordsSettings();const { selectedRecords } = useMergeRecordsSelectedRecords();- const priorityOptions = selectedRecords.map((_, index) => {- const positionLabel = getPositionWordLabel(index);- return {- value: index,- label: t`${positionLabel} record holds priority`,- Icon: getPositionNumberIcon(index),- recordIndex: index,- };- });-- const handleSelectionChange = (index: number) => {- updatePriorityRecordIndex(index);- };-- if (selectedRecords.length === 0) {- return null;- }-return (- <StyledSectionContainer>- <Section.Root>- <Select- dropdownId="merge-settings-priority-select"- options={priorityOptions}- value={mergeSettings.conflictPriorityIndex}- onChange={handleSelectionChange}- label={t`Fields conflicts`}- />- </Section.Root>- </StyledSectionContainer>+ <MergePrioritySettings+ selectedRecordCount={selectedRecords.length}+ priorityRecordIndex={mergeSettings.conflictPriorityIndex}+ onPriorityRecordIndexChange={updatePriorityRecordIndex}+ dropdownId="merge-settings-priority-select"+ />);};