The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add Ada behavior settings presentation (#29304)
Raphaël Bosi06457f6e7f88
diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAiBehaviorModeSelect.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAiBehaviorModeSelect.tsxnew file mode 100644index 00000000000..12c22f5c8c3--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAiBehaviorModeSelect.tsx@@ -0,0 +1,84 @@+import { styled } from '@linaria/react';+import { t } from '@lingui/core/macro';+import { isDefined } from 'twenty-shared/utils';+import { Select } from 'twenty-ui/primitives/input';+import { type SettingsAiAssistantMode } from '~/pages/settings/ai/types/SettingsAiAssistantMode';++type SettingsAiBehaviorModeSelectProps = {+ value: SettingsAiAssistantMode | null;+ onChange: (value: SettingsAiAssistantMode) => void;+ labelledBy: string;+ describedBy: string;+ disabled: boolean;+ isLoading: boolean;+};++const StyledSelectContainer = styled.div`+ display: flex;+ justify-content: flex-end;+`;++export const SettingsAiBehaviorModeSelect = ({+ value,+ onChange,+ labelledBy,+ describedBy,+ disabled,+ isLoading,+}: SettingsAiBehaviorModeSelectProps) => {+ const options: { value: SettingsAiAssistantMode; label: string }[] = [+ { value: 'NEVER', label: t`Never` },+ { value: 'MENTION_ONLY', label: t`Only when mentioned` },+ { value: 'AUTOMATIC', label: t`Auto` },+ ];++ return (+ <StyledSelectContainer>+ <Select.Root<SettingsAiAssistantMode>+ items={options}+ value={isLoading ? null : value}+ onValueChange={(nextValue, eventDetails) => {+ const isPickedFromOptions = eventDetails.reason === 'item-press';++ if (+ !isPickedFromOptions ||+ !isDefined(nextValue) ||+ nextValue === value+ ) {+ return;+ }++ onChange(nextValue);+ }}+ disabled={disabled}+ >+ <Select.Trigger+ size="sm"+ aria-labelledby={labelledBy}+ aria-describedby={describedBy}+ >+ <Select.Value+ placeholder={isLoading ? t`Loading...` : t`Choose behavior`}+ />+ <Select.Icon />+ </Select.Trigger>+ <Select.Portal>+ <Select.Positioner+ align="end"+ sideOffset={4}+ alignItemWithTrigger={false}+ >+ <Select.Popup aria-labelledby={labelledBy}>+ {options.map(({ value: optionValue, label }) => (+ <Select.Item key={optionValue} value={optionValue}>+ <Select.ItemText>{label}</Select.ItemText>+ <Select.ItemIndicator />+ </Select.Item>+ ))}+ </Select.Popup>+ </Select.Positioner>+ </Select.Portal>+ </Select.Root>+ </StyledSelectContainer>+ );+};diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAiBehaviorSection.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAiBehaviorSection.tsxnew file mode 100644index 00000000000..e6d1cafc530--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAiBehaviorSection.tsx@@ -0,0 +1,122 @@+import { AGENT_CHAT_ASSISTANT_NAME } from '@/ai/constants/AgentChatAssistantName';+import { SettingsOptionCardContentSelect } from '@/settings/components/SettingsOptions/SettingsOptionCardContentSelect';+import { StyledSettingsSelectGroup } from '@/settings/components/SettingsOptions/StyledSettingsSelectGroup';+import { styled } from '@linaria/react';+import { t } from '@lingui/core/macro';+import { isNonEmptyString } from '@sniptt/guards';+import { useId } from 'react';+import { InlineBanner } from 'twenty-ui/components/feedback';+import { Section } from 'twenty-ui/components/layout';+import { IconAlertTriangle, IconInbox, IconMessage } from 'twenty-ui/icon';+import { VisuallyHidden } from 'twenty-ui/primitives/accessibility';+import { Card } from 'twenty-ui/primitives/surfaces';+import { Text } from 'twenty-ui/primitives/typography';+import { themeCssVariables } from 'twenty-ui/theme';+import { SettingsAiBehaviorModeSelect } from '~/pages/settings/ai/components/SettingsAiBehaviorModeSelect';+import { type SettingsAiAssistantMode } from '~/pages/settings/ai/types/SettingsAiAssistantMode';++const BEHAVIOR_SELECT_CONTROL_WIDTH = 180;++type SettingsAiBehaviorSectionProps = {+ directMessageMode: SettingsAiAssistantMode | null;+ inboxMode: SettingsAiAssistantMode | null;+ onDirectMessageModeChange: (value: SettingsAiAssistantMode) => void;+ onInboxModeChange: (value: SettingsAiAssistantMode) => void;+ isLoading?: boolean;+ disabled?: boolean;+ errorMessage?: string;+};++const StyledBehaviorMessages = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[2]};+ margin-top: ${themeCssVariables.spacing[2]};+`;++export const SettingsAiBehaviorSection = ({+ directMessageMode,+ inboxMode,+ onDirectMessageModeChange,+ onInboxModeChange,+ isLoading = false,+ disabled = false,+ errorMessage,+}: SettingsAiBehaviorSectionProps) => {+ const sectionId = useId();+ const directMessagesLabelId = `${sectionId}-direct-messages`;+ const inboxLabelId = `${sectionId}-inbox`;+ const helperId = `${sectionId}-helper`;+ const errorId = `${sectionId}-error`;+ const hasError = isNonEmptyString(errorMessage);+ const isDisabled = disabled || isLoading;+ const describedBy = hasError ? `${helperId} ${errorId}` : helperId;+ const loadingMessage = isLoading ? t`Loading behavior settings...` : '';++ return (+ <Section.Root>+ <Section.Header+ title={t`Behavior`}+ description={t`Choose when ${AGENT_CHAT_ASSISTANT_NAME} participates in conversations across your workspace`}+ />+ <Card.Root+ backgroundColor={themeCssVariables.background.secondary}+ aria-busy={isLoading}+ >+ <StyledSettingsSelectGroup controlWidth={BEHAVIOR_SELECT_CONTROL_WIDTH}>+ <SettingsOptionCardContentSelect+ Icon={IconMessage}+ title={<span id={directMessagesLabelId}>{t`DMs`}</span>}+ description={t`One-to-one conversations between people`}+ divider+ >+ <SettingsAiBehaviorModeSelect+ value={directMessageMode}+ onChange={onDirectMessageModeChange}+ labelledBy={directMessagesLabelId}+ describedBy={describedBy}+ disabled={isDisabled}+ isLoading={isLoading}+ />+ </SettingsOptionCardContentSelect>+ <SettingsOptionCardContentSelect+ Icon={IconInbox}+ title={<span id={inboxLabelId}>{t`Global inbox`}</span>}+ description={t`Other inbox conversations`}+ >+ <SettingsAiBehaviorModeSelect+ value={inboxMode}+ onChange={onInboxModeChange}+ labelledBy={inboxLabelId}+ describedBy={describedBy}+ disabled={isDisabled}+ isLoading={isLoading}+ />+ </SettingsOptionCardContentSelect>+ </StyledSettingsSelectGroup>+ </Card.Root>+ <StyledBehaviorMessages>+ <Text id={helperId} size="sm" color="tertiary">+ {t`Never keeps ${AGENT_CHAT_ASSISTANT_NAME} out. Only when mentioned asks ${AGENT_CHAT_ASSISTANT_NAME} to reply when tagged. Auto lets ${AGENT_CHAT_ASSISTANT_NAME} decide when to reply. Chats with only you and ${AGENT_CHAT_ASSISTANT_NAME} always get replies.`}+ </Text>+ {isLoading && (+ <Text aria-hidden size="sm" color="tertiary">+ {loadingMessage}+ </Text>+ )}+ <VisuallyHidden role="status">{loadingMessage}</VisuallyHidden>+ {hasError && (+ <InlineBanner+ id={errorId}+ role="alert"+ status="error"+ icon={<IconAlertTriangle aria-hidden="true" />}+ embedded+ >+ <>{errorMessage}</>+ </InlineBanner>+ )}+ </StyledBehaviorMessages>+ </Section.Root>+ );+};diff --git a/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiBehavior.stories.tsx b/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiBehavior.stories.tsxnew file mode 100644index 00000000000..4d888ddb6e4--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiBehavior.stories.tsx@@ -0,0 +1,222 @@+import { useState } from 'react';+import { Button } from 'twenty-ui/primitives/input';+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 { SettingsAiBehaviorExample } from '~/pages/settings/ai/components/__stories__/SettingsAiBehaviorExample';++const meta = {+ title: 'Pages/Settings/AI/Behavior',+ component: SettingsAiBehaviorExample,+ decorators: [ComponentDecorator],+ parameters: { container: { width: 694 } },+ args: {+ directMessageMode: 'MENTION_ONLY',+ inboxMode: 'AUTOMATIC',+ onDirectMessageModeChange: fn(),+ onInboxModeChange: fn(),+ },+} satisfies Meta<typeof SettingsAiBehaviorExample>;++export default meta;+type Story = StoryObj<typeof meta>;++export const IndependentSelection: Story = {+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const directMessages = canvas.getByRole('combobox', { name: 'DMs' });+ const inbox = canvas.getByRole('combobox', { name: 'Global inbox' });+ const bodyQueries = within(canvasElement.ownerDocument.body);++ expect(canvas.getByRole('status')).toBeEmptyDOMElement();+ expect(directMessages).toHaveTextContent('Only when mentioned');+ expect(inbox).toHaveTextContent('Auto');+ await userEvent.click(directMessages);+ const directMessageOptions = await bodyQueries.findByRole('listbox', {+ name: 'DMs',+ });++ await userEvent.click(+ within(directMessageOptions).getByRole('option', { name: 'Never' }),+ );+ await waitFor(() => expect(directMessages).toHaveTextContent('Never'));+ await waitFor(() => expect(directMessages).toHaveFocus());+ expect(args.onDirectMessageModeChange).toHaveBeenLastCalledWith('NEVER');+ expect(args.onInboxModeChange).not.toHaveBeenCalled();+ expect(inbox).toHaveTextContent('Auto');++ await userEvent.click(inbox);+ const inboxOptions = await bodyQueries.findByRole('listbox', {+ name: 'Global inbox',+ });++ await waitFor(() =>+ expect(+ within(inboxOptions).getByRole('option', { name: 'Auto' }),+ ).toHaveFocus(),+ );+ await userEvent.keyboard('{Home}{ArrowDown}{Enter}');+ await waitFor(() => expect(inbox).toHaveTextContent('Only when mentioned'));+ expect(args.onInboxModeChange).toHaveBeenCalledOnce();+ expect(args.onInboxModeChange).toHaveBeenLastCalledWith('MENTION_ONLY');+ expect(directMessages).toHaveTextContent('Never');+ await waitFor(() => expect(inbox).toHaveFocus());++ await userEvent.click(directMessages);+ await bodyQueries.findByRole('listbox');+ await userEvent.keyboard('{ArrowDown}{Escape}');+ await waitFor(() => expect(directMessages).toHaveFocus());+ expect(args.onDirectMessageModeChange).toHaveBeenCalledOnce();+ expect(directMessages).toHaveTextContent('Never');++ await userEvent.keyboard('a');+ expect(args.onDirectMessageModeChange).toHaveBeenCalledOnce();+ expect(directMessages).toHaveTextContent('Never');+ },+};++export const Disabled: Story = {+ args: { disabled: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ for (const name of ['DMs', 'Global inbox']) {+ const trigger = canvas.getByRole('combobox', { name });++ expect(trigger).toHaveAttribute('data-disabled');+ await userEvent.click(trigger);+ }++ expect(+ within(canvasElement.ownerDocument.body).queryByRole('listbox'),+ ).not.toBeInTheDocument();+ },+};++export const Loading: Story = {+ args: { isLoading: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ expect(canvas.getByRole('status')).toHaveTextContent(+ 'Loading behavior settings...',+ );++ for (const trigger of canvas.getAllByRole('combobox')) {+ expect(trigger).toHaveAttribute('data-disabled');+ expect(trigger).toHaveTextContent('Loading...');+ }+ },+};++export const FailedChange: Story = {+ args: {+ errorMessage: 'Unable to save behavior settings. Try again.',+ shouldRejectChanges: true,+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const directMessages = canvas.getByRole('combobox', { name: 'DMs' });+ const inbox = canvas.getByRole('combobox', { name: 'Global inbox' });++ expect(canvas.getByRole('alert')).toHaveTextContent(+ 'Unable to save behavior settings. Try again.',+ );+ expect(directMessages).toHaveAccessibleDescription(+ expect.stringContaining('Unable to save behavior settings. Try again.'),+ );+ await userEvent.click(directMessages);+ const options = await within(canvasElement.ownerDocument.body).findByRole(+ 'listbox',+ );++ await userEvent.click(+ within(options).getByRole('option', { name: 'Never' }),+ );+ expect(args.onDirectMessageModeChange).toHaveBeenCalledOnce();+ expect(args.onDirectMessageModeChange).toHaveBeenLastCalledWith('NEVER');+ await waitFor(() =>+ expect(directMessages).toHaveTextContent('Only when mentioned'),+ );+ expect(inbox).toHaveTextContent('Auto');+ expect(args.onInboxModeChange).not.toHaveBeenCalled();+ },+};++export const Narrow: Story = {+ parameters: { container: { width: 320 } },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const directMessages = canvas.getByRole('combobox', { name: 'DMs' });+ const inbox = canvas.getByRole('combobox', { name: 'Global inbox' });++ expect(directMessages).toBeVisible();+ expect(inbox).toBeVisible();+ await userEvent.click(directMessages);+ const options = await within(canvasElement.ownerDocument.body).findByRole(+ 'listbox',+ );++ await userEvent.click(+ within(options).getByRole('option', { name: 'Never' }),+ );+ await waitFor(() => expect(directMessages).toHaveTextContent('Never'));+ expect(args.onDirectMessageModeChange).toHaveBeenCalledOnce();+ expect(args.onDirectMessageModeChange).toHaveBeenLastCalledWith('NEVER');+ expect(args.onInboxModeChange).not.toHaveBeenCalled();+ await waitFor(() => expect(directMessages).toHaveFocus());+ await userEvent.tab();+ expect(inbox).toHaveFocus();+ expect(inbox).toHaveTextContent('Auto');+ },+};++export const RefreshedSettings: Story = {+ render: function Render(args) {+ const [hasRefreshedSettings, setHasRefreshedSettings] = useState(false);++ return (+ <>+ <SettingsAiBehaviorExample+ directMessageMode={+ hasRefreshedSettings ? args.inboxMode : args.directMessageMode+ }+ inboxMode={+ hasRefreshedSettings ? args.directMessageMode : args.inboxMode+ }+ onDirectMessageModeChange={args.onDirectMessageModeChange}+ onInboxModeChange={args.onInboxModeChange}+ isLoading={args.isLoading}+ disabled={args.disabled}+ errorMessage={args.errorMessage}+ shouldRejectChanges={args.shouldRejectChanges}+ />+ <Button onClick={() => setHasRefreshedSettings(true)}>+ Refresh saved settings+ </Button>+ </>+ );+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const directMessages = canvas.getByRole('combobox', { name: 'DMs' });+ const inbox = canvas.getByRole('combobox', { name: 'Global inbox' });++ await userEvent.click(directMessages);+ const options = await within(canvasElement.ownerDocument.body).findByRole(+ 'listbox',+ );+ await userEvent.click(+ within(options).getByRole('option', { name: 'Never' }),+ );+ await waitFor(() => expect(directMessages).toHaveTextContent('Never'));++ await userEvent.click(+ canvas.getByRole('button', { name: 'Refresh saved settings' }),+ );+ await waitFor(() => expect(directMessages).toHaveTextContent('Auto'));+ expect(inbox).toHaveTextContent('Only when mentioned');+ expect(args.onDirectMessageModeChange).toHaveBeenCalledOnce();+ expect(args.onInboxModeChange).not.toHaveBeenCalled();+ },+};diff --git a/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiBehaviorExample.tsx b/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiBehaviorExample.tsxnew file mode 100644index 00000000000..ec0d659a878--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiBehaviorExample.tsx@@ -0,0 +1,56 @@+import { SettingsAiBehaviorExampleSyncEffect } from '~/pages/settings/ai/components/__stories__/SettingsAiBehaviorExampleSyncEffect';+import { type ComponentProps, useState } from 'react';+import { SettingsAiBehaviorSection } from '~/pages/settings/ai/components/SettingsAiBehaviorSection';++type SettingsAiBehaviorExampleProps = ComponentProps<+ typeof SettingsAiBehaviorSection+> & {+ shouldRejectChanges?: boolean;+};++export const SettingsAiBehaviorExample = ({+ directMessageMode,+ inboxMode,+ onDirectMessageModeChange,+ onInboxModeChange,+ isLoading,+ disabled,+ errorMessage,+ shouldRejectChanges = false,+}: SettingsAiBehaviorExampleProps) => {+ const [currentDirectMessageMode, setDirectMessageMode] =+ useState(directMessageMode);+ const [currentInboxMode, setInboxMode] = useState(inboxMode);++ return (+ <>+ <SettingsAiBehaviorExampleSyncEffect+ directMessageMode={directMessageMode}+ inboxMode={inboxMode}+ setDirectMessageMode={setDirectMessageMode}+ setInboxMode={setInboxMode}+ />+ <SettingsAiBehaviorSection+ directMessageMode={currentDirectMessageMode}+ inboxMode={currentInboxMode}+ onDirectMessageModeChange={(value) => {+ onDirectMessageModeChange(value);++ if (!shouldRejectChanges) {+ setDirectMessageMode(value);+ }+ }}+ onInboxModeChange={(value) => {+ onInboxModeChange(value);++ if (!shouldRejectChanges) {+ setInboxMode(value);+ }+ }}+ isLoading={isLoading}+ disabled={disabled}+ errorMessage={errorMessage}+ />+ </>+ );+};diff --git a/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiBehaviorExampleSyncEffect.tsx b/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiBehaviorExampleSyncEffect.tsxnew file mode 100644index 00000000000..057fe31c887--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiBehaviorExampleSyncEffect.tsx@@ -0,0 +1,35 @@+import {+ type ComponentProps,+ type Dispatch,+ type SetStateAction,+ useEffect,+} from 'react';+import { type SettingsAiBehaviorSection } from '~/pages/settings/ai/components/SettingsAiBehaviorSection';++type SettingsAiBehaviorMode = ComponentProps<+ typeof SettingsAiBehaviorSection+>['directMessageMode'];++type SettingsAiBehaviorExampleSyncEffectProps = {+ directMessageMode: SettingsAiBehaviorMode;+ inboxMode: SettingsAiBehaviorMode;+ setDirectMessageMode: Dispatch<SetStateAction<SettingsAiBehaviorMode>>;+ setInboxMode: Dispatch<SetStateAction<SettingsAiBehaviorMode>>;+};++export const SettingsAiBehaviorExampleSyncEffect = ({+ directMessageMode,+ inboxMode,+ setDirectMessageMode,+ setInboxMode,+}: SettingsAiBehaviorExampleSyncEffectProps) => {+ useEffect(() => {+ setDirectMessageMode(directMessageMode);+ }, [directMessageMode, setDirectMessageMode]);++ useEffect(() => {+ setInboxMode(inboxMode);+ }, [inboxMode, setInboxMode]);++ return null;+};diff --git a/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiOverview.stories.tsx b/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiOverview.stories.tsxindex 3ce1a60d9ea..c630b105c28 100644--- a/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiOverview.stories.tsx+++ b/packages/twenty-front/src/pages/settings/ai/components/__stories__/SettingsAiOverview.stories.tsx@@ -1,10 +1,11 @@import { type Meta, type StoryObj } from '@storybook/react-vite';-import { expect, userEvent, within } from 'storybook/test';+import { expect, fn, userEvent, within } from 'storybook/test';import { SettingsPath } from 'twenty-shared/types';import { getSettingsPath } from 'twenty-shared/utils';import { Section } from 'twenty-ui/components/layout';import { Text } from 'twenty-ui/primitives/typography';import { SettingsAiOverview } from '~/pages/settings/ai/components/SettingsAiOverview';+import { SettingsAiBehaviorExample } from '~/pages/settings/ai/components/__stories__/SettingsAiBehaviorExample';import { settingsAiOverviewStoryParameters } from '~/pages/settings/ai/components/__stories__/settingsAiOverviewStoryParameters';import { settingsAiOverviewStorySections } from '~/pages/settings/ai/components/__stories__/settingsAiOverviewStorySections';import { type SettingsAiOverviewProps } from '~/pages/settings/ai/types/SettingsAiOverviewProps';@@ -64,9 +65,12 @@ export const WithSections: Story = {</Section.Root>),behaviorSection: (- <Section.Root>- <Section.Header title="Behavior" />- </Section.Root>+ <SettingsAiBehaviorExample+ directMessageMode="MENTION_ONLY"+ inboxMode="AUTOMATIC"+ onDirectMessageModeChange={fn()}+ onInboxModeChange={fn()}+ />),summarySection: (<Section.Root>@@ -87,6 +91,12 @@ export const WithSections: Story = {'Workspace Instructions','System Prompt',]);+ expect(canvas.getByRole('combobox', { name: 'DMs' })).toHaveTextContent(+ 'Only when mentioned',+ );+ expect(+ canvas.getByRole('combobox', { name: 'Global inbox' }),+ ).toHaveTextContent('Auto');expect(canvas.getByText('Overview navigation')).toBeInTheDocument();},};diff --git a/packages/twenty-front/src/pages/settings/ai/types/SettingsAiAssistantMode.ts b/packages/twenty-front/src/pages/settings/ai/types/SettingsAiAssistantMode.tsnew file mode 100644index 00000000000..9383ba16398--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/types/SettingsAiAssistantMode.ts@@ -0,0 +1 @@+export type SettingsAiAssistantMode = 'NEVER' | 'MENTION_ONLY' | 'AUTOMATIC';