Skip to content

The open alternative to Salesforce, designed for AI.

Add files, records and skills from the AI chat + menu (#26797)

Thomas des Francs996d3d594b07
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAddMenu.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAddMenu.tsx
new file mode 100644
index 00000000000..5b91885c49b
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatAddMenu.tsx
@@ -0,0 +1,99 @@
+import { useLingui } from '@lingui/react/macro';
+import { type Editor } from '@tiptap/react';
+import { useId, useRef } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { Dropdown, IconButton } from 'twenty-ui/components';
+import {
+ IconAddressBook,
+ IconBook,
+ IconPaperclip,
+ IconPlus,
+} from 'twenty-ui/icon';
+
+import { AiChatAddMenuRecordsPage } from '@/ai/components/AiChatAddMenuRecordsPage';
+import { AiChatAddMenuSkillsPage } from '@/ai/components/AiChatAddMenuSkillsPage';
+import { AgentChatFileInput } from '@/ai/components/internal/AgentChatFileInput';
+import { AI_CHAT_ADD_MENU_PAGE } from '@/ai/constants/AiChatAddMenuPage';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
+
+const AI_CHAT_ADD_MENU_WIDTH_PX = 280;
+
+type AiChatAddMenuProps = {
+ editor: Editor | null;
+};
+
+export const AiChatAddMenu = ({ editor }: AiChatAddMenuProps) => {
+ const { t } = useLingui();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const instanceId = useId();
+
+ return (
+ <>
+ <AgentChatFileInput ref={fileInputRef} />
+ <DropdownRoot
+ dropdownId={`ai-chat-add-menu-${instanceId}`}
+ type="menu"
+ defaultPage={AI_CHAT_ADD_MENU_PAGE.ROOT}
+ >
+ <Dropdown.Trigger
+ render={
+ <IconButton
+ variant="ghost"
+ size="sm"
+ aria-label={t`Add files, records or skills`}
+ >
+ <IconPlus />
+ </IconButton>
+ }
+ />
+ <DropdownContent
+ width={AI_CHAT_ADD_MENU_WIDTH_PX}
+ side="top"
+ align="start"
+ sideOffset={8}
+ finalFocus={(interaction) =>
+ interaction === 'keyboard' && isDefined(editor)
+ ? editor.view.dom
+ : false
+ }
+ aria-label={t`Add files, records or skills`}
+ >
+ <Dropdown.Page id={AI_CHAT_ADD_MENU_PAGE.ROOT} type="menu">
+ <Dropdown.Section>
+ <Dropdown.ActionItem
+ startIcon={<IconPaperclip />}
+ onClick={() => {
+ editor?.view.focus();
+ fileInputRef.current?.click();
+ }}
+ >
+ {t`Attach files`}
+ </Dropdown.ActionItem>
+ <Dropdown.ActionItem
+ startIcon={<IconAddressBook />}
+ hotkeys={['@']}
+ page={AI_CHAT_ADD_MENU_PAGE.RECORDS}
+ >
+ {t`Records`}
+ </Dropdown.ActionItem>
+ <Dropdown.ActionItem
+ startIcon={<IconBook />}
+ hotkeys={['/']}
+ page={AI_CHAT_ADD_MENU_PAGE.SKILLS}
+ >
+ {t`Skills`}
+ </Dropdown.ActionItem>
+ </Dropdown.Section>
+ </Dropdown.Page>
+ <Dropdown.Page id={AI_CHAT_ADD_MENU_PAGE.RECORDS} type="picker">
+ <AiChatAddMenuRecordsPage editor={editor} />
+ </Dropdown.Page>
+ <Dropdown.Page id={AI_CHAT_ADD_MENU_PAGE.SKILLS} type="picker">
+ <AiChatAddMenuSkillsPage editor={editor} />
+ </Dropdown.Page>
+ </DropdownContent>
+ </DropdownRoot>
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAddMenuRecordsPage.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAddMenuRecordsPage.tsx
new file mode 100644
index 00000000000..642983f1dcb
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatAddMenuRecordsPage.tsx
@@ -0,0 +1,98 @@
+import { useLingui } from '@lingui/react/macro';
+import { type Editor } from '@tiptap/react';
+import { useState } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { Dropdown } from 'twenty-ui/components';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+import { useDebounce } from 'use-debounce';
+
+import { useMentionSearch } from '@/mention/hooks/useMentionSearch';
+import { getMentionTagContent } from '@/mention/utils/getMentionTagContent';
+import { getAvatarShape } from '@/object-metadata/utils/getAvatarShape';
+import { useObjectRecordSearchRecords } from '@/object-record/hooks/useObjectRecordSearchRecords';
+import { type SearchRecord } from '~/generated/graphql';
+import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';
+
+type AiChatAddMenuRecordsPageProps = {
+ editor: Editor | null;
+};
+
+export const AiChatAddMenuRecordsPage = ({
+ editor,
+}: AiChatAddMenuRecordsPageProps) => {
+ const { t } = useLingui();
+ const [search, setSearch] = useState('');
+ const trimmedSearch = search.trim();
+ const [debouncedSearch] = useDebounce(trimmedSearch, 300);
+ const { searchableObjectMetadataItems } = useMentionSearch();
+ const searchableObjectMetadataItemByNameSingular = new Map(
+ searchableObjectMetadataItems.map((objectMetadataItem) => [
+ objectMetadataItem.nameSingular,
+ objectMetadataItem,
+ ]),
+ );
+
+ const { searchRecords, loading } = useObjectRecordSearchRecords({
+ objectNameSingulars: searchableObjectMetadataItems.map(
+ ({ nameSingular }) => nameSingular,
+ ),
+ searchInput: debouncedSearch,
+ skip: searchableObjectMetadataItems.length === 0,
+ });
+ const areSearchRecordsStale = loading || debouncedSearch !== trimmedSearch;
+
+ const handleRecordSelect = (record: SearchRecord) => {
+ if (!isDefined(editor)) {
+ return;
+ }
+
+ editor.commands.insertContent(getMentionTagContent(record));
+ editor.view.focus();
+ };
+
+ return (
+ <>
+ <Dropdown.Back>{t`Records`}</Dropdown.Back>
+ <Dropdown.Search
+ aria-label={t`Search records`}
+ placeholder={t`Search records`}
+ value={search}
+ onValueChange={setSearch}
+ />
+ <Dropdown.Separator />
+ <Dropdown.Section scrollable>
+ {searchRecords.map((record) => (
+ <Dropdown.OptionItem
+ key={`${record.objectNameSingular}-${record.recordId}`}
+ selected={false}
+ indicator="none"
+ disabled={areSearchRecordsStale}
+ startIcon={
+ <Avatar
+ name={record.label}
+ colorSeed={record.recordId}
+ src={getAbsoluteImageUrl(record.imageUrl)}
+ shape={getAvatarShape(
+ searchableObjectMetadataItemByNameSingular.get(
+ record.objectNameSingular,
+ ),
+ )}
+ size="sm"
+ />
+ }
+ description={record.objectLabelSingular}
+ onSelect={() => handleRecordSelect(record)}
+ >
+ {record.label}
+ </Dropdown.OptionItem>
+ ))}
+ {searchRecords.length === 0 &&
+ (loading ? (
+ <Dropdown.Loading>{t`Loading records`}</Dropdown.Loading>
+ ) : (
+ <Dropdown.Empty>{t`No records found`}</Dropdown.Empty>
+ ))}
+ </Dropdown.Section>
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAddMenuSkillsPage.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAddMenuSkillsPage.tsx
new file mode 100644
index 00000000000..32761aa60e4
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatAddMenuSkillsPage.tsx
@@ -0,0 +1,138 @@
+import { useQuery } from '@apollo/client/react';
+import { useLingui } from '@lingui/react/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import { type Editor } from '@tiptap/react';
+import { useId, useState } from 'react';
+import { SettingsPath } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { Dropdown } from 'twenty-ui/components';
+import { IconPlus, useIcons } from 'twenty-ui/icon';
+import { useIsMobile } from 'twenty-ui/utilities';
+
+import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';
+import { SkillSuggestionPreviewCard } from '@/skill-suggestion/components/SkillSuggestionPreviewCard';
+import { DEFAULT_SKILL_ICON } from '@/skill-suggestion/constants/DefaultSkillIcon';
+import { SKILL_SUGGESTION_PREVIEW_WIDTH } from '@/skill-suggestion/constants/SkillSuggestionPreviewWidth';
+import { type SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+import { getSkillSuggestionItems } from '@/skill-suggestion/utils/getSkillSuggestionItems';
+import { getSkillTagContent } from '@/skill-suggestion/utils/getSkillTagContent';
+import { SuggestionItemPreviewTooltip } from '@/ui/suggestion/components/SuggestionItemPreviewTooltip';
+import {
+ FindManySkillsForSuggestionDocument,
+ PermissionFlagType,
+} from '~/generated-metadata/graphql';
+import { useNavigateSettings } from '~/hooks/useNavigateSettings';
+
+type AiChatAddMenuSkillsPageProps = {
+ editor: Editor | null;
+};
+
+export const AiChatAddMenuSkillsPage = ({
+ editor,
+}: AiChatAddMenuSkillsPageProps) => {
+ const { t } = useLingui();
+ const { getIcon } = useIcons();
+ const isMobile = useIsMobile();
+ const navigateSettings = useNavigateSettings();
+ const hasAiSettingsPermission = useHasPermissionFlag(
+ PermissionFlagType.AI_SETTINGS,
+ );
+ const [search, setSearch] = useState('');
+ const [hoveredSkillId, setHoveredSkillId] = useState<string | null>(null);
+ const [focusedSkillId, setFocusedSkillId] = useState<string | null>(null);
+ const skillRowIdPrefix = useId();
+ const getSkillRowId = (skillId: string) => `${skillRowIdPrefix}-${skillId}`;
+
+ const { data, loading } = useQuery(FindManySkillsForSuggestionDocument, {
+ fetchPolicy: 'cache-and-network',
+ });
+
+ const skills = getSkillSuggestionItems({
+ skills: data?.skills ?? [],
+ query: search,
+ });
+
+ const searchTargetSkillId =
+ isNonEmptyString(search.trim()) && !loading ? skills[0]?.id : undefined;
+
+ const previewedSkill = [hoveredSkillId, focusedSkillId, searchTargetSkillId]
+ .map((skillId) => skills.find((skill) => skill.id === skillId))
+ .find(isDefined);
+
+ const handleSkillSelect = (skill: SkillSuggestionItem) => {
+ if (!isDefined(editor)) {
+ return;
+ }
+
+ editor.commands.insertContent(getSkillTagContent(skill));
+ editor.view.focus();
+ };
+
+ return (
+ <>
+ <Dropdown.Back>{t`Skills`}</Dropdown.Back>
+ <Dropdown.Search
+ aria-label={t`Search skills`}
+ placeholder={t`Search skills`}
+ value={search}
+ onValueChange={setSearch}
+ />
+ <Dropdown.Separator />
+ <Dropdown.Section
+ scrollable
+ onPointerLeave={() => setHoveredSkillId(null)}
+ >
+ {skills.map((skill) => {
+ const SkillIcon = getIcon(skill.icon ?? DEFAULT_SKILL_ICON);
+
+ return (
+ <Dropdown.OptionItem
+ key={skill.id}
+ id={getSkillRowId(skill.id)}
+ selected={false}
+ indicator="none"
+ disabled={loading}
+ startIcon={<SkillIcon />}
+ onPointerEnter={() => setHoveredSkillId(skill.id)}
+ onFocus={() => setFocusedSkillId(skill.id)}
+ onBlur={() => setFocusedSkillId(null)}
+ onSelect={() => handleSkillSelect(skill)}
+ >
+ {skill.label}
+ </Dropdown.OptionItem>
+ );
+ })}
+ {skills.length === 0 &&
+ (loading ? (
+ <Dropdown.Loading>{t`Loading skills`}</Dropdown.Loading>
+ ) : (
+ <Dropdown.Empty>{t`No skills found`}</Dropdown.Empty>
+ ))}
+ </Dropdown.Section>
+ {hasAiSettingsPermission && (
+ <>
+ <Dropdown.Separator />
+ <Dropdown.Section>
+ <Dropdown.ActionItem
+ startIcon={<IconPlus />}
+ onClick={() => navigateSettings(SettingsPath.AiNewSkill)}
+ >
+ {t`New skill`}
+ </Dropdown.ActionItem>
+ </Dropdown.Section>
+ </>
+ )}
+ {!isMobile && isDefined(previewedSkill) && (
+ <SuggestionItemPreviewTooltip
+ key={previewedSkill.id}
+ anchor={() =>
+ document.getElementById(getSkillRowId(previewedSkill.id))
+ }
+ width={SKILL_SUGGESTION_PREVIEW_WIDTH}
+ >
+ <SkillSuggestionPreviewCard skill={previewedSkill} />
+ </SuggestionItemPreviewTooltip>
+ )}
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
index ac042d79622..cac4987dc0f 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
@@ -17,7 +17,7 @@ import { AIChatNoMoreBillingCreditsBanner } from '@/ai/components/AIChatNoMoreBi
import { AiChatUsageLimitReachedBanner } from '@/ai/components/AiChatUsageLimitReachedBanner';
import { AiChatStandaloneError } from '@/ai/components/AiChatStandaloneError';
import { AgentChatContextPreview } from '@/ai/components/internal/AgentChatContextPreview';
-import { AgentChatFileUploadButton } from '@/ai/components/internal/AgentChatFileUploadButton';
+import { AiChatAddMenu } from '@/ai/components/AiChatAddMenu';
import { AiChatDictationButton } from '@/ai/dictation/components/AiChatDictationButton';
import { AiChatDictationEffect } from '@/ai/dictation/components/AiChatDictationEffect';
import { AiChatDictationHint } from '@/ai/dictation/components/AiChatDictationHint';
@@ -196,7 +196,7 @@ const EditableAiChatEditorSection = () => {
<AiChatDictationHint interimText={dictationInterimText} />
<StyledButtonsContainer>
<StyledLeftButtonsContainer>
- <AgentChatFileUploadButton />
+ <AiChatAddMenu editor={editor} />
<AiChatDictationButton />
<AiChatContextUsageButton />
</StyledLeftButtonsContainer>
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatAddMenu.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatAddMenu.stories.tsx
new file mode 100644
index 00000000000..d7ae6a73d92
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatAddMenu.stories.tsx
@@ -0,0 +1,245 @@
+import { styled } from '@linaria/react';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { EditorContent } from '@tiptap/react';
+import { graphql, HttpResponse } from 'msw';
+import { expect, fireEvent, userEvent, waitFor, within } from 'storybook/test';
+import { isDefined } from 'twenty-shared/utils';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { useAdvancedTextEditor } from '@/advanced-text-editor/hooks/useAdvancedTextEditor';
+import { AiChatAddMenu } from '@/ai/components/AiChatAddMenu';
+import { AI_CHAT_EDITOR_PROFILE } from '@/ai/constants/AiChatEditorProfile';
+import { PermissionFlagType } from '~/generated-metadata/graphql';
+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';
+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';
+import { graphqlMocks } from '~/testing/graphqlMocks';
+import { mockedUserData } from '~/testing/mock-data/users';
+
+const StyledComposer = styled.div`
+ margin-top: 320px;
+ width: 400px;
+`;
+
+const AiChatAddMenuWithEditor = () => {
+ const editor = useAdvancedTextEditor({
+ profile: AI_CHAT_EDITOR_PROFILE,
+ placeholder: 'Ask anything',
+ readonly: false,
+ defaultValue: null,
+ onUpdate: () => {},
+ });
+
+ return (
+ <StyledComposer>
+ <EditorContent editor={editor} />
+ <AiChatAddMenu editor={editor} />
+ </StyledComposer>
+ );
+};
+
+const meta: Meta<typeof AiChatAddMenuWithEditor> = {
+ title: 'Modules/AI/AiChatAddMenu',
+ component: AiChatAddMenuWithEditor,
+ decorators: [
+ ComponentDecorator,
+ ObjectMetadataItemsDecorator,
+ ToastDecorator,
+ MemoryRouterDecorator,
+ ],
+ parameters: {
+ container: { height: 440 },
+ currentUserWorkspace: {
+ ...mockedUserData.currentUserWorkspace,
+ permissionFlags: [
+ ...(mockedUserData.currentUserWorkspace?.permissionFlags ?? []),
+ PermissionFlagType.AI_SETTINGS,
+ ],
+ },
+ msw: {
+ handlers: [
+ graphql.query('FindManySkillsForSuggestion', () =>
+ HttpResponse.json({
+ data: {
+ skills: [
+ {
+ __typename: 'Skill',
+ id: '20202020-5e21-4b07-9c3a-1d4f6e8a0b52',
+ name: 'meeting-prep',
+ label: 'Meeting Prep',
+ description: 'Builds a brief before your next meeting.',
+ icon: 'IconCalendarEvent',
+ isActive: true,
+ isSystem: false,
+ },
+ ],
+ },
+ }),
+ ),
+ ...graphqlMocks.handlers,
+ ],
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof AiChatAddMenuWithEditor>;
+
+const openAddMenu = async (canvasElement: HTMLElement) => {
+ await userEvent.click(
+ await within(canvasElement).findByRole('button', {
+ name: 'Add files, records or skills',
+ }),
+ );
+
+ return within(
+ await within(canvasElement.ownerDocument.body).findByRole('menu', {
+ name: 'Add files, records or skills',
+ }),
+ );
+};
+
+export const InsertRecord: Story = {
+ play: async ({ canvasElement }) => {
+ const menu = await openAddMenu(canvasElement);
+
+ await userEvent.click(menu.getByRole('menuitem', { name: /Records/ }));
+ await userEvent.click(
+ await menu.findByRole('button', { name: /Jeffery Griffin/ }),
+ );
+
+ const canvas = within(canvasElement);
+ await expect(await canvas.findByText('Jeffery Griffin')).toBeVisible();
+ await waitFor(() => expect(canvas.getByRole('textbox')).toHaveFocus());
+ },
+};
+
+export const IgnoreEnterOnOutdatedRecords: Story = {
+ play: async ({ canvasElement }) => {
+ const menu = await openAddMenu(canvasElement);
+
+ await userEvent.click(menu.getByRole('menuitem', { name: /Records/ }));
+ await menu.findByRole('button', { name: /Jeffery Griffin/ });
+
+ const searchbox = menu.getByRole('searchbox', { name: 'Search records' });
+ await userEvent.type(searchbox, 'ter{Enter}');
+
+ await expect(searchbox).toHaveFocus();
+ await expect(
+ within(within(canvasElement).getByRole('textbox')).queryByText(
+ 'Jeffery Griffin',
+ ),
+ ).not.toBeInTheDocument();
+ },
+};
+
+export const InsertSkill: Story = {
+ play: async ({ canvasElement }) => {
+ const menu = await openAddMenu(canvasElement);
+
+ await userEvent.click(menu.getByRole('menuitem', { name: /Skills/ }));
+ await expect(
+ await menu.findByRole('button', { name: 'New skill' }),
+ ).toBeInTheDocument();
+ await waitFor(() =>
+ expect(
+ menu.getByRole('button', { name: 'Meeting Prep' }),
+ ).not.toHaveAttribute('aria-disabled'),
+ );
+ await userEvent.type(
+ menu.getByRole('searchbox', { name: 'Search skills' }),
+ 'meet{Enter}',
+ );
+
+ const canvas = within(canvasElement);
+ await expect(await canvas.findByText('Meeting Prep')).toBeVisible();
+ await waitFor(() => expect(canvas.getByRole('textbox')).toHaveFocus());
+ },
+};
+
+export const PreviewSkill: Story = {
+ play: async ({ canvasElement }) => {
+ const menu = await openAddMenu(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(menu.getByRole('menuitem', { name: /Skills/ }));
+ const meetingPrep = await menu.findByRole('button', {
+ name: 'Meeting Prep',
+ });
+ await waitFor(() =>
+ expect(meetingPrep).not.toHaveAttribute('aria-disabled'),
+ );
+
+ await userEvent.hover(meetingPrep);
+ await expect(await body.findByRole('tooltip')).toHaveTextContent(
+ 'Builds a brief before your next meeting.',
+ );
+
+ await userEvent.unhover(meetingPrep);
+ await waitFor(() =>
+ expect(body.queryByRole('tooltip')).not.toBeInTheDocument(),
+ );
+
+ await userEvent.type(
+ menu.getByRole('searchbox', { name: 'Search skills' }),
+ 'meet',
+ );
+ await expect(await body.findByRole('tooltip')).toHaveTextContent(
+ '/meeting-prep',
+ );
+ },
+};
+
+const SCROLLABLE_SKILLS = Array.from({ length: 10 }, (_, index) => {
+ const skillNumber = String(index + 1).padStart(2, '0');
+
+ return {
+ __typename: 'Skill',
+ id: `20202020-0000-4000-8000-0000000000${skillNumber}`,
+ name: `skill-${skillNumber}`,
+ label: `Skill ${skillNumber}`,
+ description: `Runs skill ${skillNumber}.`,
+ icon: 'IconBook',
+ isActive: true,
+ isSystem: false,
+ };
+});
+
+export const HideScrolledOutSkillPreview: Story = {
+ parameters: {
+ msw: {
+ handlers: [
+ graphql.query('FindManySkillsForSuggestion', () =>
+ HttpResponse.json({ data: { skills: SCROLLABLE_SKILLS } }),
+ ),
+ ...graphqlMocks.handlers,
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const menu = await openAddMenu(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(menu.getByRole('menuitem', { name: /Skills/ }));
+ const firstSkill = await menu.findByRole('button', { name: 'Skill 01' });
+ await waitFor(() =>
+ expect(firstSkill).not.toHaveAttribute('aria-disabled'),
+ );
+
+ await userEvent.type(
+ menu.getByRole('searchbox', { name: 'Search skills' }),
+ 'skill',
+ );
+ const preview = await body.findByRole('tooltip');
+ await expect(preview).toHaveTextContent('/skill-01');
+
+ const skillList = firstSkill.closest('[data-scrollable]');
+ if (isDefined(skillList)) {
+ fireEvent.scroll(skillList, {
+ target: { scrollTop: skillList.scrollHeight },
+ });
+ }
+
+ await waitFor(() => expect(preview).not.toBeVisible());
+ },
+};
diff --git a/packages/twenty-front/src/modules/ai/components/internal/AgentChatFileInput.tsx b/packages/twenty-front/src/modules/ai/components/internal/AgentChatFileInput.tsx
new file mode 100644
index 00000000000..b777682adef
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/internal/AgentChatFileInput.tsx
@@ -0,0 +1,42 @@
+import { useAiChatFileUpload } from '@/ai/hooks/useAiChatFileUpload';
+import { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';
+import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
+import { styled } from '@linaria/react';
+import { type ChangeEvent, type Ref } from 'react';
+
+const StyledFileInput = styled.input`
+ display: none;
+`;
+
+type AgentChatFileInputProps = {
+ ref: Ref<HTMLInputElement>;
+};
+
+export const AgentChatFileInput = ({ ref }: AgentChatFileInputProps) => {
+ const setAgentChatSelectedFiles = useSetAtomState(
+ agentChatSelectedFilesState,
+ );
+ const { uploadFiles } = useAiChatFileUpload();
+
+ const handleFileInputChange = (event: ChangeEvent<HTMLInputElement>) => {
+ if (!event.target.files) {
+ return;
+ }
+
+ const files = Array.from(event.target.files);
+
+ uploadFiles(files);
+ setAgentChatSelectedFiles(files);
+ event.target.value = '';
+ };
+
+ return (
+ <StyledFileInput
+ ref={ref}
+ type="file"
+ multiple
+ accept="*/*"
+ onChange={handleFileInputChange}
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/internal/AgentChatFileUploadButton.tsx b/packages/twenty-front/src/modules/ai/components/internal/AgentChatFileUploadButton.tsx
index 6018b168214..a2bdb5eb60d 100644
--- a/packages/twenty-front/src/modules/ai/components/internal/AgentChatFileUploadButton.tsx
+++ b/packages/twenty-front/src/modules/ai/components/internal/AgentChatFileUploadButton.tsx
@@ -1,9 +1,7 @@
-import { useAiChatFileUpload } from '@/ai/hooks/useAiChatFileUpload';
-import { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';
-import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
+import { AgentChatFileInput } from '@/ai/components/internal/AgentChatFileInput';
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
-import React, { useRef } from 'react';
+import { useRef } from 'react';
import { IconPaperclip } from 'twenty-ui/icon';
import { IconButton } from 'twenty-ui/components';
import { themeCssVariables } from 'twenty-ui/theme';
@@ -14,37 +12,12 @@ const StyledFileUploadContainer = styled.div`
gap: ${themeCssVariables.spacing[2]};
`;
-const StyledFileInput = styled.input`
- display: none;
-`;
-
export const AgentChatFileUploadButton = () => {
- const setAgentChatSelectedFiles = useSetAtomState(
- agentChatSelectedFilesState,
- );
const fileInputRef = useRef<HTMLInputElement>(null);
- const { uploadFiles } = useAiChatFileUpload();
-
- const handleFileInputChange = (
- event: React.ChangeEvent<HTMLInputElement>,
- ) => {
- if (!event.target.files) {
- return;
- }
-
- uploadFiles(Array.from(event.target.files));
- setAgentChatSelectedFiles(Array.from(event.target.files));
- };
return (
<StyledFileUploadContainer>
- <StyledFileInput
- ref={fileInputRef}
- type="file"
- multiple
- accept="*/*"
- onChange={handleFileInputChange}
- />
+ <AgentChatFileInput ref={fileInputRef} />
<IconButton
variant="ghost"
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatAddMenuPage.ts b/packages/twenty-front/src/modules/ai/constants/AiChatAddMenuPage.ts
new file mode 100644
index 00000000000..d783bf1d290
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatAddMenuPage.ts
@@ -0,0 +1,5 @@
+export const AI_CHAT_ADD_MENU_PAGE = {
+ ROOT: 'root',
+ RECORDS: 'records',
+ SKILLS: 'skills',
+} as const;
diff --git a/packages/twenty-front/src/modules/mention/extensions/MentionSuggestion.ts b/packages/twenty-front/src/modules/mention/extensions/MentionSuggestion.ts
index 376b919e158..ba674871430 100644
--- a/packages/twenty-front/src/modules/mention/extensions/MentionSuggestion.ts
+++ b/packages/twenty-front/src/modules/mention/extensions/MentionSuggestion.ts
@@ -4,6 +4,7 @@ import Suggestion from '@tiptap/suggestion';
import { MentionSuggestionMenu } from '@/mention/components/MentionSuggestionMenu';
import { MENTION_SUGGESTION_PLUGIN_KEY } from '@/mention/constants/MentionSuggestionPluginKey';
import type { MentionSearchResult } from '@/mention/types/MentionSearchResult';
+import { getMentionTagContent } from '@/mention/utils/getMentionTagContent';
import { createSuggestionRenderLifecycle } from '@/ui/suggestion/components/createSuggestionRenderLifecycle';
type MentionSuggestionOptions = {
@@ -41,16 +42,7 @@ export const MentionSuggestion = Extension.create<MentionSuggestionOptions>({
.chain()
.focus()
.deleteRange(range)
- .insertContent({
- type: 'mentionTag',
- attrs: {
- recordId: selectedItem.recordId,
- objectNameSingular: selectedItem.objectNameSingular,
- label: selectedItem.label,
- imageUrl: selectedItem.imageUrl,
- },
- })
- .insertContent(' ')
+ .insertContent(getMentionTagContent(selectedItem))
.run();
},
render: () =>
diff --git a/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionSuggestion.test.ts b/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionSuggestion.test.ts
index 25afe3fc8b9..0b3dcbeddcb 100644
--- a/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionSuggestion.test.ts
+++ b/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionSuggestion.test.ts
@@ -61,30 +61,6 @@ describe('MentionSuggestion', () => {
expect(hasSuggestionPlugin).toBe(true);
});
- it('should insert mention content via editor commands', () => {
- editor.commands.setContent('<p>Hello </p>');
- editor.commands.focus('end');
-
- editor
- .chain()
- .focus()
- .insertContent({
- type: 'mentionTag',
- attrs: {
- recordId: 'test-id',
- objectNameSingular: 'company',
- label: 'Acme',
- imageUrl: '',
- },
- })
- .insertContent(' ')
- .run();
-
- const text = editor.getText();
-
- expect(text).toContain('[[record:company:test-id:Acme]]');
- });
-
it('should accept @ character in editor content', () => {
editor.commands.setContent('<p></p>');
editor.commands.focus();
diff --git a/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionTag.test.ts b/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionTag.test.ts
index 6ab95dffbb3..eea702c983a 100644
--- a/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionTag.test.ts
+++ b/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionTag.test.ts
@@ -4,6 +4,7 @@ import { Paragraph } from '@tiptap/extension-paragraph';
import { Text } from '@tiptap/extension-text';
import { MentionTag } from '@/mention/extensions/MentionTag';
+import { getMentionTagContent } from '@/mention/utils/getMentionTagContent';
// Mock ReactNodeViewRenderer since we're testing in a non-DOM environment
jest.mock('@tiptap/react', () => ({
@@ -136,27 +137,17 @@ describe('MentionTag', () => {
});
describe('insertContent command', () => {
- it('should insert a mention tag via editor commands', () => {
- editor.commands.setContent('<p></p>');
- editor.commands.focus();
-
- editor
- .chain()
- .focus()
- .insertContent({
- type: 'mentionTag',
- attrs: {
- recordId: 'test-id',
- objectNameSingular: 'opportunity',
- label: 'Big Deal',
- imageUrl: 'https://example.com/img.png',
- },
- })
- .run();
-
- const text = editor.getText();
+ it('should insert a picked record as a reference followed by a space', () => {
+ editor.commands.insertContent(
+ getMentionTagContent({
+ recordId: 'test-id',
+ objectNameSingular: 'opportunity',
+ label: 'Big Deal',
+ imageUrl: null,
+ }),
+ );
- expect(text).toContain('[[record:opportunity:test-id:Big Deal]]');
+ expect(editor.getText()).toBe('[[record:opportunity:test-id:Big Deal]] ');
});
});
diff --git a/packages/twenty-front/src/modules/mention/utils/getMentionTagContent.ts b/packages/twenty-front/src/modules/mention/utils/getMentionTagContent.ts
new file mode 100644
index 00000000000..130a9197a0a
--- /dev/null
+++ b/packages/twenty-front/src/modules/mention/utils/getMentionTagContent.ts
@@ -0,0 +1,24 @@
+import type { JSONContent } from '@tiptap/react';
+
+import { type SearchRecord } from '~/generated/graphql';
+
+export const getMentionTagContent = ({
+ recordId,
+ objectNameSingular,
+ label,
+ imageUrl,
+}: Pick<
+ SearchRecord,
+ 'recordId' | 'objectNameSingular' | 'label' | 'imageUrl'
+>): JSONContent[] => [
+ {
+ type: 'mentionTag',
+ attrs: {
+ recordId,
+ objectNameSingular,
+ label,
+ imageUrl: imageUrl ?? '',
+ },
+ },
+ { type: 'text', text: ' ' },
+];
diff --git a/packages/twenty-front/src/modules/skill-suggestion/extensions/SkillSuggestion.ts b/packages/twenty-front/src/modules/skill-suggestion/extensions/SkillSuggestion.ts
index 1edacd28d09..86023839789 100644
--- a/packages/twenty-front/src/modules/skill-suggestion/extensions/SkillSuggestion.ts
+++ b/packages/twenty-front/src/modules/skill-suggestion/extensions/SkillSuggestion.ts
@@ -4,6 +4,7 @@ import Suggestion from '@tiptap/suggestion';
import { SkillSuggestionMenu } from '@/skill-suggestion/components/SkillSuggestionMenu';
import { SKILL_SUGGESTION_PLUGIN_KEY } from '@/skill-suggestion/constants/SkillSuggestionPluginKey';
import type { SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+import { getSkillTagContent } from '@/skill-suggestion/utils/getSkillTagContent';
import { createSuggestionRenderLifecycle } from '@/ui/suggestion/components/createSuggestionRenderLifecycle';
type SkillSuggestionOptions = {
@@ -41,16 +42,7 @@ export const SkillSuggestion = Extension.create<SkillSuggestionOptions>({
.chain()
.focus()
.deleteRange(range)
- .insertContent({
- type: 'skillTag',
- attrs: {
- skillId: selectedItem.id,
- name: selectedItem.name,
- label: selectedItem.label,
- icon: selectedItem.icon,
- },
- })
- .insertContent(' ')
+ .insertContent(getSkillTagContent(selectedItem))
.run();
},
render: () =>
diff --git a/packages/twenty-front/src/modules/skill-suggestion/extensions/__tests__/SkillTag.test.ts b/packages/twenty-front/src/modules/skill-suggestion/extensions/__tests__/SkillTag.test.ts
index e707c41fbcd..9c924fc3481 100644
--- a/packages/twenty-front/src/modules/skill-suggestion/extensions/__tests__/SkillTag.test.ts
+++ b/packages/twenty-front/src/modules/skill-suggestion/extensions/__tests__/SkillTag.test.ts
@@ -4,6 +4,7 @@ import { Paragraph } from '@tiptap/extension-paragraph';
import { Text } from '@tiptap/extension-text';
import { SkillTag } from '@/skill-suggestion/extensions/SkillTag';
+import { getSkillTagContent } from '@/skill-suggestion/utils/getSkillTagContent';
// Mock ReactNodeViewRenderer since we're testing in a non-DOM environment
jest.mock('@tiptap/react', () => ({
@@ -60,4 +61,17 @@ describe('SkillTag', () => {
'Use [[skill:skill-123:Workflow building]] now',
);
});
+
+ it('should insert a picked skill as a reference followed by a space', () => {
+ editor.commands.insertContent(
+ getSkillTagContent({
+ id: 'skill-123',
+ name: 'workflow-building',
+ label: 'Workflow building',
+ icon: null,
+ }),
+ );
+
+ expect(editor.getText()).toBe('[[skill:skill-123:Workflow building]] ');
+ });
});
diff --git a/packages/twenty-front/src/modules/skill-suggestion/hooks/__tests__/useSkillSuggestionSearch.test.tsx b/packages/twenty-front/src/modules/skill-suggestion/hooks/__tests__/useSkillSuggestionSearch.test.tsx
index ced9b6616dd..055b656e1f3 100644
--- a/packages/twenty-front/src/modules/skill-suggestion/hooks/__tests__/useSkillSuggestionSearch.test.tsx
+++ b/packages/twenty-front/src/modules/skill-suggestion/hooks/__tests__/useSkillSuggestionSearch.test.tsx
@@ -83,6 +83,14 @@ describe('useSkillSuggestionSearch', () => {
expect(skills.map((skill) => skill.name)).toEqual(['meeting-prep']);
});
+ it('ignores spaces around the query', async () => {
+ const { result } = renderUseSkillSuggestionSearch();
+
+ const skills = await result.current.searchSkills(' meeting ');
+
+ expect(skills.map((skill) => skill.name)).toEqual(['meeting-prep']);
+ });
+
it('never offers a system skill, even when the query names it', async () => {
const { result } = renderUseSkillSuggestionSearch();
diff --git a/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts b/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts
index be4b650c77a..745dce0de01 100644
--- a/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts
+++ b/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts
@@ -2,8 +2,8 @@ import { useApolloClient } from '@apollo/client/react';
import { useCallback } from 'react';
import type { SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+import { getSkillSuggestionItems } from '@/skill-suggestion/utils/getSkillSuggestionItems';
import { FindManySkillsForSuggestionDocument } from '~/generated-metadata/graphql';
-import { normalizeSearchText } from '~/utils/normalizeSearchText';
export const useSkillSuggestionSearch = () => {
const apolloMetadataClient = useApolloClient();
@@ -18,24 +18,7 @@ export const useSkillSuggestionSearch = () => {
fetchPolicy: query === '' ? 'network-only' : 'cache-first',
});
- const normalizedQuery = normalizeSearchText(query);
-
- return (data?.skills ?? [])
- .filter(
- (skill) =>
- skill.isActive &&
- !skill.isSystem &&
- (normalizeSearchText(skill.name).includes(normalizedQuery) ||
- normalizeSearchText(skill.label).includes(normalizedQuery)),
- )
- .sort((skillA, skillB) => skillA.label.localeCompare(skillB.label))
- .map((skill) => ({
- id: skill.id,
- name: skill.name,
- label: skill.label,
- description: skill.description ?? null,
- icon: skill.icon ?? null,
- }));
+ return getSkillSuggestionItems({ skills: data?.skills ?? [], query });
},
[apolloMetadataClient],
);
diff --git a/packages/twenty-front/src/modules/skill-suggestion/utils/getSkillSuggestionItems.ts b/packages/twenty-front/src/modules/skill-suggestion/utils/getSkillSuggestionItems.ts
new file mode 100644
index 00000000000..3cf6e3c4997
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/utils/getSkillSuggestionItems.ts
@@ -0,0 +1,30 @@
+import type { SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+import { type FindManySkillsForSuggestionQuery } from '~/generated-metadata/graphql';
+import { normalizeSearchText } from '~/utils/normalizeSearchText';
+
+export const getSkillSuggestionItems = ({
+ skills,
+ query,
+}: {
+ skills: FindManySkillsForSuggestionQuery['skills'];
+ query: string;
+}): SkillSuggestionItem[] => {
+ const normalizedQuery = normalizeSearchText(query.trim());
+
+ return skills
+ .filter(
+ (skill) =>
+ skill.isActive &&
+ !skill.isSystem &&
+ (normalizeSearchText(skill.name).includes(normalizedQuery) ||
+ normalizeSearchText(skill.label).includes(normalizedQuery)),
+ )
+ .sort((skillA, skillB) => skillA.label.localeCompare(skillB.label))
+ .map((skill) => ({
+ id: skill.id,
+ name: skill.name,
+ label: skill.label,
+ description: skill.description ?? null,
+ icon: skill.icon ?? null,
+ }));
+};
diff --git a/packages/twenty-front/src/modules/skill-suggestion/utils/getSkillTagContent.ts b/packages/twenty-front/src/modules/skill-suggestion/utils/getSkillTagContent.ts
new file mode 100644
index 00000000000..96ec01b14fc
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/utils/getSkillTagContent.ts
@@ -0,0 +1,24 @@
+import type { JSONContent } from '@tiptap/react';
+
+import type { SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+
+export const getSkillTagContent = ({
+ id,
+ name,
+ label,
+ icon,
+}: Pick<
+ SkillSuggestionItem,
+ 'id' | 'name' | 'label' | 'icon'
+>): JSONContent[] => [
+ {
+ type: 'skillTag',
+ attrs: {
+ skillId: id,
+ name,
+ label,
+ icon,
+ },
+ },
+ { type: 'text', text: ' ' },
+];
diff --git a/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionItemPreviewTooltip.tsx b/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionItemPreviewTooltip.tsx
new file mode 100644
index 00000000000..0231be77719
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionItemPreviewTooltip.tsx
@@ -0,0 +1,40 @@
+import { css } from '@linaria/core';
+import { type ReactNode } from 'react';
+import { Tooltip, type TooltipPopupProps } from 'twenty-ui/primitives/surfaces';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+const previewTooltipClass = css`
+ background: transparent !important;
+ border-radius: ${themeCssVariables.border.radius.md} !important;
+ box-shadow: ${themeCssVariables.boxShadow.strong} !important;
+ padding: 0 !important;
+
+ [data-anchor-hidden] & {
+ visibility: hidden;
+ }
+`;
+
+type SuggestionItemPreviewTooltipProps = {
+ anchor: TooltipPopupProps['anchor'];
+ width: number;
+ children: ReactNode;
+};
+
+export const SuggestionItemPreviewTooltip = ({
+ anchor,
+ width,
+ children,
+}: SuggestionItemPreviewTooltipProps) => (
+ <Tooltip.Root open>
+ <Tooltip.Popup
+ anchor={anchor}
+ side="right"
+ align="start"
+ sideOffset={16}
+ className={previewTooltipClass}
+ maxWidth={`${width}px`}
+ >
+ {children}
+ </Tooltip.Popup>
+ </Tooltip.Root>
+);
diff --git a/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx b/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx
index 04dab630b7e..76b85b11619 100644
--- a/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx
+++ b/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx
@@ -5,7 +5,6 @@ import {
shift,
useFloating,
} from '@floating-ui/react';
-import { css } from '@linaria/core';
import { motion } from 'framer-motion';
import {
forwardRef,
@@ -20,20 +19,10 @@ import { RootStackingContextZIndices } from '@/ui/layout/constants/RootStackingC
import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';
import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
import { OverlayContainer } from '@/ui/layout/overlay/components/OverlayContainer';
+import { SuggestionItemPreviewTooltip } from '@/ui/suggestion/components/SuggestionItemPreviewTooltip';
import type { SuggestionMenuProps } from '@/ui/suggestion/types/SuggestionMenuProps';
import { getSuggestionMenuItemAnchorId } from '@/ui/suggestion/utils/getSuggestionMenuItemAnchorId';
import { useIsMobile } from 'twenty-ui/utilities';
-import { Tooltip } from 'twenty-ui/primitives/surfaces';
-import { themeCssVariables } from 'twenty-ui/theme';
-
-// The preview card brings its own surface, so the tooltip only contributes
-// the shadow. Tooltips render at 0.9 opacity, which would make it translucent.
-const previewTooltipClass = css`
- background: transparent !important;
- border-radius: ${themeCssVariables.border.radius.md} !important;
- box-shadow: ${themeCssVariables.boxShadow.strong} !important;
- padding: 0 !important;
-`;
type SuggestionMenuInnerProps<TItem> = SuggestionMenuProps<TItem>;
@@ -236,18 +225,13 @@ const SuggestionMenuInner = <TItem,>(
</LegacyDropdownContent>
</OverlayContainer>
{shouldDisplayPreview && (
- <Tooltip.Root key={getItemKey(selectedItem)} open>
- <Tooltip.Popup
- anchor={activeItemRef}
- side="right"
- align="start"
- sideOffset={16}
- className={previewTooltipClass}
- maxWidth={`${selectedItemPreview.width}px`}
- >
- {selectedItemPreview.render(selectedItem)}
- </Tooltip.Popup>
- </Tooltip.Root>
+ <SuggestionItemPreviewTooltip
+ key={getItemKey(selectedItem)}
+ anchor={activeItemRef}
+ width={selectedItemPreview.width}
+ >
+ {selectedItemPreview.render(selectedItem)}
+ </SuggestionItemPreviewTooltip>
)}
</motion.div>
);