Skip to content

The open alternative to Salesforce, designed for AI.

Resolve AI chat references through one table instead of eight link components (#25260)

Félix Malfaitf44581a89d43
diff --git a/packages/twenty-front/src/modules/ai/components/ApplicationLink.tsx b/packages/twenty-front/src/modules/ai/components/ApplicationLink.tsx
deleted file mode 100644
index a7a4ff23370..00000000000
--- a/packages/twenty-front/src/modules/ai/components/ApplicationLink.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';
-import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';
-import { SettingsPath } from 'twenty-shared/types';
-import { getSettingsPath } from 'twenty-shared/utils';
-import { IconApps } from 'twenty-ui/icon';
-import { useTheme } from 'twenty-ui/theme-constants';
-import { PermissionFlagType } from '~/generated-metadata/graphql';
-
-type ApplicationLinkProps = {
- applicationId: string;
- displayName: string;
-};
-
-export const ApplicationLink = ({
- applicationId,
- displayName,
-}: ApplicationLinkProps) => {
- const theme = useTheme();
- const hasApplicationsPermission = useHasPermissionFlag(
- PermissionFlagType.APPLICATIONS,
- );
-
- return (
- <ChatReferenceChipDisplay
- displayName={displayName}
- to={
- hasApplicationsPermission
- ? getSettingsPath(SettingsPath.ApplicationDetail, { applicationId })
- : undefined
- }
- leftComponent={
- <IconApps size={theme.icon.size.sm} stroke={theme.icon.stroke.sm} />
- }
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx b/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx
index e479d21bf6c..2927bb1e96c 100644
--- a/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx
+++ b/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx
@@ -1,79 +1,44 @@
-import { ApplicationLink } from '@/ai/components/ApplicationLink';
-import { FieldMetadataLink } from '@/ai/components/FieldMetadataLink';
-import { DeprecatedFieldMetadataLinkById } from '@/ai/components/DeprecatedFieldMetadataLinkById';
-import { ObjectMetadataLink } from '@/ai/components/ObjectMetadataLink';
-import { RecordLink } from '@/ai/components/RecordLink';
-import { RecordsLink } from '@/ai/components/RecordsLink';
-import { RoleLink } from '@/ai/components/RoleLink';
-import { ViewLink } from '@/ai/components/ViewLink';
+import { t } from '@lingui/core/macro';
+import { useContext } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { Chip, ChipVariant, LinkChip } from 'twenty-ui/data-display';
+
+import { ChatReferenceNavigationEnabledContext } from '@/ai/contexts/ChatReferenceNavigationEnabledContext';
+import { useChatReferenceTarget } from '@/ai/hooks/useChatReferenceTarget';
import { type ChatReferenceMatch } from '@/ai/types/ChatReferenceMatch';
-import { assertUnreachable } from 'twenty-shared/utils';
type ChatReferenceChipProps = {
reference: ChatReferenceMatch;
};
export const ChatReferenceChip = ({ reference }: ChatReferenceChipProps) => {
- switch (reference.kind) {
- case 'record':
- return (
- <RecordLink
- objectNameSingular={reference.objectNameSingular}
- recordId={reference.recordId}
- displayName={reference.displayName}
- />
- );
- case 'records':
- return (
- <RecordsLink
- objectMetadataId={reference.objectMetadataId}
- displayName={reference.displayName}
- />
- );
- case 'object':
- return (
- <ObjectMetadataLink
- objectNameSingular={reference.objectNameSingular}
- displayName={reference.displayName}
- />
- );
- case 'field':
- return (
- <FieldMetadataLink
- objectNameSingular={reference.objectNameSingular}
- fieldName={reference.fieldName}
- displayName={reference.displayName}
- />
- );
- case 'legacyFieldById':
- return (
- <DeprecatedFieldMetadataLinkById
- fieldMetadataItemId={reference.fieldMetadataItemId}
- displayName={reference.displayName}
- />
- );
- case 'view':
- return (
- <ViewLink
- viewId={reference.viewId}
- displayName={reference.displayName}
- />
- );
- case 'role':
- return (
- <RoleLink
- roleId={reference.roleId}
- displayName={reference.displayName}
- />
- );
- case 'app':
- return (
- <ApplicationLink
- applicationId={reference.applicationId}
- displayName={reference.displayName}
- />
- );
- default:
- return assertUnreachable(reference);
+ const isNavigationEnabled = useContext(ChatReferenceNavigationEnabledContext);
+ const target = useChatReferenceTarget(reference);
+
+ if (!isDefined(target)) {
+ return <span>{reference.displayName}</span>;
}
+
+ if (!isDefined(target.to) || !isNavigationEnabled) {
+ return (
+ <Chip
+ label={reference.displayName}
+ emptyLabel={t`Untitled`}
+ variant={ChipVariant.Static}
+ leftComponent={target.leftComponent}
+ clickable={false}
+ />
+ );
+ }
+
+ return (
+ <LinkChip
+ label={reference.displayName}
+ emptyLabel={t`Untitled`}
+ to={target.to}
+ onClick={target.onClick}
+ variant={ChipVariant.Highlighted}
+ leftComponent={target.leftComponent}
+ />
+ );
};
diff --git a/packages/twenty-front/src/modules/ai/components/ChatReferenceChipDisplay.tsx b/packages/twenty-front/src/modules/ai/components/ChatReferenceChipDisplay.tsx
deleted file mode 100644
index 7f34d5355d3..00000000000
--- a/packages/twenty-front/src/modules/ai/components/ChatReferenceChipDisplay.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { t } from '@lingui/core/macro';
-import { type MouseEvent, type ReactNode, useContext } from 'react';
-import { isDefined } from 'twenty-shared/utils';
-import { Chip, ChipVariant, LinkChip } from 'twenty-ui/data-display';
-
-import { ChatReferenceNavigationEnabledContext } from '@/ai/contexts/ChatReferenceNavigationEnabledContext';
-
-type ChatReferenceChipDisplayProps = {
- displayName: string;
- leftComponent: ReactNode;
- to?: string;
- onClick?: (event: MouseEvent<HTMLElement>) => void;
-};
-
-export const ChatReferenceChipDisplay = ({
- displayName,
- leftComponent,
- to,
- onClick,
-}: ChatReferenceChipDisplayProps) => {
- const isNavigationEnabled = useContext(ChatReferenceNavigationEnabledContext);
-
- if (!isDefined(to) || !isNavigationEnabled) {
- return (
- <Chip
- label={displayName}
- emptyLabel={t`Untitled`}
- variant={ChipVariant.Static}
- leftComponent={leftComponent}
- clickable={false}
- />
- );
- }
-
- return (
- <LinkChip
- label={displayName}
- emptyLabel={t`Untitled`}
- to={to}
- onClick={onClick}
- variant={ChipVariant.Highlighted}
- leftComponent={leftComponent}
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/DeprecatedFieldMetadataLinkById.tsx b/packages/twenty-front/src/modules/ai/components/DeprecatedFieldMetadataLinkById.tsx
deleted file mode 100644
index 631e7605c8f..00000000000
--- a/packages/twenty-front/src/modules/ai/components/DeprecatedFieldMetadataLinkById.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { FieldMetadataChip } from '@/ai/components/FieldMetadataChip';
-import { fieldMetadataItemByIdSelector } from '@/object-metadata/states/fieldMetadataItemByIdSelector';
-import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
-import { isDefined } from 'twenty-shared/utils';
-
-type DeprecatedFieldMetadataLinkByIdProps = {
- fieldMetadataItemId: string;
- displayName: string;
-};
-
-/**
- * @deprecated Renders field references persisted with the old id-based syntax
- * (`[[field:<uuid>:<label>]]`). New messages address fields by object and field
- * name, handled by `FieldMetadataLink`.
- *
- * Kept only so already-persisted chat messages keep rendering.
- * Delete after 2026 september, along with the `legacyFieldById` reference kind.
- */
-export const DeprecatedFieldMetadataLinkById = ({
- fieldMetadataItemId,
- displayName,
-}: DeprecatedFieldMetadataLinkByIdProps) => {
- const { foundFieldMetadataItem, foundObjectMetadataItem } =
- useAtomFamilySelectorValue(fieldMetadataItemByIdSelector, {
- fieldMetadataItemId,
- });
-
- if (
- !isDefined(foundFieldMetadataItem) ||
- !isDefined(foundObjectMetadataItem)
- ) {
- return <span>{displayName}</span>;
- }
-
- return (
- <FieldMetadataChip
- displayName={displayName}
- objectMetadataItem={foundObjectMetadataItem}
- fieldMetadataItem={foundFieldMetadataItem}
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/FieldMetadataChip.tsx b/packages/twenty-front/src/modules/ai/components/FieldMetadataChip.tsx
deleted file mode 100644
index c846032b563..00000000000
--- a/packages/twenty-front/src/modules/ai/components/FieldMetadataChip.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';
-import { useChatReferenceTarget } from '@/ai/hooks/useChatReferenceTarget';
-import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
-import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem';
-import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';
-import { SettingsPath } from 'twenty-shared/types';
-import { getSettingsPath, isDefined } from 'twenty-shared/utils';
-import { useIcons } from 'twenty-ui/icon';
-import { useTheme } from 'twenty-ui/theme-constants';
-import { PermissionFlagType } from '~/generated-metadata/graphql';
-
-const PROPOSED_FIELD_METADATA_ICON = 'IconTag';
-
-type FieldMetadataChipProps = {
- displayName: string;
- objectMetadataItem?: EnrichedObjectMetadataItem | null;
- fieldMetadataItem?: FieldMetadataItem;
-};
-
-export const FieldMetadataChip = ({
- displayName,
- objectMetadataItem,
- fieldMetadataItem,
-}: FieldMetadataChipProps) => {
- const theme = useTheme();
- const { getIcon } = useIcons();
-
- const hasDataModelPermission = useHasPermissionFlag(
- PermissionFlagType.DATA_MODEL,
- );
-
- const Icon = getIcon(fieldMetadataItem?.icon ?? PROPOSED_FIELD_METADATA_ICON);
-
- const path =
- isDefined(objectMetadataItem) &&
- isDefined(fieldMetadataItem) &&
- hasDataModelPermission
- ? getSettingsPath(SettingsPath.ObjectFieldEdit, {
- objectNamePlural: objectMetadataItem.namePlural,
- fieldName: fieldMetadataItem.name,
- })
- : undefined;
-
- const target = useChatReferenceTarget(path);
-
- return (
- <ChatReferenceChipDisplay
- displayName={displayName}
- to={target.to}
- onClick={target.onClick}
- leftComponent={
- <Icon size={theme.icon.size.sm} stroke={theme.icon.stroke.sm} />
- }
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/FieldMetadataLink.tsx b/packages/twenty-front/src/modules/ai/components/FieldMetadataLink.tsx
deleted file mode 100644
index 3dc31a942e8..00000000000
--- a/packages/twenty-front/src/modules/ai/components/FieldMetadataLink.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { FieldMetadataChip } from '@/ai/components/FieldMetadataChip';
-import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
-import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
-
-type FieldMetadataLinkProps = {
- objectNameSingular: string;
- fieldName: string;
- displayName: string;
-};
-
-export const FieldMetadataLink = ({
- objectNameSingular,
- fieldName,
- displayName,
-}: FieldMetadataLinkProps) => {
- const objectMetadataItem = useAtomFamilySelectorValue(
- objectMetadataItemFamilySelector,
- {
- objectName: objectNameSingular,
- objectNameType: 'singular',
- },
- );
-
- const fieldMetadataItem = objectMetadataItem?.fields.find(
- (field) => field.name === fieldName,
- );
-
- return (
- <FieldMetadataChip
- displayName={displayName}
- objectMetadataItem={objectMetadataItem}
- fieldMetadataItem={fieldMetadataItem}
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/ObjectMetadataLink.tsx b/packages/twenty-front/src/modules/ai/components/ObjectMetadataLink.tsx
deleted file mode 100644
index 4f45fa5a6c4..00000000000
--- a/packages/twenty-front/src/modules/ai/components/ObjectMetadataLink.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';
-import { useChatReferenceTarget } from '@/ai/hooks/useChatReferenceTarget';
-import { ObjectMetadataIcon } from '@/object-metadata/components/ObjectMetadataIcon';
-import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
-import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';
-import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
-import { SettingsPath } from 'twenty-shared/types';
-import { getSettingsPath, isDefined } from 'twenty-shared/utils';
-import { useTheme } from 'twenty-ui/theme-constants';
-import { PermissionFlagType } from '~/generated-metadata/graphql';
-
-const PROPOSED_OBJECT_METADATA_ICON = 'IconListNumbers';
-
-type ObjectMetadataLinkProps = {
- objectNameSingular: string;
- displayName: string;
-};
-
-export const ObjectMetadataLink = ({
- objectNameSingular,
- displayName,
-}: ObjectMetadataLinkProps) => {
- const theme = useTheme();
- const hasDataModelPermission = useHasPermissionFlag(
- PermissionFlagType.DATA_MODEL,
- );
-
- const objectMetadataItem = useAtomFamilySelectorValue(
- objectMetadataItemFamilySelector,
- {
- objectName: objectNameSingular,
- objectNameType: 'singular',
- },
- );
-
- const path =
- isDefined(objectMetadataItem) && hasDataModelPermission
- ? getSettingsPath(SettingsPath.ObjectDetail, {
- objectNamePlural: objectMetadataItem.namePlural,
- })
- : undefined;
-
- const { to, onClick } = useChatReferenceTarget(path);
-
- return (
- <ChatReferenceChipDisplay
- displayName={displayName}
- to={to}
- onClick={onClick}
- leftComponent={
- <ObjectMetadataIcon
- objectMetadataItem={
- objectMetadataItem ?? {
- icon: PROPOSED_OBJECT_METADATA_ICON,
- nameSingular: objectNameSingular,
- color: null,
- isSystem: false,
- }
- }
- size={theme.icon.size.sm}
- stroke={theme.icon.stroke.sm}
- />
- }
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/RecordLink.tsx b/packages/twenty-front/src/modules/ai/components/RecordLink.tsx
deleted file mode 100644
index 12ae70e9bc3..00000000000
--- a/packages/twenty-front/src/modules/ai/components/RecordLink.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';
-import { useChatReferenceTarget } from '@/ai/hooks/useChatReferenceTarget';
-import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
-import { getLinkToShowPage } from '@/object-metadata/utils/getLinkToShowPage';
-import { useOpenRecordInSidePanel } from '@/side-panel/hooks/useOpenRecordInSidePanel';
-import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
-import { isNonEmptyString } from '@sniptt/guards';
-import { AvatarOrIcon } from 'twenty-ui/data-display';
-
-type RecordLinkProps = {
- objectNameSingular: string;
- recordId: string;
- displayName: string;
-};
-
-export const RecordLink = ({
- objectNameSingular,
- recordId,
- displayName,
-}: RecordLinkProps) => {
- const objectMetadataItem = useAtomFamilySelectorValue(
- objectMetadataItemFamilySelector,
- {
- objectName: objectNameSingular,
- objectNameType: 'singular',
- },
- );
- const { openRecordInSidePanel } = useOpenRecordInSidePanel();
-
- const recordPath =
- objectMetadataItem && isNonEmptyString(recordId)
- ? getLinkToShowPage(objectNameSingular, { id: recordId })
- : undefined;
- const path = isNonEmptyString(recordPath) ? recordPath : undefined;
-
- const { to, onClick } = useChatReferenceTarget(path, () => {
- openRecordInSidePanel({ recordId, objectNameSingular });
- });
-
- if (!objectMetadataItem || !isNonEmptyString(recordId)) {
- return <span>{displayName}</span>;
- }
-
- return (
- <ChatReferenceChipDisplay
- displayName={displayName}
- to={to}
- onClick={onClick}
- leftComponent={
- <AvatarOrIcon
- placeholder={displayName}
- placeholderColorSeed={recordId}
- avatarType="rounded"
- avatarUrl=""
- />
- }
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/RecordsLink.tsx b/packages/twenty-front/src/modules/ai/components/RecordsLink.tsx
deleted file mode 100644
index 28d6341d6c9..00000000000
--- a/packages/twenty-front/src/modules/ai/components/RecordsLink.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';
-import { useChatTargetNavigation } from '@/ai/hooks/useChatTargetNavigation';
-import { ObjectMetadataIcon } from '@/object-metadata/components/ObjectMetadataIcon';
-import { objectMetadataItemsByIdMapSelector } from '@/object-metadata/states/objectMetadataItemsByIdMapSelector';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { AppPath } from 'twenty-shared/types';
-import { getAppPath, isDefined } from 'twenty-shared/utils';
-import { useTheme } from 'twenty-ui/theme-constants';
-import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';
-
-type RecordsLinkProps = {
- objectMetadataId: string;
- displayName: string;
-};
-
-export const RecordsLink = ({
- objectMetadataId,
- displayName,
-}: RecordsLinkProps) => {
- const theme = useTheme();
- const { openViewTarget } = useChatTargetNavigation();
- const objectMetadataItemsByIdMap = useAtomStateValue(
- objectMetadataItemsByIdMapSelector,
- );
- const objectMetadataItem = objectMetadataItemsByIdMap.get(objectMetadataId);
-
- if (!isDefined(objectMetadataItem)) {
- return <span>{displayName}</span>;
- }
-
- const handleOpenViewTarget = () => {
- openViewTarget({
- objectNameSingular: objectMetadataItem.nameSingular,
- });
- };
-
- return (
- <ChatReferenceChipDisplay
- displayName={displayName}
- to={getAppPath(AppPath.RecordIndexPage, {
- objectNamePlural: objectMetadataItem.namePlural,
- })}
- onClick={isCurrentPathAiChatPage() ? handleOpenViewTarget : undefined}
- leftComponent={
- <ObjectMetadataIcon
- objectMetadataItem={objectMetadataItem}
- size={theme.icon.size.sm}
- stroke={theme.icon.stroke.sm}
- />
- }
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/RoleLink.tsx b/packages/twenty-front/src/modules/ai/components/RoleLink.tsx
deleted file mode 100644
index 1b0be0ae819..00000000000
--- a/packages/twenty-front/src/modules/ai/components/RoleLink.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';
-import { useChatReferenceTarget } from '@/ai/hooks/useChatReferenceTarget';
-import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';
-import { SettingsPath } from 'twenty-shared/types';
-import { getSettingsPath } from 'twenty-shared/utils';
-import { IconLock } from 'twenty-ui/icon';
-import { useTheme } from 'twenty-ui/theme-constants';
-import { PermissionFlagType } from '~/generated-metadata/graphql';
-
-type RoleLinkProps = {
- roleId: string;
- displayName: string;
-};
-
-export const RoleLink = ({ roleId, displayName }: RoleLinkProps) => {
- const theme = useTheme();
- const hasRolesPermission = useHasPermissionFlag(PermissionFlagType.ROLES);
- const path = hasRolesPermission
- ? getSettingsPath(SettingsPath.RoleDetail, { roleId })
- : undefined;
- const { to, onClick } = useChatReferenceTarget(path);
-
- return (
- <ChatReferenceChipDisplay
- displayName={displayName}
- to={to}
- onClick={onClick}
- leftComponent={
- <IconLock size={theme.icon.size.sm} stroke={theme.icon.stroke.sm} />
- }
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/ViewLink.tsx b/packages/twenty-front/src/modules/ai/components/ViewLink.tsx
deleted file mode 100644
index 705ad360773..00000000000
--- a/packages/twenty-front/src/modules/ai/components/ViewLink.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';
-import { useChatReferenceTarget } from '@/ai/hooks/useChatReferenceTarget';
-import { objectMetadataItemsByIdMapSelector } from '@/object-metadata/states/objectMetadataItemsByIdMapSelector';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { useViewById } from '@/views/hooks/useViewById';
-import { AppPath } from 'twenty-shared/types';
-import { getAppPath, isDefined } from 'twenty-shared/utils';
-import { useIcons } from 'twenty-ui/icon';
-import { useTheme } from 'twenty-ui/theme-constants';
-
-type ViewLinkProps = {
- viewId: string;
- displayName: string;
-};
-
-export const ViewLink = ({ viewId, displayName }: ViewLinkProps) => {
- const theme = useTheme();
- const { getIcon } = useIcons();
-
- const { view } = useViewById(viewId);
- const objectMetadataItemsByIdMap = useAtomStateValue(
- objectMetadataItemsByIdMapSelector,
- );
-
- const objectMetadataItem = isDefined(view)
- ? objectMetadataItemsByIdMap.get(view.objectMetadataId)
- : undefined;
-
- const path =
- isDefined(view) && isDefined(objectMetadataItem)
- ? getAppPath(
- AppPath.RecordIndexPage,
- { objectNamePlural: objectMetadataItem.namePlural },
- { viewId },
- )
- : undefined;
-
- const { to, onClick } = useChatReferenceTarget(path);
-
- if (!isDefined(view) || !isDefined(objectMetadataItem)) {
- return <span>{displayName}</span>;
- }
-
- const Icon = getIcon(view.icon);
-
- return (
- <ChatReferenceChipDisplay
- displayName={displayName}
- to={to}
- onClick={onClick}
- leftComponent={
- <Icon size={theme.icon.size.sm} stroke={theme.icon.stroke.sm} />
- }
- />
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/ChatReferenceChip.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/ChatReferenceChip.stories.tsx
deleted file mode 100644
index b09277b894a..00000000000
--- a/packages/twenty-front/src/modules/ai/components/__stories__/ChatReferenceChip.stories.tsx
+++ /dev/null
@@ -1,169 +0,0 @@
-import { type Meta, type StoryObj } from '@storybook/react-vite';
-import { expect, within } from 'storybook/test';
-
-import { LazyMarkdownRenderer } from '@/ai/components/LazyMarkdownRenderer';
-import { formatChatReference } from '@/ai/utils/formatChatReference';
-import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';
-import { styled } from '@linaria/react';
-import { useStore } from 'jotai';
-import { type ReactNode, useEffect, useState } from 'react';
-import { type ViewWithRelations } from '@/views/types/ViewWithRelations';
-import { PermissionFlagType } from '~/generated-metadata/graphql';
-import { ComponentWithRouterDecorator } from '~/testing/decorators/ComponentWithRouterDecorator';
-import { IconsProviderDecorator } from '~/testing/decorators/IconsProviderDecorator';
-import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
-import { getMockFieldMetadataItemOrThrow } from '~/testing/utils/getMockFieldMetadataItemOrThrow';
-import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
-import { setTestViewsInMetadataStore } from '~/testing/utils/setTestViewsInMetadataStore';
-
-const StyledContainer = styled.div`
- max-width: 640px;
-`;
-
-const companyObjectMetadataItem = getMockObjectMetadataItemOrThrow('company');
-
-const employeesFieldMetadataItem = getMockFieldMetadataItemOrThrow({
- objectMetadataItem: companyObjectMetadataItem,
- fieldName: 'employees',
-});
-
-const allCompaniesView = {
- id: '20202020-4444-4444-4444-444444444444',
- name: 'All Companies',
- icon: 'IconList',
- objectMetadataId: companyObjectMetadataItem.id,
- isActive: true,
-} as ViewWithRelations;
-
-// Declared locally because ObjectMetadataItemsDecorator drops every mocked view,
-// and importing the generated view mocks breaks the linaria build-time evaluator.
-const ChatReferenceStoreSeeder = ({ children }: { children: ReactNode }) => {
- const store = useStore();
- const [isSeeded, setIsSeeded] = useState(false);
-
- useEffect(() => {
- setTestViewsInMetadataStore(store, [allCompaniesView]);
-
- store.set(currentUserWorkspaceState.atom, {
- permissionFlags: [PermissionFlagType.DATA_MODEL],
- twoFactorAuthenticationMethodSummary: [],
- objectsPermissions: [],
- });
-
- setIsSeeded(true);
- }, [store]);
-
- return isSeeded ? <>{children}</> : null;
-};
-
-const meta: Meta<typeof LazyMarkdownRenderer> = {
- title: 'Modules/AiChat/ChatReferenceChip',
- component: LazyMarkdownRenderer,
- decorators: [
- (Story) => (
- <ChatReferenceStoreSeeder>
- <StyledContainer>
- <Story />
- </StyledContainer>
- </ChatReferenceStoreSeeder>
- ),
- ObjectMetadataItemsDecorator,
- IconsProviderDecorator,
- ComponentWithRouterDecorator,
- ],
-};
-
-export default meta;
-
-type Story = StoryObj<typeof LazyMarkdownRenderer>;
-
-export const ExistingMetadata: Story = {
- args: {
- text: `Your ${formatChatReference({
- kind: 'object',
- objectNameSingular: 'company',
- displayName: 'Companies',
- })} object is sorted by ${formatChatReference({
- kind: 'legacyFieldById',
- fieldMetadataItemId: employeesFieldMetadataItem.id,
- displayName: 'Employees',
- })} in the ${formatChatReference({
- kind: 'view',
- viewId: allCompaniesView.id,
- displayName: allCompaniesView.name,
- })} view.`,
- },
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement);
-
- expect((await canvas.findByText('Companies')).closest('a')).toHaveAttribute(
- 'href',
- `/settings/objects/${companyObjectMetadataItem.namePlural}`,
- );
- expect((await canvas.findByText('Employees')).closest('a')).toHaveAttribute(
- 'href',
- `/settings/objects/${companyObjectMetadataItem.namePlural}/${employeesFieldMetadataItem.name}`,
- );
- expect(
- (await canvas.findByText('All Companies')).closest('a'),
- ).toHaveAttribute(
- 'href',
- `/objects/${companyObjectMetadataItem.namePlural}?viewId=${allCompaniesView.id}`,
- );
- },
-};
-
-export const ProposedField: Story = {
- args: {
- text: `For pipeline reporting I suggest adding ${formatChatReference({
- kind: 'field',
- objectNameSingular: 'company',
- fieldName: 'annualContractValue',
- displayName: 'Annual contract value',
- })} to ${formatChatReference({
- kind: 'object',
- objectNameSingular: 'company',
- displayName: 'Companies',
- })}, alongside the ${formatChatReference({
- kind: 'field',
- objectNameSingular: 'company',
- fieldName: employeesFieldMetadataItem.name,
- displayName: 'Employees',
- })} field you already have.`,
- },
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement);
-
- const fieldByNameChipLabel = await canvas.findByText(
- 'Annual contract value',
- );
-
- expect(fieldByNameChipLabel).toBeVisible();
- expect(fieldByNameChipLabel.closest('a')).toBeNull();
-
- expect((await canvas.findByText('Employees')).closest('a')).toHaveAttribute(
- 'href',
- `/settings/objects/${companyObjectMetadataItem.namePlural}/${employeesFieldMetadataItem.name}`,
- );
- },
-};
-
-export const ProposedObject: Story = {
- args: {
- text: `As a Head of Partnerships, you seem to work across partner companies, key contacts, and commercial follow-ups, so I suggest creating a ${formatChatReference(
- {
- kind: 'object',
- objectNameSingular: 'partner',
- displayName: 'Partners',
- },
- )} object to track relationship status, partner type, owner, and next step. Should I create it?`,
- },
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement);
-
- const proposedObjectChipLabel = await canvas.findByText('Partners');
-
- expect(proposedObjectChipLabel).toBeVisible();
- expect(proposedObjectChipLabel.closest('a')).toBeNull();
- },
-};
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/ApplicationLink.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/ApplicationLink.test.tsx
deleted file mode 100644
index 25a6a843d17..00000000000
--- a/packages/twenty-front/src/modules/ai/components/__tests__/ApplicationLink.test.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { MemoryRouter } from 'react-router-dom';
-
-import { ApplicationLink } from '@/ai/components/ApplicationLink';
-import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';
-import { PermissionFlagType } from '~/generated-metadata/graphql';
-import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
-
-const APPLICATION_ID = '66666666-6666-4666-8666-666666666666';
-
-const renderApplicationLink = (permissionFlags: PermissionFlagType[]) => {
- const Wrapper = getJestMetadataAndApolloMocksWrapper({
- apolloMocks: [],
- onInitializeJotaiStore: (store) => {
- store.set(currentUserWorkspaceState.atom, {
- permissionFlags,
- twoFactorAuthenticationMethodSummary: [],
- objectsPermissions: [],
- });
- },
- });
-
- return render(
- <MemoryRouter>
- <ApplicationLink applicationId={APPLICATION_ID} displayName="Twenty" />
- </MemoryRouter>,
- { wrapper: Wrapper },
- );
-};
-
-describe('ApplicationLink', () => {
- it('should link to the application settings page when allowed', () => {
- renderApplicationLink([PermissionFlagType.APPLICATIONS]);
-
- expect(screen.getByText('Twenty').closest('a')).toHaveAttribute(
- 'href',
- `/settings/applications/${APPLICATION_ID}`,
- );
- });
-
- it('should render a chip without a link when application settings are forbidden', () => {
- renderApplicationLink([]);
-
- expect(screen.getByText('Twenty').closest('a')).toBeNull();
- expect(screen.getByTestId('chip')).toBeInTheDocument();
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChip.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChip.test.tsx
new file mode 100644
index 00000000000..3f024e0fcb6
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChip.test.tsx
@@ -0,0 +1,403 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import { type ReactNode } from 'react';
+import { MemoryRouter, useLocation } from 'react-router-dom';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ChatReferenceChip } from '@/ai/components/ChatReferenceChip';
+import { TextWithChatReferences } from '@/ai/components/TextWithChatReferences';
+import { ChatReferenceNavigationEnabledContext } from '@/ai/contexts/ChatReferenceNavigationEnabledContext';
+import { type ChatReferenceIdentity } from '@/ai/types/ChatReferenceIdentity';
+import { type ChatReferenceMatch } from '@/ai/types/ChatReferenceMatch';
+import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';
+import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';
+import { type ViewWithRelations } from '@/views/types/ViewWithRelations';
+import { PermissionFlagType } from '~/generated-metadata/graphql';
+import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
+import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
+import { setTestViewsInMetadataStore } from '~/testing/utils/setTestViewsInMetadataStore';
+
+const openRoutedPageInSidePanelMock = jest.fn();
+const openRecordInSidePanelMock = jest.fn();
+
+jest.mock('@/side-panel/routing/hooks/useOpenRoutedPageInSidePanel', () => ({
+ useOpenRoutedPageInSidePanel: () => ({
+ openRoutedPageInSidePanel: openRoutedPageInSidePanelMock,
+ }),
+}));
+
+jest.mock('@/side-panel/hooks/useOpenRecordInSidePanel', () => ({
+ useOpenRecordInSidePanel: () => ({
+ openRecordInSidePanel: openRecordInSidePanelMock,
+ }),
+}));
+
+const companyObjectMetadataItem = getMockObjectMetadataItemOrThrow('company');
+
+const RECORD_ID = '11111111-1111-4111-8111-111111111111';
+const VIEW_ID = '44444444-4444-4444-4444-444444444444';
+const ROLE_ID = '55555555-5555-4555-8555-555555555555';
+const APPLICATION_ID = '66666666-6666-4666-8666-666666666666';
+const UNKNOWN_ID = '77777777-7777-4777-8777-777777777777';
+
+const allCompaniesView = {
+ id: VIEW_ID,
+ name: 'All Companies',
+ icon: 'IconBuildingSkyscraper',
+ objectMetadataId: companyObjectMetadataItem.id,
+ isActive: true,
+} as ViewWithRelations;
+
+const ALL_PERMISSION_FLAGS = [
+ PermissionFlagType.DATA_MODEL,
+ PermissionFlagType.ROLES,
+ PermissionFlagType.APPLICATIONS,
+];
+
+const asMatch = (
+ reference: ChatReferenceIdentity & { displayName: string },
+): ChatReferenceMatch => ({ ...reference, fullMatch: '', index: 0 });
+
+const referenceCases: Array<{
+ reference: ChatReferenceMatch;
+ href: string;
+ permissionFlag?: PermissionFlagType;
+}> = [
+ {
+ reference: asMatch({
+ kind: 'record',
+ objectNameSingular: 'company',
+ recordId: RECORD_ID,
+ displayName: 'Acme',
+ }),
+ href: `/object/company/${RECORD_ID}`,
+ },
+ {
+ reference: asMatch({
+ kind: 'records',
+ objectMetadataId: companyObjectMetadataItem.id,
+ displayName: 'Companies',
+ }),
+ href: '/objects/companies',
+ },
+ {
+ reference: asMatch({
+ kind: 'object',
+ objectNameSingular: 'company',
+ displayName: 'Companies',
+ }),
+ href: '/settings/objects/companies',
+ permissionFlag: PermissionFlagType.DATA_MODEL,
+ },
+ {
+ reference: asMatch({
+ kind: 'field',
+ objectNameSingular: 'company',
+ fieldName: 'name',
+ displayName: 'Name',
+ }),
+ href: '/settings/objects/companies/name',
+ permissionFlag: PermissionFlagType.DATA_MODEL,
+ },
+ {
+ reference: asMatch({
+ kind: 'view',
+ viewId: VIEW_ID,
+ displayName: 'All Companies',
+ }),
+ href: `/objects/companies?viewId=${VIEW_ID}`,
+ },
+ {
+ reference: asMatch({ kind: 'role', roleId: ROLE_ID, displayName: 'Admin' }),
+ href: `/settings/members/roles/${ROLE_ID}`,
+ permissionFlag: PermissionFlagType.ROLES,
+ },
+ {
+ reference: asMatch({
+ kind: 'app',
+ applicationId: APPLICATION_ID,
+ displayName: 'Twenty',
+ }),
+ href: `/settings/applications/${APPLICATION_ID}`,
+ permissionFlag: PermissionFlagType.APPLICATIONS,
+ },
+];
+
+const findCase = (kind: ChatReferenceIdentity['kind']) =>
+ referenceCases.find(({ reference }) => reference.kind === kind)!;
+
+const LocationProbe = () => {
+ const location = useLocation();
+
+ return (
+ <div data-testid="location-probe">
+ {location.pathname}
+ {location.search}
+ </div>
+ );
+};
+
+const renderWithReferences = (
+ children: ReactNode,
+ {
+ permissionFlags = ALL_PERMISSION_FLAGS,
+ views = [allCompaniesView],
+ initialPath = '/objects/companies',
+ isNavigationEnabled = true,
+ isWorkspaceSetupChat = false,
+ }: {
+ permissionFlags?: PermissionFlagType[];
+ views?: ViewWithRelations[];
+ initialPath?: string;
+ isNavigationEnabled?: boolean;
+ isWorkspaceSetupChat?: boolean;
+ } = {},
+) => {
+ const Wrapper = getJestMetadataAndApolloMocksWrapper({
+ apolloMocks: [],
+ onInitializeJotaiStore: (store) => {
+ setTestViewsInMetadataStore(store, views);
+ store.set(currentUserWorkspaceState.atom, {
+ permissionFlags,
+ twoFactorAuthenticationMethodSummary: [],
+ objectsPermissions: [],
+ });
+ store.set(
+ shouldOpenAiChatAfterOnboardingState.atom,
+ isWorkspaceSetupChat,
+ );
+ },
+ });
+
+ return render(
+ <MemoryRouter initialEntries={[initialPath]}>
+ <ChatReferenceNavigationEnabledContext.Provider
+ value={isNavigationEnabled}
+ >
+ {children}
+ <LocationProbe />
+ </ChatReferenceNavigationEnabledContext.Provider>
+ </MemoryRouter>,
+ { wrapper: Wrapper },
+ );
+};
+
+const clickChip = (label: string) => {
+ const link = screen.getByText(label).closest('a') as HTMLElement;
+
+ fireEvent.mouseDown(link);
+ fireEvent.click(link);
+};
+
+describe('ChatReferenceChip', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it.each(referenceCases)(
+ 'should link a $reference.kind reference to $href',
+ ({ reference, href }) => {
+ renderWithReferences(<ChatReferenceChip reference={reference} />);
+
+ expect(
+ screen.getByText(reference.displayName).closest('a'),
+ ).toHaveAttribute('href', href);
+ },
+ );
+
+ it.each(
+ referenceCases.filter((testCase) => isDefined(testCase.permissionFlag)),
+ )(
+ 'should render a $reference.kind chip without a link when its settings are forbidden',
+ ({ reference }) => {
+ renderWithReferences(<ChatReferenceChip reference={reference} />, {
+ permissionFlags: [],
+ });
+
+ expect(screen.getByText(reference.displayName).closest('a')).toBeNull();
+ expect(screen.getByTestId('chip')).toBeInTheDocument();
+ },
+ );
+
+ it.each(
+ referenceCases.filter(
+ ({ reference }) =>
+ reference.kind !== 'record' && reference.kind !== 'app',
+ ),
+ )(
+ 'should open a $reference.kind reference beside the chat instead of navigating',
+ ({ reference, href }) => {
+ renderWithReferences(<ChatReferenceChip reference={reference} />, {
+ initialPath: '/chat',
+ });
+
+ clickChip(reference.displayName);
+
+ expect(openRoutedPageInSidePanelMock).toHaveBeenCalledWith({
+ path: href,
+ });
+ expect(screen.getByTestId('location-probe')).toHaveTextContent('/chat');
+ },
+ );
+
+ it('should open a record in the record side panel from the chat page', () => {
+ renderWithReferences(
+ <ChatReferenceChip reference={findCase('record').reference} />,
+ { initialPath: '/chat' },
+ );
+
+ clickChip('Acme');
+
+ expect(openRecordInSidePanelMock).toHaveBeenCalledWith({
+ recordId: RECORD_ID,
+ objectNameSingular: 'company',
+ });
+ });
+
+ it('should navigate to the application settings from the chat page since they have no side panel route', () => {
+ renderWithReferences(
+ <ChatReferenceChip reference={findCase('app').reference} />,
+ { initialPath: '/chat' },
+ );
+
+ clickChip('Twenty');
+
+ expect(openRoutedPageInSidePanelMock).not.toHaveBeenCalled();
+ expect(screen.getByTestId('location-probe')).toHaveTextContent(
+ `/settings/applications/${APPLICATION_ID}`,
+ );
+ });
+
+ it.each([
+ { name: 'outside the chat page', initialPath: '/objects/companies' },
+ {
+ name: 'on the workspace setup chat',
+ initialPath: '/chat',
+ isWorkspaceSetupChat: true,
+ },
+ ])(
+ 'should navigate instead of opening a side panel $name',
+ ({ initialPath, isWorkspaceSetupChat }) => {
+ const { reference, href } = findCase('view');
+
+ renderWithReferences(<ChatReferenceChip reference={reference} />, {
+ initialPath,
+ isWorkspaceSetupChat,
+ });
+
+ clickChip(reference.displayName);
+
+ expect(openRoutedPageInSidePanelMock).not.toHaveBeenCalled();
+ expect(screen.getByTestId('location-probe')).toHaveTextContent(href);
+ },
+ );
+
+ it.each([
+ {
+ name: 'a record of an unknown object',
+ reference: asMatch({
+ kind: 'record',
+ objectNameSingular: 'partner',
+ recordId: RECORD_ID,
+ displayName: 'Acme',
+ }),
+ },
+ {
+ name: 'an unknown object metadata id',
+ reference: asMatch({
+ kind: 'records',
+ objectMetadataId: UNKNOWN_ID,
+ displayName: 'Companies',
+ }),
+ },
+ {
+ name: 'an unknown view id',
+ reference: asMatch({
+ kind: 'view',
+ viewId: UNKNOWN_ID,
+ displayName: 'All Companies',
+ }),
+ },
+ {
+ name: 'an archived view',
+ reference: findCase('view').reference,
+ views: [{ ...allCompaniesView, isActive: false }],
+ },
+ ])('should render plain text for $name', ({ reference, views }) => {
+ renderWithReferences(<ChatReferenceChip reference={reference} />, {
+ views,
+ });
+
+ expect(screen.getByText(reference.displayName)).toBeInTheDocument();
+ expect(screen.queryByTestId('chip')).not.toBeInTheDocument();
+ });
+
+ it.each([
+ {
+ name: 'an object that does not exist yet',
+ reference: asMatch({
+ kind: 'object',
+ objectNameSingular: 'partner',
+ displayName: 'Partners',
+ }),
+ },
+ {
+ name: 'a field that does not exist yet',
+ reference: asMatch({
+ kind: 'field',
+ objectNameSingular: 'company',
+ fieldName: 'annualContractValue',
+ displayName: 'Annual contract value',
+ }),
+ },
+ ])('should render a chip without a link for $name', ({ reference }) => {
+ renderWithReferences(<ChatReferenceChip reference={reference} />);
+
+ expect(screen.getByText(reference.displayName).closest('a')).toBeNull();
+ expect(screen.getByTestId('chip')).toBeInTheDocument();
+ });
+
+ it('should render a static chip when navigation is disabled', () => {
+ renderWithReferences(
+ <ChatReferenceChip reference={findCase('role').reference} />,
+ { isNavigationEnabled: false },
+ );
+
+ expect(screen.queryByRole('link')).not.toBeInTheDocument();
+
+ const chipClassName = screen.getByTestId('chip').className;
+
+ expect(chipClassName).not.toMatch(/cursorPointer/);
+ expect(chipClassName).toMatch(/backgroundStatic/);
+ });
+});
+
+describe('TextWithChatReferences', () => {
+ it('should render chips inside the surrounding text', () => {
+ renderWithReferences(
+ <TextWithChatReferences
+ text={`Open the [[view:${VIEW_ID}:All Companies]] view`}
+ />,
+ );
+
+ expect(screen.getByText('All Companies').closest('a')).toHaveAttribute(
+ 'href',
+ `/objects/companies?viewId=${VIEW_ID}`,
+ );
+ expect(screen.getByText(/Open the/)).toHaveTextContent(
+ 'Open the All Companies view',
+ );
+ });
+
+ it('should render the label of a retired id-addressed field reference as plain text', () => {
+ renderWithReferences(
+ <TextWithChatReferences
+ text={`Sort by [[field:${UNKNOWN_ID}:Stage]] first`}
+ />,
+ );
+
+ expect(screen.queryByTestId('chip')).not.toBeInTheDocument();
+ expect(screen.getByText(/Sort by/)).toHaveTextContent(
+ 'Sort by Stage first',
+ );
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChipDisplay.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChipDisplay.test.tsx
deleted file mode 100644
index 0d7b1ef7f98..00000000000
--- a/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChipDisplay.test.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { MemoryRouter, useLocation } from 'react-router-dom';
-
-import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';
-import { ChatReferenceNavigationEnabledContext } from '@/ai/contexts/ChatReferenceNavigationEnabledContext';
-
-const LocationProbe = () => {
- const location = useLocation();
-
- return <div data-testid="location-probe">{location.pathname}</div>;
-};
-
-const renderChip = ({
- isNavigationEnabled,
-}: {
- isNavigationEnabled: boolean;
-}) =>
- render(
- <MemoryRouter>
- <ChatReferenceNavigationEnabledContext.Provider
- value={isNavigationEnabled}
- >
- <ChatReferenceChipDisplay
- displayName="Acme"
- leftComponent={null}
- to="/objects/companies/acme-id"
- />
- </ChatReferenceNavigationEnabledContext.Provider>
- </MemoryRouter>,
- );
-
-describe('ChatReferenceChipDisplay', () => {
- it('should link to the reference when navigation is enabled', () => {
- renderChip({ isNavigationEnabled: true });
-
- expect(screen.getByRole('link')).toHaveAttribute(
- 'href',
- '/objects/companies/acme-id',
- );
- });
-
- it('should render a plain chip when navigation is disabled', () => {
- renderChip({ isNavigationEnabled: false });
-
- expect(screen.queryByRole('link')).not.toBeInTheDocument();
- expect(screen.getByText('Acme')).toBeInTheDocument();
- });
-
- it('should not look interactive when navigation is disabled', () => {
- renderChip({ isNavigationEnabled: false });
-
- const chipClassName = screen.getByTestId('chip').className;
-
- expect(chipClassName).not.toMatch(/cursorPointer/);
- expect(chipClassName).toMatch(/backgroundStatic/);
- });
-
- it('should run onClick on a plain click instead of navigating to `to`', () => {
- const onClickMock = jest.fn();
-
- render(
- <MemoryRouter initialEntries={['/chat/thread-id']}>
- <ChatReferenceNavigationEnabledContext.Provider value={true}>
- <ChatReferenceChipDisplay
- displayName="Acme"
- leftComponent={null}
- to="/objects/companies/acme-id"
- onClick={onClickMock}
- />
- </ChatReferenceNavigationEnabledContext.Provider>
- <LocationProbe />
- </MemoryRouter>,
- );
-
- const link = screen.getByRole('link');
- fireEvent.mouseDown(link);
- fireEvent.click(link);
-
- expect(onClickMock).toHaveBeenCalledTimes(1);
- expect(screen.getByTestId('location-probe')).toHaveTextContent(
- '/chat/thread-id',
- );
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/DeprecatedFieldMetadataLinkById.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/DeprecatedFieldMetadataLinkById.test.tsx
deleted file mode 100644
index 32ac5fcad9d..00000000000
--- a/packages/twenty-front/src/modules/ai/components/__tests__/DeprecatedFieldMetadataLinkById.test.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { MemoryRouter } from 'react-router-dom';
-
-import { DeprecatedFieldMetadataLinkById } from '@/ai/components/DeprecatedFieldMetadataLinkById';
-import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';
-import { type Store } from 'jotai/vanilla/store';
-import { PermissionFlagType } from '~/generated-metadata/graphql';
-import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
-import { getMockFieldMetadataItemOrThrow } from '~/testing/utils/getMockFieldMetadataItemOrThrow';
-import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
-
-const companyObjectMetadataItem = getMockObjectMetadataItemOrThrow('company');
-
-const nameFieldMetadataItem = getMockFieldMetadataItemOrThrow({
- objectMetadataItem: companyObjectMetadataItem,
- fieldName: 'name',
-});
-
-const setPermissionFlags = (
- store: Store,
- permissionFlags: PermissionFlagType[],
-) => {
- store.set(currentUserWorkspaceState.atom, {
- permissionFlags,
- twoFactorAuthenticationMethodSummary: [],
- objectsPermissions: [],
- });
-};
-
-const renderDeprecatedFieldMetadataLinkById = ({
- fieldMetadataItemId,
- displayName,
- permissionFlags,
-}: {
- fieldMetadataItemId: string;
- displayName: string;
- permissionFlags: PermissionFlagType[];
-}) => {
- const Wrapper = getJestMetadataAndApolloMocksWrapper({
- apolloMocks: [],
- onInitializeJotaiStore: (store) =>
- setPermissionFlags(store, permissionFlags),
- });
-
- return render(
- <MemoryRouter>
- <DeprecatedFieldMetadataLinkById
- fieldMetadataItemId={fieldMetadataItemId}
- displayName={displayName}
- />
- </MemoryRouter>,
- { wrapper: Wrapper },
- );
-};
-
-describe('DeprecatedFieldMetadataLinkById', () => {
- it('should link a field to its settings page', () => {
- renderDeprecatedFieldMetadataLinkById({
- fieldMetadataItemId: nameFieldMetadataItem.id,
- displayName: 'Name',
- permissionFlags: [PermissionFlagType.DATA_MODEL],
- });
-
- expect(screen.getByText('Name').closest('a')).toHaveAttribute(
- 'href',
- `/settings/objects/${companyObjectMetadataItem.namePlural}/${nameFieldMetadataItem.name}`,
- );
- });
-
- it('should render a chip without a link when the user cannot access the data model', () => {
- renderDeprecatedFieldMetadataLinkById({
- fieldMetadataItemId: nameFieldMetadataItem.id,
- displayName: 'Name',
- permissionFlags: [],
- });
-
- expect(screen.getByText('Name').closest('a')).toBeNull();
- expect(screen.getByTestId('chip')).toBeInTheDocument();
- });
-
- it('should render plain text for an unknown field id', () => {
- renderDeprecatedFieldMetadataLinkById({
- fieldMetadataItemId: '33333333-3333-3333-3333-333333333333',
- displayName: 'Partner type',
- permissionFlags: [PermissionFlagType.DATA_MODEL],
- });
-
- expect(screen.getByText('Partner type')).toBeInTheDocument();
- expect(screen.queryByTestId('chip')).not.toBeInTheDocument();
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/ObjectMetadataLink.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/ObjectMetadataLink.test.tsx
deleted file mode 100644
index ef8947a42ee..00000000000
--- a/packages/twenty-front/src/modules/ai/components/__tests__/ObjectMetadataLink.test.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { MemoryRouter } from 'react-router-dom';
-
-import { ObjectMetadataLink } from '@/ai/components/ObjectMetadataLink';
-import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';
-import { PermissionFlagType } from '~/generated-metadata/graphql';
-import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
-
-const renderObjectMetadataLink = ({
- objectNameSingular,
- displayName,
- permissionFlags = [PermissionFlagType.DATA_MODEL],
-}: {
- objectNameSingular: string;
- displayName: string;
- permissionFlags?: PermissionFlagType[];
-}) => {
- const Wrapper = getJestMetadataAndApolloMocksWrapper({
- apolloMocks: [],
- onInitializeJotaiStore: (store) => {
- store.set(currentUserWorkspaceState.atom, {
- permissionFlags,
- twoFactorAuthenticationMethodSummary: [],
- objectsPermissions: [],
- });
- },
- });
-
- return render(
- <MemoryRouter>
- <ObjectMetadataLink
- objectNameSingular={objectNameSingular}
- displayName={displayName}
- />
- </MemoryRouter>,
- { wrapper: Wrapper },
- );
-};
-
-describe('ObjectMetadataLink', () => {
- it('should link an existing object to its data model settings page', () => {
- renderObjectMetadataLink({
- objectNameSingular: 'company',
- displayName: 'Companies',
- });
-
- expect(screen.getByText('Companies').closest('a')).toHaveAttribute(
- 'href',
- '/settings/objects/companies',
- );
- });
-
- it('should render a chip without a link when data model settings are forbidden', () => {
- renderObjectMetadataLink({
- objectNameSingular: 'company',
- displayName: 'Companies',
- permissionFlags: [],
- });
-
- expect(screen.getByText('Companies').closest('a')).toBeNull();
- expect(screen.getByTestId('chip')).toBeInTheDocument();
- });
-
- it('should render a chip without a link for an object that does not exist yet', () => {
- renderObjectMetadataLink({
- objectNameSingular: 'partner',
- displayName: 'Partners',
- });
-
- expect(screen.getByText('Partners')).toBeInTheDocument();
- expect(screen.getByText('Partners').closest('a')).toBeNull();
- expect(screen.getByTestId('chip')).toBeInTheDocument();
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/RecordsLink.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/RecordsLink.test.tsx
deleted file mode 100644
index e82306b4a8e..00000000000
--- a/packages/twenty-front/src/modules/ai/components/__tests__/RecordsLink.test.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { MemoryRouter } from 'react-router-dom';
-
-import { RecordsLink } from '@/ai/components/RecordsLink';
-import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
-import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
-
-const openViewTargetMock = jest.fn();
-
-jest.mock('@/ai/hooks/useChatTargetNavigation', () => ({
- useChatTargetNavigation: () => ({
- openViewTarget: openViewTargetMock,
- }),
-}));
-
-const companyObjectMetadataItem = getMockObjectMetadataItemOrThrow('company');
-
-const renderRecordsLink = (objectMetadataId: string) => {
- const Wrapper = getJestMetadataAndApolloMocksWrapper({ apolloMocks: [] });
-
- return render(
- <MemoryRouter>
- <RecordsLink
- objectMetadataId={objectMetadataId}
- displayName="Companies"
- />
- </MemoryRouter>,
- { wrapper: Wrapper },
- );
-};
-
-describe('RecordsLink', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- window.history.pushState({}, '', '/objects/companies');
- });
-
- it('should link to the object records without selecting a view', () => {
- renderRecordsLink(companyObjectMetadataItem.id);
-
- expect(screen.getByText('Companies').closest('a')).toHaveAttribute(
- 'href',
- '/objects/companies',
- );
- });
-
- it('should open the default records destination from the chat page', () => {
- window.history.pushState({}, '', '/chat');
- renderRecordsLink(companyObjectMetadataItem.id);
-
- const link = screen.getByText('Companies').closest('a') as HTMLElement;
- fireEvent.mouseDown(link);
- fireEvent.click(link);
-
- expect(openViewTargetMock).toHaveBeenCalledWith({
- objectNameSingular: companyObjectMetadataItem.nameSingular,
- });
- });
-
- it('should render plain text for an unknown object metadata id', () => {
- renderRecordsLink('77777777-7777-4777-8777-777777777777');
-
- expect(screen.getByText('Companies')).toBeInTheDocument();
- expect(screen.queryByTestId('chip')).not.toBeInTheDocument();
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/RoleLink.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/RoleLink.test.tsx
deleted file mode 100644
index c6dba3553dd..00000000000
--- a/packages/twenty-front/src/modules/ai/components/__tests__/RoleLink.test.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { MemoryRouter } from 'react-router-dom';
-
-import { RoleLink } from '@/ai/components/RoleLink';
-import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';
-import { PermissionFlagType } from '~/generated-metadata/graphql';
-import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
-
-const ROLE_ID = '55555555-5555-4555-8555-555555555555';
-const openRoutedPageInSidePanelMock = jest.fn();
-
-jest.mock('@/side-panel/routing/hooks/useOpenRoutedPageInSidePanel', () => ({
- useOpenRoutedPageInSidePanel: () => ({
- openRoutedPageInSidePanel: openRoutedPageInSidePanelMock,
- }),
-}));
-
-const renderRoleLink = (
- permissionFlags: PermissionFlagType[],
- initialPath = '/objects/companies',
-) => {
- const Wrapper = getJestMetadataAndApolloMocksWrapper({
- apolloMocks: [],
- onInitializeJotaiStore: (store) => {
- store.set(currentUserWorkspaceState.atom, {
- permissionFlags,
- twoFactorAuthenticationMethodSummary: [],
- objectsPermissions: [],
- });
- },
- });
-
- return render(
- <MemoryRouter initialEntries={[initialPath]}>
- <RoleLink roleId={ROLE_ID} displayName="Admin" />
- </MemoryRouter>,
- { wrapper: Wrapper },
- );
-};
-
-describe('RoleLink', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('should open the role as an artifact on the chat page', () => {
- renderRoleLink([PermissionFlagType.ROLES], '/chat');
-
- const link = screen.getByText('Admin').closest('a') as HTMLElement;
- fireEvent.mouseDown(link);
- fireEvent.click(link);
-
- expect(openRoutedPageInSidePanelMock).toHaveBeenCalledWith({
- path: `/settings/members/roles/${ROLE_ID}`,
- });
- });
-
- it('should link to the role settings page when allowed', () => {
- renderRoleLink([PermissionFlagType.ROLES]);
-
- expect(screen.getByText('Admin').closest('a')).toHaveAttribute(
- 'href',
- `/settings/members/roles/${ROLE_ID}`,
- );
- });
-
- it('should render a chip without a link when roles settings are forbidden', () => {
- renderRoleLink([]);
-
- expect(screen.getByText('Admin').closest('a')).toBeNull();
- expect(screen.getByTestId('chip')).toBeInTheDocument();
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/TextWithChatReferences.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/TextWithChatReferences.test.tsx
deleted file mode 100644
index e2830602c61..00000000000
--- a/packages/twenty-front/src/modules/ai/components/__tests__/TextWithChatReferences.test.tsx
+++ /dev/null
@@ -1,224 +0,0 @@
-import { render, screen } from '@testing-library/react';
-
-import { TextWithChatReferences } from '@/ai/components/TextWithChatReferences';
-
-jest.mock('@/ai/components/RecordLink', () => ({
- RecordLink: ({
- displayName,
- objectNameSingular,
- recordId,
- }: {
- displayName: string;
- objectNameSingular: string;
- recordId: string;
- }) => (
- <a data-testid="record-link" href={`/${objectNameSingular}/${recordId}`}>
- {displayName}
- </a>
- ),
-}));
-
-jest.mock('@/ai/components/RecordsLink', () => ({
- RecordsLink: ({
- displayName,
- objectMetadataId,
- }: {
- displayName: string;
- objectMetadataId: string;
- }) => (
- <a data-testid="records-link" href={`/records/${objectMetadataId}`}>
- {displayName}
- </a>
- ),
-}));
-
-jest.mock('@/ai/components/ObjectMetadataLink', () => ({
- ObjectMetadataLink: ({
- displayName,
- objectNameSingular,
- }: {
- displayName: string;
- objectNameSingular: string;
- }) => (
- <a data-testid="object-link" href={`/objects/${objectNameSingular}`}>
- {displayName}
- </a>
- ),
-}));
-
-jest.mock('@/ai/components/FieldMetadataLink', () => ({
- FieldMetadataLink: ({
- objectNameSingular,
- fieldName,
- displayName,
- }: {
- objectNameSingular: string;
- fieldName: string;
- displayName: string;
- }) => (
- <a
- data-testid="field-link"
- href={`/fields/${objectNameSingular}/${fieldName}`}
- >
- {displayName}
- </a>
- ),
-}));
-
-jest.mock('@/ai/components/DeprecatedFieldMetadataLinkById', () => ({
- DeprecatedFieldMetadataLinkById: ({
- fieldMetadataItemId,
- displayName,
- }: {
- fieldMetadataItemId: string;
- displayName: string;
- }) => (
- <a data-testid="legacy-field-link" href={`/fields/${fieldMetadataItemId}`}>
- {displayName}
- </a>
- ),
-}));
-
-jest.mock('@/ai/components/ViewLink', () => ({
- ViewLink: ({
- displayName,
- viewId,
- }: {
- displayName: string;
- viewId: string;
- }) => (
- <a data-testid="view-link" href={`/views/${viewId}`}>
- {displayName}
- </a>
- ),
-}));
-
-jest.mock('@/ai/components/RoleLink', () => ({
- RoleLink: ({
- displayName,
- roleId,
- }: {
- displayName: string;
- roleId: string;
- }) => (
- <a data-testid="role-link" href={`/roles/${roleId}`}>
- {displayName}
- </a>
- ),
-}));
-
-jest.mock('@/ai/components/ApplicationLink', () => ({
- ApplicationLink: ({
- applicationId,
- displayName,
- }: {
- applicationId: string;
- displayName: string;
- }) => (
- <a data-testid="app-link" href={`/apps/${applicationId}`}>
- {displayName}
- </a>
- ),
-}));
-
-describe('TextWithChatReferences', () => {
- it('should render plain text without references as-is', () => {
- render(<TextWithChatReferences text="Which company should we contact?" />);
-
- expect(
- screen.getByText('Which company should we contact?'),
- ).toBeInTheDocument();
- expect(screen.queryByTestId('record-link')).not.toBeInTheDocument();
- });
-
- it('should replace record references with RecordLink chips', () => {
- render(
- <TextWithChatReferences text="Contact [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme]] next" />,
- );
-
- expect(screen.getByTestId('record-link')).toHaveTextContent('Acme');
- expect(screen.getByText(/Contact/)).toHaveTextContent('Contact Acme next');
- expect(screen.queryByText(/\[\[record:company:/)).not.toBeInTheDocument();
- });
-
- it('should replace multiple record references in option-style labels', () => {
- render(
- <TextWithChatReferences text="Merge [[person:11111111-1111-1111-1111-111111111111:Alice]] into [[person:22222222-2222-2222-2222-222222222222:Bob]]" />,
- );
-
- const recordLinks = screen.getAllByTestId('record-link');
-
- expect(recordLinks).toHaveLength(2);
- expect(recordLinks[0]).toHaveTextContent('Alice');
- expect(recordLinks[1]).toHaveTextContent('Bob');
- expect(screen.queryByText(/\[\[/)).not.toBeInTheDocument();
- });
-
- it('should chip labels that contain backticks and colons', () => {
- render(
- <TextWithChatReferences text="See [[record:workflow:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Workflow `UPDATE_RECORD` step]] then [[record:person:c1b2c3d4-e5f6-7890-abcd-ef1234567890:Doe: Jane]]" />,
- );
-
- const recordLinks = screen.getAllByTestId('record-link');
-
- expect(recordLinks).toHaveLength(2);
- expect(recordLinks[0]).toHaveTextContent('Workflow `UPDATE_RECORD` step');
- expect(recordLinks[1]).toHaveTextContent('Doe: Jane');
- expect(screen.queryByText(/\[\[record:/)).not.toBeInTheDocument();
- });
-
- it('should render a reference using a retired closing tag as plain text', () => {
- render(
- <TextWithChatReferences text="Contact [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme[[/record]] next" />,
- );
-
- expect(screen.queryByTestId('record-link')).not.toBeInTheDocument();
- expect(screen.getByText(/Contact/)).toHaveTextContent(
- 'Contact [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme[[/record]] next',
- );
- });
-
- it('should route a name-addressed field reference to the field chip', () => {
- render(
- <TextWithChatReferences text="Add [[field:person:role:Role]] to People" />,
- );
-
- expect(screen.getByTestId('field-link')).toHaveAttribute(
- 'href',
- '/fields/person/role',
- );
- expect(screen.queryByTestId('legacy-field-link')).not.toBeInTheDocument();
- });
-
- it('should route each reference kind to its own chip', () => {
- render(
- <TextWithChatReferences text="The [[view:44444444-4444-4444-4444-444444444444:Pipeline]] view of [[records:77777777-7777-4777-8777-777777777777:Companies]] uses the [[object:partner:Partners]] schema and groups [[record:person:11111111-1111-1111-1111-111111111111:Alice]] by [[field:33333333-3333-3333-3333-333333333333:Stage]] for [[role:55555555-5555-4555-8555-555555555555:Admin]] in [[app:66666666-6666-4666-8666-666666666666:Twenty]]" />,
- );
-
- expect(screen.getByTestId('view-link')).toHaveAttribute(
- 'href',
- '/views/44444444-4444-4444-4444-444444444444',
- );
- expect(screen.getByTestId('records-link')).toHaveAttribute(
- 'href',
- '/records/77777777-7777-4777-8777-777777777777',
- );
- expect(screen.getByTestId('object-link')).toHaveAttribute(
- 'href',
- '/objects/partner',
- );
- expect(screen.getByTestId('record-link')).toHaveTextContent('Alice');
- expect(screen.getByTestId('legacy-field-link')).toHaveAttribute(
- 'href',
- '/fields/33333333-3333-3333-3333-333333333333',
- );
- expect(screen.getByTestId('role-link')).toHaveAttribute(
- 'href',
- '/roles/55555555-5555-4555-8555-555555555555',
- );
- expect(screen.getByTestId('app-link')).toHaveAttribute(
- 'href',
- '/apps/66666666-6666-4666-8666-666666666666',
- );
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/ViewLink.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/ViewLink.test.tsx
deleted file mode 100644
index ecf9b97b44d..00000000000
--- a/packages/twenty-front/src/modules/ai/components/__tests__/ViewLink.test.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { MemoryRouter } from 'react-router-dom';
-
-import { ViewLink } from '@/ai/components/ViewLink';
-import { type ViewWithRelations } from '@/views/types/ViewWithRelations';
-import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
-import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
-import { setTestViewsInMetadataStore } from '~/testing/utils/setTestViewsInMetadataStore';
-
-const openRoutedPageInSidePanelMock = jest.fn();
-
-jest.mock('@/side-panel/routing/hooks/useOpenRoutedPageInSidePanel', () => ({
- useOpenRoutedPageInSidePanel: () => ({
- openRoutedPageInSidePanel: openRoutedPageInSidePanelMock,
- }),
-}));
-
-const companyObjectMetadataItem = getMockObjectMetadataItemOrThrow('company');
-
-const VIEW_ID = '44444444-4444-4444-4444-444444444444';
-
-const allCompaniesView = {
- id: VIEW_ID,
- name: 'All Companies',
- icon: 'IconBuildingSkyscraper',
- objectMetadataId: companyObjectMetadataItem.id,
- isActive: true,
-} as ViewWithRelations;
-
-const renderViewLink = ({
- viewId,
- displayName,
- views,
- initialPath = '/objects/companies',
-}: {
- viewId: string;
- displayName: string;
- views: ViewWithRelations[];
- initialPath?: string;
-}) => {
- const Wrapper = getJestMetadataAndApolloMocksWrapper({
- apolloMocks: [],
- onInitializeJotaiStore: (store) =>
- setTestViewsInMetadataStore(store, views),
- });
-
- return render(
- <MemoryRouter initialEntries={[initialPath]}>
- <ViewLink viewId={viewId} displayName={displayName} />
- </MemoryRouter>,
- { wrapper: Wrapper },
- );
-};
-
-describe('ViewLink', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('should open the view as an artifact on a plain click on the chat page', () => {
- renderViewLink({
- viewId: VIEW_ID,
- displayName: 'All Companies',
- views: [allCompaniesView],
- initialPath: '/chat',
- });
-
- const link = screen.getByText('All Companies').closest('a') as HTMLElement;
- fireEvent.mouseDown(link);
- fireEvent.click(link);
-
- expect(openRoutedPageInSidePanelMock).toHaveBeenCalledWith({
- path: `/objects/${companyObjectMetadataItem.namePlural}?viewId=${VIEW_ID}`,
- });
- });
-
- it('should not open an artifact on click outside the chat page', () => {
- renderViewLink({
- viewId: VIEW_ID,
- displayName: 'All Companies',
- views: [allCompaniesView],
- });
-
- const link = screen.getByText('All Companies').closest('a') as HTMLElement;
- fireEvent.mouseDown(link);
- fireEvent.click(link);
-
- expect(openRoutedPageInSidePanelMock).not.toHaveBeenCalled();
- });
-
- it('should link a view to its object index page', () => {
- renderViewLink({
- viewId: VIEW_ID,
- displayName: 'All Companies',
- views: [allCompaniesView],
- });
-
- expect(screen.getByText('All Companies').closest('a')).toHaveAttribute(
- 'href',
- `/objects/${companyObjectMetadataItem.namePlural}?viewId=${VIEW_ID}`,
- );
- });
-
- it('should render plain text for an unknown view id', () => {
- renderViewLink({
- viewId: VIEW_ID,
- displayName: 'All Companies',
- views: [],
- });
-
- expect(screen.getByText('All Companies')).toBeInTheDocument();
- expect(screen.queryByTestId('chip')).not.toBeInTheDocument();
- });
-
- it('should render plain text for an archived view', () => {
- renderViewLink({
- viewId: VIEW_ID,
- displayName: 'All Companies',
- views: [{ ...allCompaniesView, isActive: false }],
- });
-
- expect(screen.queryByTestId('chip')).not.toBeInTheDocument();
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceAppPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceAppPattern.ts
deleted file mode 100644
index e4364139cd2..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceAppPattern.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
-import { CHAT_REFERENCE_UUID_PATTERN } from '@/ai/constants/ChatReferenceUuidPattern';
-
-export const CHAT_REFERENCE_APP_PATTERN = `\\[\\[app:(?<applicationId>${CHAT_REFERENCE_UUID_PATTERN}):(?<applicationLabel>${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`;
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceLabelPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceBodyPattern.ts
similarity index 64%
rename from packages/twenty-front/src/modules/ai/constants/ChatReferenceLabelPattern.ts
rename to packages/twenty-front/src/modules/ai/constants/ChatReferenceBodyPattern.ts
index fb08cedfb4e..81af118630c 100644
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceLabelPattern.ts
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceBodyPattern.ts
@@ -1,2 +1,2 @@
// Excluding brackets and line breaks stops an unclosed reference from swallowing the text and markers after it.
-export const CHAT_REFERENCE_LABEL_PATTERN = '[^\\[\\]\\n]*';
+export const CHAT_REFERENCE_BODY_PATTERN = '[^\\[\\]\\n]*';
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceFieldPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceFieldPattern.ts
deleted file mode 100644
index 3c523e8bf61..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceFieldPattern.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
-import { CHAT_REFERENCE_METADATA_NAME_PATTERN } from '@/ai/constants/ChatReferenceMetadataNamePattern';
-
-export const CHAT_REFERENCE_FIELD_PATTERN = `\\[\\[field:(?<fieldObjectNameSingular>${CHAT_REFERENCE_METADATA_NAME_PATTERN}):(?<fieldName>${CHAT_REFERENCE_METADATA_NAME_PATTERN}):(?<fieldLabel>${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`;
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceIdentityShapeByKind.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceIdentityShapeByKind.ts
new file mode 100644
index 00000000000..476ef9a5362
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceIdentityShapeByKind.ts
@@ -0,0 +1,19 @@
+import { CHAT_REFERENCE_METADATA_NAME_REGEX } from '@/ai/constants/ChatReferenceMetadataNameRegex';
+import { CHAT_REFERENCE_UUID_REGEX } from '@/ai/constants/ChatReferenceUuidRegex';
+import { type ChatReferenceKind } from '@/ai/types/ChatReferenceKind';
+
+export const CHAT_REFERENCE_IDENTITY_SHAPE_BY_KIND: Record<
+ ChatReferenceKind,
+ readonly RegExp[]
+> = {
+ record: [CHAT_REFERENCE_METADATA_NAME_REGEX, CHAT_REFERENCE_UUID_REGEX],
+ records: [CHAT_REFERENCE_UUID_REGEX],
+ object: [CHAT_REFERENCE_METADATA_NAME_REGEX],
+ field: [
+ CHAT_REFERENCE_METADATA_NAME_REGEX,
+ CHAT_REFERENCE_METADATA_NAME_REGEX,
+ ],
+ view: [CHAT_REFERENCE_UUID_REGEX],
+ role: [CHAT_REFERENCE_UUID_REGEX],
+ app: [CHAT_REFERENCE_UUID_REGEX],
+};
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceLegacyFieldByIdPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceLegacyFieldByIdPattern.ts
deleted file mode 100644
index 0bab88ee9c3..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceLegacyFieldByIdPattern.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
-import { CHAT_REFERENCE_UUID_PATTERN } from '@/ai/constants/ChatReferenceUuidPattern';
-
-export const CHAT_REFERENCE_LEGACY_FIELD_BY_ID_PATTERN = `\\[\\[field:(?<legacyFieldMetadataItemId>${CHAT_REFERENCE_UUID_PATTERN}):(?<legacyFieldLabel>${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`;
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceMalformedRegex.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceMalformedRegex.ts
index d971b03f908..e26b8ddd3d1 100644
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceMalformedRegex.ts
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceMalformedRegex.ts
@@ -1,6 +1,6 @@
-import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
+import { CHAT_REFERENCE_BODY_PATTERN } from '@/ai/constants/ChatReferenceBodyPattern';
export const CHAT_REFERENCE_MALFORMED_REGEX = new RegExp(
- `\\[\\[(?:record|records|object|field|view|role|app):(${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`,
+ `\\[\\[(?:record|records|object|field|view|role|app):(${CHAT_REFERENCE_BODY_PATTERN})\\]\\]`,
'g',
);
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceMetadataNamePattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceMetadataNamePattern.ts
deleted file mode 100644
index 200a0262eb2..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceMetadataNamePattern.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const CHAT_REFERENCE_METADATA_NAME_PATTERN = '[a-zA-Z][a-zA-Z0-9]*';
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceMetadataNameRegex.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceMetadataNameRegex.ts
new file mode 100644
index 00000000000..8ec4a42f331
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceMetadataNameRegex.ts
@@ -0,0 +1 @@
+export const CHAT_REFERENCE_METADATA_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9]*$/;
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceObjectPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceObjectPattern.ts
deleted file mode 100644
index 6e2b6a62a9a..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceObjectPattern.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
-import { CHAT_REFERENCE_METADATA_NAME_PATTERN } from '@/ai/constants/ChatReferenceMetadataNamePattern';
-
-export const CHAT_REFERENCE_OBJECT_PATTERN = `\\[\\[object:(?<objectNameSingular>${CHAT_REFERENCE_METADATA_NAME_PATTERN}):(?<objectLabel>${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`;
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferencePermissionFlagByKind.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferencePermissionFlagByKind.ts
new file mode 100644
index 00000000000..fdfa2943c10
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferencePermissionFlagByKind.ts
@@ -0,0 +1,11 @@
+import { type ChatReferenceKind } from '@/ai/types/ChatReferenceKind';
+import { PermissionFlagType } from '~/generated-metadata/graphql';
+
+export const CHAT_REFERENCE_PERMISSION_FLAG_BY_KIND: Partial<
+ Record<ChatReferenceKind, PermissionFlagType>
+> = {
+ object: PermissionFlagType.DATA_MODEL,
+ field: PermissionFlagType.DATA_MODEL,
+ role: PermissionFlagType.ROLES,
+ app: PermissionFlagType.APPLICATIONS,
+};
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceRecordPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceRecordPattern.ts
deleted file mode 100644
index cb4ac4ef5dc..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceRecordPattern.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
-import { CHAT_REFERENCE_METADATA_NAME_PATTERN } from '@/ai/constants/ChatReferenceMetadataNamePattern';
-import { CHAT_REFERENCE_UUID_PATTERN } from '@/ai/constants/ChatReferenceUuidPattern';
-
-export const CHAT_REFERENCE_RECORD_PATTERN = `\\[\\[(?:record:)?(?<recordObjectNameSingular>${CHAT_REFERENCE_METADATA_NAME_PATTERN}):(?<recordId>${CHAT_REFERENCE_UUID_PATTERN}):(?<recordLabel>${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`;
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceRecordsPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceRecordsPattern.ts
deleted file mode 100644
index 7b10384eeb8..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceRecordsPattern.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
-import { CHAT_REFERENCE_UUID_PATTERN } from '@/ai/constants/ChatReferenceUuidPattern';
-
-export const CHAT_REFERENCE_RECORDS_PATTERN = `\\[\\[records:(?<objectMetadataId>${CHAT_REFERENCE_UUID_PATTERN}):(?<recordsLabel>${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`;
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceRegex.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceRegex.ts
index a7ee75c35d2..6e704536ab9 100644
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceRegex.ts
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceRegex.ts
@@ -1,24 +1,6 @@
-import { CHAT_REFERENCE_APP_PATTERN } from '@/ai/constants/ChatReferenceAppPattern';
-import { CHAT_REFERENCE_FIELD_PATTERN } from '@/ai/constants/ChatReferenceFieldPattern';
-import { CHAT_REFERENCE_LEGACY_FIELD_BY_ID_PATTERN } from '@/ai/constants/ChatReferenceLegacyFieldByIdPattern';
-import { CHAT_REFERENCE_OBJECT_PATTERN } from '@/ai/constants/ChatReferenceObjectPattern';
-import { CHAT_REFERENCE_RECORD_PATTERN } from '@/ai/constants/ChatReferenceRecordPattern';
-import { CHAT_REFERENCE_RECORDS_PATTERN } from '@/ai/constants/ChatReferenceRecordsPattern';
-import { CHAT_REFERENCE_ROLE_PATTERN } from '@/ai/constants/ChatReferenceRolePattern';
-import { CHAT_REFERENCE_VIEW_PATTERN } from '@/ai/constants/ChatReferenceViewPattern';
+import { CHAT_REFERENCE_BODY_PATTERN } from '@/ai/constants/ChatReferenceBodyPattern';
-// The record pattern must stay last: its `record:` prefix is optional, so it
-// matches the metadata markers too and would swallow them if tried first.
export const CHAT_REFERENCE_REGEX = new RegExp(
- [
- CHAT_REFERENCE_OBJECT_PATTERN,
- CHAT_REFERENCE_FIELD_PATTERN,
- CHAT_REFERENCE_LEGACY_FIELD_BY_ID_PATTERN,
- CHAT_REFERENCE_VIEW_PATTERN,
- CHAT_REFERENCE_RECORDS_PATTERN,
- CHAT_REFERENCE_ROLE_PATTERN,
- CHAT_REFERENCE_APP_PATTERN,
- CHAT_REFERENCE_RECORD_PATTERN,
- ].join('|'),
+ `\\[\\[(${CHAT_REFERENCE_BODY_PATTERN})\\]\\]`,
'g',
);
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceRolePattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceRolePattern.ts
deleted file mode 100644
index 574e632d7c5..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceRolePattern.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
-import { CHAT_REFERENCE_UUID_PATTERN } from '@/ai/constants/ChatReferenceUuidPattern';
-
-export const CHAT_REFERENCE_ROLE_PATTERN = `\\[\\[role:(?<roleId>${CHAT_REFERENCE_UUID_PATTERN}):(?<roleLabel>${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`;
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceUuidPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceUuidPattern.ts
deleted file mode 100644
index 409c464d42b..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceUuidPattern.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export const CHAT_REFERENCE_UUID_PATTERN =
- '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceUuidRegex.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceUuidRegex.ts
new file mode 100644
index 00000000000..953c913d30d
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceUuidRegex.ts
@@ -0,0 +1,2 @@
+export const CHAT_REFERENCE_UUID_REGEX =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceViewPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceViewPattern.ts
deleted file mode 100644
index 2087aead5b5..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceViewPattern.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
-import { CHAT_REFERENCE_UUID_PATTERN } from '@/ai/constants/ChatReferenceUuidPattern';
-
-export const CHAT_REFERENCE_VIEW_PATTERN = `\\[\\[view:(?<viewId>${CHAT_REFERENCE_UUID_PATTERN}):(?<viewLabel>${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`;
diff --git a/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.ts b/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.ts
deleted file mode 100644
index d37a9f65b08..00000000000
--- a/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { useLocation } from 'react-router-dom';
-import { isNonEmptyString } from '@sniptt/guards';
-
-import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';
-import { useOpenRoutedPageInSidePanel } from '@/side-panel/routing/hooks/useOpenRoutedPageInSidePanel';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { isAiChatPath } from '~/utils/isAiChatPath';
-
-export const useChatReferenceTarget = (
- path: string | undefined,
- onOpenArtifact?: () => void,
-) => {
- const { pathname } = useLocation();
- const shouldOpenAiChatAfterOnboarding = useAtomStateValue(
- shouldOpenAiChatAfterOnboardingState,
- );
- const { openRoutedPageInSidePanel } = useOpenRoutedPageInSidePanel();
- const isArtifactSurface =
- isAiChatPath(pathname) && !shouldOpenAiChatAfterOnboarding;
-
- return {
- to: path,
- onClick:
- isNonEmptyString(path) && isArtifactSurface
- ? (onOpenArtifact ?? (() => openRoutedPageInSidePanel({ path })))
- : undefined,
- };
-};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx b/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
new file mode 100644
index 00000000000..d4e09d8389a
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
@@ -0,0 +1,231 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type ReactNode } from 'react';
+import { AppPath, SettingsPath } from 'twenty-shared/types';
+import {
+ assertUnreachable,
+ getAppPath,
+ getSettingsPath,
+ isDefined,
+} from 'twenty-shared/utils';
+import { AvatarOrIcon } from 'twenty-ui/data-display';
+import { IconApps, IconLock, useIcons } from 'twenty-ui/icon';
+import { useTheme } from 'twenty-ui/theme-constants';
+
+import { CHAT_REFERENCE_PERMISSION_FLAG_BY_KIND } from '@/ai/constants/ChatReferencePermissionFlagByKind';
+import { useIsAiChatArtifactSurface } from '@/ai/hooks/useIsAiChatArtifactSurface';
+import { type ChatReferenceMatch } from '@/ai/types/ChatReferenceMatch';
+import { ObjectMetadataIcon } from '@/object-metadata/components/ObjectMetadataIcon';
+import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
+import { objectMetadataItemsByIdMapSelector } from '@/object-metadata/states/objectMetadataItemsByIdMapSelector';
+import { getLinkToShowPage } from '@/object-metadata/utils/getLinkToShowPage';
+import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';
+import { useOpenRecordInSidePanel } from '@/side-panel/hooks/useOpenRecordInSidePanel';
+import { useOpenRoutedPageInSidePanel } from '@/side-panel/routing/hooks/useOpenRoutedPageInSidePanel';
+import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { useViewById } from '@/views/hooks/useViewById';
+
+const PROPOSED_OBJECT_METADATA_ICON = 'IconListNumbers';
+const PROPOSED_FIELD_METADATA_ICON = 'IconTag';
+
+type ChatReferenceDestination = {
+ path: string | undefined;
+ leftComponent: ReactNode;
+};
+
+type ChatReferenceTarget = ChatReferenceDestination & {
+ to: string | undefined;
+ onClick: (() => void) | undefined;
+};
+
+export const useChatReferenceTarget = (
+ reference: ChatReferenceMatch,
+): ChatReferenceTarget | null => {
+ const theme = useTheme();
+ const { getIcon } = useIcons();
+ const isAiChatArtifactSurface = useIsAiChatArtifactSurface();
+ const { openRecordInSidePanel } = useOpenRecordInSidePanel();
+ const { openRoutedPageInSidePanel } = useOpenRoutedPageInSidePanel();
+ const hasPermission = useHasPermissionFlag(
+ CHAT_REFERENCE_PERMISSION_FLAG_BY_KIND[reference.kind],
+ );
+ const objectMetadataItem = useAtomFamilySelectorValue(
+ objectMetadataItemFamilySelector,
+ {
+ objectName:
+ 'objectNameSingular' in reference ? reference.objectNameSingular : '',
+ objectNameType: 'singular',
+ },
+ );
+ const objectMetadataItemsByIdMap = useAtomStateValue(
+ objectMetadataItemsByIdMapSelector,
+ );
+ const { view } = useViewById(
+ reference.kind === 'view' ? reference.viewId : null,
+ );
+
+ const iconSize = theme.icon.size.sm;
+ const iconStroke = theme.icon.stroke.sm;
+
+ const resolveDestination = (): ChatReferenceDestination | null => {
+ switch (reference.kind) {
+ case 'record': {
+ if (
+ !isDefined(objectMetadataItem) ||
+ !isNonEmptyString(reference.recordId)
+ ) {
+ return null;
+ }
+
+ const recordPath = getLinkToShowPage(reference.objectNameSingular, {
+ id: reference.recordId,
+ });
+
+ return {
+ path: isNonEmptyString(recordPath) ? recordPath : undefined,
+ leftComponent: (
+ <AvatarOrIcon
+ placeholder={reference.displayName}
+ placeholderColorSeed={reference.recordId}
+ avatarType="rounded"
+ avatarUrl=""
+ />
+ ),
+ };
+ }
+ case 'records': {
+ const recordsObjectMetadataItem = objectMetadataItemsByIdMap.get(
+ reference.objectMetadataId,
+ );
+
+ if (!isDefined(recordsObjectMetadataItem)) {
+ return null;
+ }
+
+ return {
+ path: getAppPath(AppPath.RecordIndexPage, {
+ objectNamePlural: recordsObjectMetadataItem.namePlural,
+ }),
+ leftComponent: (
+ <ObjectMetadataIcon
+ objectMetadataItem={recordsObjectMetadataItem}
+ size={iconSize}
+ stroke={iconStroke}
+ />
+ ),
+ };
+ }
+ case 'object':
+ return {
+ path: isDefined(objectMetadataItem)
+ ? getSettingsPath(SettingsPath.ObjectDetail, {
+ objectNamePlural: objectMetadataItem.namePlural,
+ })
+ : undefined,
+ leftComponent: (
+ <ObjectMetadataIcon
+ objectMetadataItem={
+ objectMetadataItem ?? {
+ icon: PROPOSED_OBJECT_METADATA_ICON,
+ nameSingular: reference.objectNameSingular,
+ color: null,
+ isSystem: false,
+ }
+ }
+ size={iconSize}
+ stroke={iconStroke}
+ />
+ ),
+ };
+ case 'field': {
+ const fieldMetadataItem = objectMetadataItem?.fields.find(
+ (field) => field.name === reference.fieldName,
+ );
+ const Icon = getIcon(
+ fieldMetadataItem?.icon ?? PROPOSED_FIELD_METADATA_ICON,
+ );
+
+ return {
+ path:
+ isDefined(objectMetadataItem) && isDefined(fieldMetadataItem)
+ ? getSettingsPath(SettingsPath.ObjectFieldEdit, {
+ objectNamePlural: objectMetadataItem.namePlural,
+ fieldName: fieldMetadataItem.name,
+ })
+ : undefined,
+ leftComponent: <Icon size={iconSize} stroke={iconStroke} />,
+ };
+ }
+ case 'view': {
+ const viewObjectMetadataItem = isDefined(view)
+ ? objectMetadataItemsByIdMap.get(view.objectMetadataId)
+ : undefined;
+
+ if (!isDefined(view) || !isDefined(viewObjectMetadataItem)) {
+ return null;
+ }
+
+ const Icon = getIcon(view.icon);
+
+ return {
+ path: getAppPath(
+ AppPath.RecordIndexPage,
+ { objectNamePlural: viewObjectMetadataItem.namePlural },
+ { viewId: reference.viewId },
+ ),
+ leftComponent: <Icon size={iconSize} stroke={iconStroke} />,
+ };
+ }
+ case 'role':
+ return {
+ path: getSettingsPath(SettingsPath.RoleDetail, {
+ roleId: reference.roleId,
+ }),
+ leftComponent: <IconLock size={iconSize} stroke={iconStroke} />,
+ };
+ case 'app':
+ return {
+ path: getSettingsPath(SettingsPath.ApplicationDetail, {
+ applicationId: reference.applicationId,
+ }),
+ leftComponent: <IconApps size={iconSize} stroke={iconStroke} />,
+ };
+ default:
+ return assertUnreachable(reference);
+ }
+ };
+
+ const getOpenArtifact = (path: string): (() => void) | undefined => {
+ switch (reference.kind) {
+ case 'record':
+ return () =>
+ openRecordInSidePanel({
+ recordId: reference.recordId,
+ objectNameSingular: reference.objectNameSingular,
+ });
+ // The application settings page is not routed on the side panel, so
+ // its chip keeps navigating the way a plain link does.
+ case 'app':
+ return undefined;
+ default:
+ return () => openRoutedPageInSidePanel({ path });
+ }
+ };
+
+ const destination = resolveDestination();
+
+ if (!isDefined(destination)) {
+ return null;
+ }
+
+ const to = hasPermission ? destination.path : undefined;
+
+ return {
+ ...destination,
+ to,
+ onClick:
+ isAiChatArtifactSurface && isNonEmptyString(to)
+ ? getOpenArtifact(to)
+ : undefined,
+ };
+};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useChatTargetNavigation.ts b/packages/twenty-front/src/modules/ai/hooks/useChatTargetNavigation.ts
index 8509129f797..667a89175e7 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useChatTargetNavigation.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useChatTargetNavigation.ts
@@ -2,7 +2,7 @@ import { useStore } from 'jotai';
import { AppPath } from 'twenty-shared/types';
import { getAppPath, isDefined } from 'twenty-shared/utils';
-import { isAiChatArtifactSurface } from '@/ai/utils/isAiChatArtifactSurface';
+import { useIsAiChatArtifactSurface } from '@/ai/hooks/useIsAiChatArtifactSurface';
import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
import { useOpenRecordInSidePanel } from '@/side-panel/hooks/useOpenRecordInSidePanel';
import { useOpenRoutedPageInSidePanel } from '@/side-panel/routing/hooks/useOpenRoutedPageInSidePanel';
@@ -13,8 +13,7 @@ export const useChatTargetNavigation = () => {
const navigateApp = useNavigateApp();
const { openRecordInSidePanel } = useOpenRecordInSidePanel();
const { openRoutedPageInSidePanel } = useOpenRoutedPageInSidePanel();
-
- const isArtifactSurface = () => isAiChatArtifactSurface(store);
+ const isAiChatArtifactSurface = useIsAiChatArtifactSurface();
const openRecordTarget = ({
recordId,
@@ -23,7 +22,7 @@ export const useChatTargetNavigation = () => {
recordId: string;
objectNameSingular: string;
}) => {
- if (isArtifactSurface()) {
+ if (isAiChatArtifactSurface) {
openRecordInSidePanel({
recordId,
objectNameSingular,
@@ -63,7 +62,7 @@ export const useChatTargetNavigation = () => {
};
const recordIndexQueryParams = isDefined(viewId) ? { viewId } : undefined;
- if (isArtifactSurface()) {
+ if (isAiChatArtifactSurface) {
openRoutedPageInSidePanel({
path: getAppPath(
AppPath.RecordIndexPage,
diff --git a/packages/twenty-front/src/modules/ai/hooks/useIsAiChatArtifactSurface.ts b/packages/twenty-front/src/modules/ai/hooks/useIsAiChatArtifactSurface.ts
new file mode 100644
index 00000000000..723e95601d8
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/hooks/useIsAiChatArtifactSurface.ts
@@ -0,0 +1,17 @@
+import { useLocation } from 'react-router-dom';
+
+import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { isAiChatPath } from '~/utils/isAiChatPath';
+
+// Only the full page chat has room beside it for a side panel to act as an
+// artifact surface. The onboarding chat owns the whole screen, so what it
+// references opens as a page instead.
+export const useIsAiChatArtifactSurface = () => {
+ const { pathname } = useLocation();
+ const shouldOpenAiChatAfterOnboarding = useAtomStateValue(
+ shouldOpenAiChatAfterOnboardingState,
+ );
+
+ return isAiChatPath(pathname) && !shouldOpenAiChatAfterOnboarding;
+};
diff --git a/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts b/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts
index fe23202f639..6364a71ca79 100644
--- a/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts
+++ b/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts
@@ -3,7 +3,6 @@ export type ChatReferenceIdentity =
| { kind: 'records'; objectMetadataId: string }
| { kind: 'object'; objectNameSingular: string }
| { kind: 'field'; objectNameSingular: string; fieldName: string }
- | { kind: 'legacyFieldById'; fieldMetadataItemId: string }
| { kind: 'view'; viewId: string }
| { kind: 'role'; roleId: string }
| { kind: 'app'; applicationId: string };
diff --git a/packages/twenty-front/src/modules/ai/types/ChatReferenceKind.ts b/packages/twenty-front/src/modules/ai/types/ChatReferenceKind.ts
new file mode 100644
index 00000000000..7ee5e881d28
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/types/ChatReferenceKind.ts
@@ -0,0 +1,3 @@
+import { type ChatReferenceIdentity } from '@/ai/types/ChatReferenceIdentity';
+
+export type ChatReferenceKind = ChatReferenceIdentity['kind'];
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/findChatReferences.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/findChatReferences.test.ts
deleted file mode 100644
index 7f22d70b527..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/findChatReferences.test.ts
+++ /dev/null
@@ -1,336 +0,0 @@
-import { findChatReferences } from '@/ai/utils/findChatReferences';
-
-describe('findChatReferences', () => {
- it('should leave plain text without matches', () => {
- expect(findChatReferences('Which company should we contact?')).toEqual([]);
- });
-
- it('should find a record reference', () => {
- expect(
- findChatReferences(
- 'Contact [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme]] next',
- ),
- ).toEqual([
- {
- kind: 'record',
- fullMatch:
- '[[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme]]',
- index: 8,
- objectNameSingular: 'company',
- recordId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
- displayName: 'Acme',
- },
- ]);
- });
-
- it('should find a record reference written without the record prefix', () => {
- expect(
- findChatReferences(
- 'Merge [[person:11111111-1111-1111-1111-111111111111:Alice]] into [[record:person:22222222-2222-2222-2222-222222222222:Bob]]',
- ),
- ).toEqual([
- {
- kind: 'record',
- fullMatch: '[[person:11111111-1111-1111-1111-111111111111:Alice]]',
- index: 6,
- objectNameSingular: 'person',
- recordId: '11111111-1111-1111-1111-111111111111',
- displayName: 'Alice',
- },
- {
- kind: 'record',
- fullMatch: '[[record:person:22222222-2222-2222-2222-222222222222:Bob]]',
- index: 65,
- objectNameSingular: 'person',
- recordId: '22222222-2222-2222-2222-222222222222',
- displayName: 'Bob',
- },
- ]);
- });
-
- it('should find an object reference', () => {
- expect(
- findChatReferences('Open [[object:partner:Partners]] to start'),
- ).toEqual([
- {
- kind: 'object',
- fullMatch: '[[object:partner:Partners]]',
- index: 5,
- objectNameSingular: 'partner',
- displayName: 'Partners',
- },
- ]);
- });
-
- it('should find a field reference addressed by object and field name', () => {
- expect(findChatReferences('The [[field:person:role:Role]] field')).toEqual([
- {
- kind: 'field',
- fullMatch: '[[field:person:role:Role]]',
- index: 4,
- objectNameSingular: 'person',
- fieldName: 'role',
- displayName: 'Role',
- },
- ]);
- });
-
- it('should read a field reference addressed by id as the legacy kind', () => {
- expect(
- findChatReferences(
- 'The [[field:33333333-3333-3333-3333-333333333333:Stage]] field',
- ),
- ).toEqual([
- {
- kind: 'legacyFieldById',
- fullMatch: '[[field:33333333-3333-3333-3333-333333333333:Stage]]',
- index: 4,
- fieldMetadataItemId: '33333333-3333-3333-3333-333333333333',
- displayName: 'Stage',
- },
- ]);
- });
-
- it('should find a view reference instead of reading it as a record', () => {
- expect(
- findChatReferences(
- 'See [[view:44444444-4444-4444-4444-444444444444:All Companies]]',
- ),
- ).toEqual([
- {
- kind: 'view',
- fullMatch:
- '[[view:44444444-4444-4444-4444-444444444444:All Companies]]',
- index: 4,
- viewId: '44444444-4444-4444-4444-444444444444',
- displayName: 'All Companies',
- },
- ]);
- });
-
- it('should find a records reference by object metadata id', () => {
- expect(
- findChatReferences(
- 'Browse [[records:77777777-7777-4777-8777-777777777777:Companies]]',
- ),
- ).toEqual([
- {
- kind: 'records',
- fullMatch: '[[records:77777777-7777-4777-8777-777777777777:Companies]]',
- index: 7,
- objectMetadataId: '77777777-7777-4777-8777-777777777777',
- displayName: 'Companies',
- },
- ]);
- });
-
- it('should find role and app references instead of reading them as records', () => {
- expect(
- findChatReferences(
- 'Review [[role:55555555-5555-4555-8555-555555555555:Admin]] in [[app:66666666-6666-4666-8666-666666666666:Twenty]]',
- ),
- ).toEqual([
- {
- kind: 'role',
- fullMatch: '[[role:55555555-5555-4555-8555-555555555555:Admin]]',
- index: 7,
- roleId: '55555555-5555-4555-8555-555555555555',
- displayName: 'Admin',
- },
- {
- kind: 'app',
- fullMatch: '[[app:66666666-6666-4666-8666-666666666666:Twenty]]',
- index: 62,
- applicationId: '66666666-6666-4666-8666-666666666666',
- displayName: 'Twenty',
- },
- ]);
- });
-
- it('should read an explicit record prefix as a record even when the object is named view', () => {
- expect(
- findChatReferences(
- 'Open [[record:view:44444444-4444-4444-4444-444444444444:Quarterly]]',
- ),
- ).toEqual([
- {
- kind: 'record',
- fullMatch:
- '[[record:view:44444444-4444-4444-4444-444444444444:Quarterly]]',
- index: 5,
- objectNameSingular: 'view',
- recordId: '44444444-4444-4444-4444-444444444444',
- displayName: 'Quarterly',
- },
- ]);
- });
-
- it('should match object names containing digits', () => {
- expect(
- findChatReferences(
- '[[record:company2:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme]] and [[object:company2:Companies 2]]',
- ),
- ).toEqual([
- {
- kind: 'record',
- fullMatch:
- '[[record:company2:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme]]',
- index: 0,
- objectNameSingular: 'company2',
- recordId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
- displayName: 'Acme',
- },
- {
- kind: 'object',
- fullMatch: '[[object:company2:Companies 2]]',
- index: 66,
- objectNameSingular: 'company2',
- displayName: 'Companies 2',
- },
- ]);
- });
-
- it('should find every kind in a single string', () => {
- const references = findChatReferences(
- 'The [[view:44444444-4444-4444-4444-444444444444:Pipeline]] view of [[records:77777777-7777-4777-8777-777777777777:Companies]] uses the [[object:partner:Partners]] schema and groups [[record:person:11111111-1111-1111-1111-111111111111:Alice]] by [[field:33333333-3333-3333-3333-333333333333:Stage]] for [[role:55555555-5555-4555-8555-555555555555:Admin]] in [[app:66666666-6666-4666-8666-666666666666:Twenty]]',
- );
-
- expect(references.map((reference) => reference.kind)).toEqual([
- 'view',
- 'records',
- 'object',
- 'record',
- 'legacyFieldById',
- 'role',
- 'app',
- ]);
- expect(references.map((reference) => reference.displayName)).toEqual([
- 'Pipeline',
- 'Companies',
- 'Partners',
- 'Alice',
- 'Stage',
- 'Admin',
- 'Twenty',
- ]);
- });
-
- it('should find adjacent references without a separator', () => {
- const references = findChatReferences(
- '[[object:partner:Partners]][[object:company:Companies]]',
- );
-
- expect(references).toHaveLength(2);
- expect(references[0].displayName).toBe('Partners');
- expect(references[1].displayName).toBe('Companies');
- expect(references[1].index).toBe(27);
- });
-
- it('should find a reference with an empty display name', () => {
- expect(
- findChatReferences(
- '[[record:person:11111111-1111-1111-1111-111111111111:]]',
- ),
- ).toEqual([
- {
- kind: 'record',
- fullMatch: '[[record:person:11111111-1111-1111-1111-111111111111:]]',
- index: 0,
- objectNameSingular: 'person',
- recordId: '11111111-1111-1111-1111-111111111111',
- displayName: '',
- },
- ]);
- });
-
- it('should drop an unclosed reference', () => {
- expect(findChatReferences('Open [[object:partner:Partners')).toEqual([]);
- });
-
- it('should not treat a single bracket as a terminator', () => {
- expect(
- findChatReferences('Open [[object:partner:Partners] to start'),
- ).toEqual([]);
- });
-
- it('should not let an unclosed reference swallow the next one', () => {
- const references = findChatReferences(
- 'Open [[object:partner:Partners [[object:company:Companies]]',
- );
-
- expect(references).toHaveLength(1);
- expect(references[0].displayName).toBe('Companies');
- });
-
- it('should not close a reference across a line break', () => {
- expect(
- findChatReferences('Open [[object:partner:Partners\nand others]]'),
- ).toEqual([]);
- });
-
- it('should drop a reference whose display name contains brackets', () => {
- expect(
- findChatReferences(
- 'Open [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:[test] name]]',
- ),
- ).toEqual([]);
- });
-
- it('should drop a reference closed by a retired closing tag', () => {
- expect(
- findChatReferences(
- 'Contact [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme[[/record]] and [[object:partner:Partners[[/object]] and [[field:33333333-3333-3333-3333-333333333333:Stage[[/field]] and [[view:44444444-4444-4444-4444-444444444444:Pipeline[[/view]]',
- ),
- ).toEqual([]);
- });
-
- it('should leave a surplus bracket added after a reference out of the match', () => {
- expect(
- findChatReferences('Created [[object:opportunity:Opportunities]]].'),
- ).toEqual([
- {
- kind: 'object',
- fullMatch: '[[object:opportunity:Opportunities]]',
- index: 8,
- objectNameSingular: 'opportunity',
- displayName: 'Opportunities',
- },
- ]);
- });
-
- it('should find a reference whose display name contains markdown characters', () => {
- expect(
- findChatReferences(
- 'See [[record:workflow:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Workflow `UPDATE_RECORD` step]]',
- ),
- ).toEqual([
- {
- kind: 'record',
- fullMatch:
- '[[record:workflow:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Workflow `UPDATE_RECORD` step]]',
- index: 4,
- objectNameSingular: 'workflow',
- recordId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
- displayName: 'Workflow `UPDATE_RECORD` step',
- },
- ]);
- });
-
- it('should find a reference whose display name contains a colon', () => {
- expect(
- findChatReferences(
- 'Ping [[record:person:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Doe: Jane]]',
- ),
- ).toEqual([
- {
- kind: 'record',
- fullMatch:
- '[[record:person:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Doe: Jane]]',
- index: 5,
- objectNameSingular: 'person',
- recordId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
- displayName: 'Doe: Jane',
- },
- ]);
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/parseChatReferences.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/parseChatReferences.test.ts
new file mode 100644
index 00000000000..441000b3239
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/parseChatReferences.test.ts
@@ -0,0 +1,274 @@
+import { parseChatReferences } from '@/ai/utils/parseChatReferences';
+
+describe('parseChatReferences', () => {
+ it('should leave plain text without matches', () => {
+ expect(parseChatReferences('Which company should we contact?')).toEqual([]);
+ });
+
+ it.each([
+ {
+ name: 'a record',
+ text: 'Contact [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme]] next',
+ reference: {
+ kind: 'record',
+ fullMatch:
+ '[[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme]]',
+ index: 8,
+ objectNameSingular: 'company',
+ recordId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
+ displayName: 'Acme',
+ },
+ },
+ {
+ name: 'a record written without the record prefix',
+ text: 'Merge [[person:11111111-1111-1111-1111-111111111111:Alice]] first',
+ reference: {
+ kind: 'record',
+ fullMatch: '[[person:11111111-1111-1111-1111-111111111111:Alice]]',
+ index: 6,
+ objectNameSingular: 'person',
+ recordId: '11111111-1111-1111-1111-111111111111',
+ displayName: 'Alice',
+ },
+ },
+ {
+ name: 'a record whose object is named like a kind',
+ text: 'Open [[record:view:44444444-4444-4444-4444-444444444444:Quarterly]]',
+ reference: {
+ kind: 'record',
+ fullMatch:
+ '[[record:view:44444444-4444-4444-4444-444444444444:Quarterly]]',
+ index: 5,
+ objectNameSingular: 'view',
+ recordId: '44444444-4444-4444-4444-444444444444',
+ displayName: 'Quarterly',
+ },
+ },
+ {
+ name: 'a record of an object whose name contains digits',
+ text: '[[record:company2:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme]]',
+ reference: {
+ kind: 'record',
+ fullMatch:
+ '[[record:company2:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme]]',
+ index: 0,
+ objectNameSingular: 'company2',
+ recordId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
+ displayName: 'Acme',
+ },
+ },
+ {
+ name: 'a record with an empty display name',
+ text: '[[record:person:11111111-1111-1111-1111-111111111111:]]',
+ reference: {
+ kind: 'record',
+ fullMatch: '[[record:person:11111111-1111-1111-1111-111111111111:]]',
+ index: 0,
+ objectNameSingular: 'person',
+ recordId: '11111111-1111-1111-1111-111111111111',
+ displayName: '',
+ },
+ },
+ {
+ name: 'a record whose display name contains markdown characters',
+ text: 'See [[record:workflow:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Workflow `UPDATE_RECORD` step]]',
+ reference: {
+ kind: 'record',
+ fullMatch:
+ '[[record:workflow:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Workflow `UPDATE_RECORD` step]]',
+ index: 4,
+ objectNameSingular: 'workflow',
+ recordId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
+ displayName: 'Workflow `UPDATE_RECORD` step',
+ },
+ },
+ {
+ name: 'a record whose display name contains a colon',
+ text: 'Ping [[record:person:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Doe: Jane]]',
+ reference: {
+ kind: 'record',
+ fullMatch:
+ '[[record:person:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Doe: Jane]]',
+ index: 5,
+ objectNameSingular: 'person',
+ recordId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
+ displayName: 'Doe: Jane',
+ },
+ },
+ {
+ name: 'a records reference by object metadata id',
+ text: 'Browse [[records:77777777-7777-4777-8777-777777777777:Companies]]',
+ reference: {
+ kind: 'records',
+ fullMatch: '[[records:77777777-7777-4777-8777-777777777777:Companies]]',
+ index: 7,
+ objectMetadataId: '77777777-7777-4777-8777-777777777777',
+ displayName: 'Companies',
+ },
+ },
+ {
+ name: 'an object',
+ text: 'Open [[object:partner:Partners]] to start',
+ reference: {
+ kind: 'object',
+ fullMatch: '[[object:partner:Partners]]',
+ index: 5,
+ objectNameSingular: 'partner',
+ displayName: 'Partners',
+ },
+ },
+ {
+ name: 'an object followed by a surplus bracket',
+ text: 'Created [[object:opportunity:Opportunities]]].',
+ reference: {
+ kind: 'object',
+ fullMatch: '[[object:opportunity:Opportunities]]',
+ index: 8,
+ objectNameSingular: 'opportunity',
+ displayName: 'Opportunities',
+ },
+ },
+ {
+ name: 'a field addressed by object and field name',
+ text: 'The [[field:person:role:Role]] field',
+ reference: {
+ kind: 'field',
+ fullMatch: '[[field:person:role:Role]]',
+ index: 4,
+ objectNameSingular: 'person',
+ fieldName: 'role',
+ displayName: 'Role',
+ },
+ },
+ {
+ name: 'a view',
+ text: 'See [[view:44444444-4444-4444-4444-444444444444:All Companies]]',
+ reference: {
+ kind: 'view',
+ fullMatch:
+ '[[view:44444444-4444-4444-4444-444444444444:All Companies]]',
+ index: 4,
+ viewId: '44444444-4444-4444-4444-444444444444',
+ displayName: 'All Companies',
+ },
+ },
+ {
+ name: 'a view whose display name contains a colon',
+ text: 'See [[view:44444444-4444-4444-4444-444444444444:Q1: Pipeline]]',
+ reference: {
+ kind: 'view',
+ fullMatch: '[[view:44444444-4444-4444-4444-444444444444:Q1: Pipeline]]',
+ index: 4,
+ viewId: '44444444-4444-4444-4444-444444444444',
+ displayName: 'Q1: Pipeline',
+ },
+ },
+ {
+ name: 'a role',
+ text: 'Review [[role:55555555-5555-4555-8555-555555555555:Admin]]',
+ reference: {
+ kind: 'role',
+ fullMatch: '[[role:55555555-5555-4555-8555-555555555555:Admin]]',
+ index: 7,
+ roleId: '55555555-5555-4555-8555-555555555555',
+ displayName: 'Admin',
+ },
+ },
+ {
+ name: 'an app',
+ text: 'in [[app:66666666-6666-4666-8666-666666666666:Twenty]]',
+ reference: {
+ kind: 'app',
+ fullMatch: '[[app:66666666-6666-4666-8666-666666666666:Twenty]]',
+ index: 3,
+ applicationId: '66666666-6666-4666-8666-666666666666',
+ displayName: 'Twenty',
+ },
+ },
+ ])('should find $name', ({ text, reference }) => {
+ expect(parseChatReferences(text)).toEqual([reference]);
+ });
+
+ it('should find every kind in a single string', () => {
+ const references = parseChatReferences(
+ 'The [[view:44444444-4444-4444-4444-444444444444:Pipeline]] view of [[records:77777777-7777-4777-8777-777777777777:Companies]] uses the [[object:partner:Partners]] schema and groups [[record:person:11111111-1111-1111-1111-111111111111:Alice]] by [[field:person:stage:Stage]] for [[role:55555555-5555-4555-8555-555555555555:Admin]] in [[app:66666666-6666-4666-8666-666666666666:Twenty]]',
+ );
+
+ expect(references.map((reference) => reference.kind)).toEqual([
+ 'view',
+ 'records',
+ 'object',
+ 'record',
+ 'field',
+ 'role',
+ 'app',
+ ]);
+ expect(references.map((reference) => reference.displayName)).toEqual([
+ 'Pipeline',
+ 'Companies',
+ 'Partners',
+ 'Alice',
+ 'Stage',
+ 'Admin',
+ 'Twenty',
+ ]);
+ });
+
+ it('should find adjacent references without a separator', () => {
+ const references = parseChatReferences(
+ '[[object:partner:Partners]][[object:company:Companies]]',
+ );
+
+ expect(references).toHaveLength(2);
+ expect(references[0].displayName).toBe('Partners');
+ expect(references[1].displayName).toBe('Companies');
+ expect(references[1].index).toBe(27);
+ });
+
+ it('should not let an unclosed reference swallow the next one', () => {
+ const references = parseChatReferences(
+ 'Open [[object:partner:Partners [[object:company:Companies]]',
+ );
+
+ expect(references).toHaveLength(1);
+ expect(references[0].displayName).toBe('Companies');
+ });
+
+ it.each([
+ { name: 'an unclosed reference', text: 'Open [[object:partner:Partners' },
+ {
+ name: 'a reference closed by a single bracket',
+ text: 'Open [[object:partner:Partners] to start',
+ },
+ {
+ name: 'a reference closed across a line break',
+ text: 'Open [[object:partner:Partners\nand others]]',
+ },
+ {
+ name: 'a reference whose display name contains brackets',
+ text: 'Open [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:[test] name]]',
+ },
+ {
+ name: 'references closed by a retired closing tag',
+ text: 'Contact [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme[[/record]] and [[object:partner:Partners[[/object]] and [[field:person:stage:Stage[[/field]] and [[view:44444444-4444-4444-4444-444444444444:Pipeline[[/view]]',
+ },
+ {
+ name: 'a view whose id is not a uuid',
+ text: 'See [[view:pipeline:Pipeline]]',
+ },
+ {
+ name: 'a field missing its field name',
+ text: 'The [[field:person:Role]] field',
+ },
+ {
+ name: 'a record whose id is not a uuid',
+ text: 'Contact [[record:company:acme:Acme]]',
+ },
+ {
+ name: 'a retired field reference addressed by id',
+ text: 'Set [[field:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Amount]] first',
+ },
+ ])('should drop $name', ({ text }) => {
+ expect(parseChatReferences(text)).toEqual([]);
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/protectChatReferencesForMarkdown.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/protectChatReferencesForMarkdown.test.ts
index e4b9de471b1..d81695c8d2e 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/protectChatReferencesForMarkdown.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/protectChatReferencesForMarkdown.test.ts
@@ -55,14 +55,12 @@ describe('protectChatReferencesForMarkdown', () => {
).toBe('Open [[object:partner:Partners \\(EMEA\\)]]');
});
- it('should escape a field label without touching its id', () => {
+ it('should escape a field label without touching its names', () => {
expect(
protectChatReferencesForMarkdown(
- 'The [[field:33333333-3333-3333-3333-333333333333:Next step]] field',
+ 'The [[field:opportunity:nextStep:Next step (owner)]] field',
),
- ).toBe(
- 'The [[field:33333333-3333-3333-3333-333333333333:Next step]] field',
- );
+ ).toBe('The [[field:opportunity:nextStep:Next step \\(owner\\)]] field');
});
it('should escape a view label without touching its id', () => {
@@ -86,11 +84,9 @@ describe('protectChatReferencesForMarkdown', () => {
it('should leave a marker using a retired closing tag unchanged', () => {
expect(
protectChatReferencesForMarkdown(
- 'The [[field:33333333-3333-3333-3333-333333333333:Stage[[/field]] field',
+ 'The [[field:opportunity:stage:Stage[[/field]] field',
),
- ).toBe(
- 'The [[field:33333333-3333-3333-3333-333333333333:Stage[[/field]] field',
- );
+ ).toBe('The [[field:opportunity:stage:Stage[[/field]] field');
});
it('should keep a surplus bracket added after a reference', () => {
@@ -122,20 +118,20 @@ describe('protectChatReferencesForMarkdown', () => {
it('should keep only the display name of a marker matching no reference form', () => {
expect(
protectChatReferencesForMarkdown(
- '[[object:person:People]] gets [[field:person:lead source:Lead source]] and [[field:33333333-3333-3333-3333-333333333333:Stage]]',
+ '[[object:person:People]] gets [[field:person:lead source:Lead source]] and [[field:person:stage:Stage]]',
),
).toBe(
- '[[object:person:People]] gets Lead source and [[field:33333333-3333-3333-3333-333333333333:Stage]]',
+ '[[object:person:People]] gets Lead source and [[field:person:stage:Stage]]',
);
});
it('should rewrite every kind in a mixed string', () => {
expect(
protectChatReferencesForMarkdown(
- 'The [[view:44444444-4444-4444-4444-444444444444:Pipeline]] view of [[object:partner:Partners]] groups [[person:11111111-1111-1111-1111-111111111111:Alice]] by [[field:33333333-3333-3333-3333-333333333333:Stage]]',
+ 'The [[view:44444444-4444-4444-4444-444444444444:Pipeline]] view of [[object:partner:Partners]] groups [[person:11111111-1111-1111-1111-111111111111:Alice]] by [[field:person:stage:Stage]]',
),
).toBe(
- 'The [[view:44444444-4444-4444-4444-444444444444:Pipeline]] view of [[object:partner:Partners]] groups [[record:person:11111111-1111-1111-1111-111111111111:Alice]] by [[field:33333333-3333-3333-3333-333333333333:Stage]]',
+ 'The [[view:44444444-4444-4444-4444-444444444444:Pipeline]] view of [[object:partner:Partners]] groups [[record:person:11111111-1111-1111-1111-111111111111:Alice]] by [[field:person:stage:Stage]]',
);
});
});
diff --git a/packages/twenty-front/src/modules/ai/utils/findChatReferences.ts b/packages/twenty-front/src/modules/ai/utils/findChatReferences.ts
deleted file mode 100644
index 34cdb9f9730..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/findChatReferences.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { CHAT_REFERENCE_REGEX } from '@/ai/constants/ChatReferenceRegex';
-import { type ChatReferenceMatch } from '@/ai/types/ChatReferenceMatch';
-import { getChatReferenceMatchFromRegexMatch } from '@/ai/utils/getChatReferenceMatchFromRegexMatch';
-
-export const findChatReferences = (text: string): ChatReferenceMatch[] => {
- if (!text.includes('[[')) {
- return [];
- }
-
- return [...text.matchAll(CHAT_REFERENCE_REGEX)].map((match) =>
- getChatReferenceMatchFromRegexMatch(match),
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts b/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts
index 81304d27191..9ce2613f795 100644
--- a/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts
+++ b/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts
@@ -9,9 +9,5 @@ export const formatChatReference = (
return formatRecordReference(reference);
}
- if (reference.kind === 'legacyFieldById') {
- return `[[field:${getChatReferenceIdentitySegment(reference)}:${reference.displayName}]]`;
- }
-
return `[[${reference.kind}:${getChatReferenceIdentitySegment(reference)}:${reference.displayName}]]`;
};
diff --git a/packages/twenty-front/src/modules/ai/utils/getChatReferenceIdentitySegment.ts b/packages/twenty-front/src/modules/ai/utils/getChatReferenceIdentitySegment.ts
index b13d9463cee..96df9306385 100644
--- a/packages/twenty-front/src/modules/ai/utils/getChatReferenceIdentitySegment.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getChatReferenceIdentitySegment.ts
@@ -13,8 +13,6 @@ export const getChatReferenceIdentitySegment = (
return identity.objectNameSingular;
case 'field':
return `${identity.objectNameSingular}:${identity.fieldName}`;
- case 'legacyFieldById':
- return identity.fieldMetadataItemId;
case 'view':
return identity.viewId;
case 'role':
diff --git a/packages/twenty-front/src/modules/ai/utils/getChatReferenceMatchFromRegexMatch.ts b/packages/twenty-front/src/modules/ai/utils/getChatReferenceMatchFromRegexMatch.ts
deleted file mode 100644
index b3fbe959e5d..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/getChatReferenceMatchFromRegexMatch.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { type ChatReferenceMatch } from '@/ai/types/ChatReferenceMatch';
-import { isDefined } from 'twenty-shared/utils';
-
-export const getChatReferenceMatchFromRegexMatch = (
- match: RegExpExecArray,
-): ChatReferenceMatch => {
- const {
- objectNameSingular,
- objectLabel,
- objectMetadataId,
- recordsLabel,
- fieldObjectNameSingular,
- fieldName,
- fieldLabel,
- legacyFieldMetadataItemId,
- legacyFieldLabel,
- viewId,
- viewLabel,
- roleId,
- roleLabel,
- applicationId,
- applicationLabel,
- recordObjectNameSingular,
- recordId,
- recordLabel,
- } = match.groups ?? {};
-
- const position = { fullMatch: match[0], index: match.index };
-
- if (isDefined(objectNameSingular)) {
- return {
- ...position,
- kind: 'object',
- objectNameSingular,
- displayName: objectLabel,
- };
- }
-
- if (isDefined(objectMetadataId)) {
- return {
- ...position,
- kind: 'records',
- objectMetadataId,
- displayName: recordsLabel,
- };
- }
-
- if (isDefined(fieldObjectNameSingular)) {
- return {
- ...position,
- kind: 'field',
- objectNameSingular: fieldObjectNameSingular,
- fieldName,
- displayName: fieldLabel,
- };
- }
-
- if (isDefined(legacyFieldMetadataItemId)) {
- return {
- ...position,
- kind: 'legacyFieldById',
- fieldMetadataItemId: legacyFieldMetadataItemId,
- displayName: legacyFieldLabel,
- };
- }
-
- if (isDefined(viewId)) {
- return {
- ...position,
- kind: 'view',
- viewId,
- displayName: viewLabel,
- };
- }
-
- if (isDefined(roleId)) {
- return {
- ...position,
- kind: 'role',
- roleId,
- displayName: roleLabel,
- };
- }
-
- if (isDefined(applicationId)) {
- return {
- ...position,
- kind: 'app',
- applicationId,
- displayName: applicationLabel,
- };
- }
-
- return {
- ...position,
- kind: 'record',
- objectNameSingular: recordObjectNameSingular,
- recordId,
- displayName: recordLabel,
- };
-};
diff --git a/packages/twenty-front/src/modules/ai/utils/getChatReferenceSegments.ts b/packages/twenty-front/src/modules/ai/utils/getChatReferenceSegments.ts
index b8583bd8946..8385d49487b 100644
--- a/packages/twenty-front/src/modules/ai/utils/getChatReferenceSegments.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getChatReferenceSegments.ts
@@ -1,11 +1,11 @@
import { type ChatReferenceMatch } from '@/ai/types/ChatReferenceMatch';
-import { findChatReferences } from '@/ai/utils/findChatReferences';
+import { parseChatReferences } from '@/ai/utils/parseChatReferences';
import { replaceMalformedChatReferencesWithDisplayName } from '@/ai/utils/replaceMalformedChatReferencesWithDisplayName';
export const getChatReferenceSegments = (
text: string,
): Array<string | ChatReferenceMatch> => {
- const references = findChatReferences(text);
+ const references = parseChatReferences(text);
const segments: Array<string | ChatReferenceMatch> = [];
let lastIndex = 0;
diff --git a/packages/twenty-front/src/modules/ai/utils/isAiChatArtifactSurface.ts b/packages/twenty-front/src/modules/ai/utils/isAiChatArtifactSurface.ts
deleted file mode 100644
index 2d744b36ba9..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/isAiChatArtifactSurface.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { type getDefaultStore } from 'jotai';
-
-import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';
-import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';
-
-// Only the full page chat has room beside it for a side panel to act as an
-// artifact surface. The onboarding chat owns the whole screen, so what it
-// references opens as a page instead.
-export const isAiChatArtifactSurface = (
- store: ReturnType<typeof getDefaultStore>,
-) =>
- isCurrentPathAiChatPage() &&
- !store.get(shouldOpenAiChatAfterOnboardingState.atom);
diff --git a/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts b/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts
new file mode 100644
index 00000000000..6664c3b4a98
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts
@@ -0,0 +1,84 @@
+import { CHAT_REFERENCE_IDENTITY_SHAPE_BY_KIND } from '@/ai/constants/ChatReferenceIdentityShapeByKind';
+import { type ChatReferenceIdentity } from '@/ai/types/ChatReferenceIdentity';
+import { type ChatReferenceKind } from '@/ai/types/ChatReferenceKind';
+import { assertUnreachable } from 'twenty-shared/utils';
+
+type ParsedChatReferenceBody = ChatReferenceIdentity & { displayName: string };
+
+const isChatReferenceKind = (segment: string): segment is ChatReferenceKind =>
+ Object.hasOwn(CHAT_REFERENCE_IDENTITY_SHAPE_BY_KIND, segment);
+
+const getChatReferenceIdentity = ({
+ kind,
+ segments: [firstSegment, secondSegment],
+}: {
+ kind: ChatReferenceKind;
+ segments: string[];
+}): ChatReferenceIdentity => {
+ switch (kind) {
+ case 'record':
+ return {
+ kind,
+ objectNameSingular: firstSegment,
+ recordId: secondSegment,
+ };
+ case 'records':
+ return { kind, objectMetadataId: firstSegment };
+ case 'object':
+ return { kind, objectNameSingular: firstSegment };
+ case 'field':
+ return {
+ kind,
+ objectNameSingular: firstSegment,
+ fieldName: secondSegment,
+ };
+ case 'view':
+ return { kind, viewId: firstSegment };
+ case 'role':
+ return { kind, roleId: firstSegment };
+ case 'app':
+ return { kind, applicationId: firstSegment };
+ default:
+ return assertUnreachable(kind);
+ }
+};
+
+const parseSegments = ({
+ kind,
+ segments,
+}: {
+ kind: ChatReferenceKind;
+ segments: string[];
+}): ParsedChatReferenceBody | undefined => {
+ const shape = CHAT_REFERENCE_IDENTITY_SHAPE_BY_KIND[kind];
+ const identitySegments = segments.slice(0, shape.length);
+ const hasLabel = segments.length > shape.length;
+
+ if (
+ !hasLabel ||
+ !shape.every((regex, index) => regex.test(identitySegments[index]))
+ ) {
+ return undefined;
+ }
+
+ return {
+ ...getChatReferenceIdentity({ kind, segments: identitySegments }),
+ displayName: segments.slice(shape.length).join(':'),
+ };
+};
+
+export const parseChatReferenceBody = (
+ body: string,
+): ParsedChatReferenceBody | undefined => {
+ const segments = body.split(':');
+ const [kindPrefix, ...identityAndLabel] = segments;
+
+ // A recognised prefix followed by an identity of the wrong shape is a
+ // retired or malformed marker, not a record of an object bearing that
+ // name, so it must not fall through to the unprefixed record form.
+ if (isChatReferenceKind(kindPrefix)) {
+ return parseSegments({ kind: kindPrefix, segments: identityAndLabel });
+ }
+
+ return parseSegments({ kind: 'record', segments });
+};
diff --git a/packages/twenty-front/src/modules/ai/utils/parseChatReferences.ts b/packages/twenty-front/src/modules/ai/utils/parseChatReferences.ts
new file mode 100644
index 00000000000..e47f546eacd
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/parseChatReferences.ts
@@ -0,0 +1,18 @@
+import { CHAT_REFERENCE_REGEX } from '@/ai/constants/ChatReferenceRegex';
+import { type ChatReferenceMatch } from '@/ai/types/ChatReferenceMatch';
+import { parseChatReferenceBody } from '@/ai/utils/parseChatReferenceBody';
+import { isDefined } from 'twenty-shared/utils';
+
+export const parseChatReferences = (text: string): ChatReferenceMatch[] => {
+ if (!text.includes('[[')) {
+ return [];
+ }
+
+ return [...text.matchAll(CHAT_REFERENCE_REGEX)].flatMap((match) => {
+ const reference = parseChatReferenceBody(match[1]);
+
+ return isDefined(reference)
+ ? [{ ...reference, fullMatch: match[0], index: match.index }]
+ : [];
+ });
+};