Skip to content

The open alternative to Salesforce, designed for AI.

feat(ai-chat): address field references by name (#24701)

Etiennee966b5d526f0
diff --git a/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx b/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx
index 81573032b1b..c8140474c09 100644
--- a/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx
+++ b/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx
@@ -1,4 +1,5 @@
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 { ViewLink } from '@/ai/components/ViewLink';
@@ -29,6 +30,14 @@ export const ChatReferenceChip = ({ reference }: ChatReferenceChipProps) => {
case 'field':
return (
<FieldMetadataLink
+ objectNameSingular={reference.objectNameSingular}
+ fieldName={reference.fieldName}
+ displayName={reference.displayName}
+ />
+ );
+ case 'legacyFieldById':
+ return (
+ <DeprecatedFieldMetadataLinkById
fieldMetadataItemId={reference.fieldMetadataItemId}
displayName={reference.displayName}
/>
diff --git a/packages/twenty-front/src/modules/ai/components/DeprecatedFieldMetadataLinkById.tsx b/packages/twenty-front/src/modules/ai/components/DeprecatedFieldMetadataLinkById.tsx
new file mode 100644
index 00000000000..631e7605c8f
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/DeprecatedFieldMetadataLinkById.tsx
@@ -0,0 +1,42 @@
+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
new file mode 100644
index 00000000000..007276cf7cc
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/FieldMetadataChip.tsx
@@ -0,0 +1,51 @@
+import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';
+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);
+
+ return (
+ <ChatReferenceChipDisplay
+ displayName={displayName}
+ to={
+ isDefined(objectMetadataItem) &&
+ isDefined(fieldMetadataItem) &&
+ hasDataModelPermission
+ ? getSettingsPath(SettingsPath.ObjectFieldEdit, {
+ objectNamePlural: objectMetadataItem.namePlural,
+ fieldName: fieldMetadataItem.name,
+ })
+ : undefined
+ }
+ 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
index 7074e2caeb6..3dc31a942e8 100644
--- a/packages/twenty-front/src/modules/ai/components/FieldMetadataLink.tsx
+++ b/packages/twenty-front/src/modules/ai/components/FieldMetadataLink.tsx
@@ -1,57 +1,35 @@
-import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';
-import { fieldMetadataItemByIdSelector } from '@/object-metadata/states/fieldMetadataItemByIdSelector';
-import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';
+import { FieldMetadataChip } from '@/ai/components/FieldMetadataChip';
+import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
-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';
type FieldMetadataLinkProps = {
- fieldMetadataItemId: string;
+ objectNameSingular: string;
+ fieldName: string;
displayName: string;
};
export const FieldMetadataLink = ({
- fieldMetadataItemId,
+ objectNameSingular,
+ fieldName,
displayName,
}: FieldMetadataLinkProps) => {
- const theme = useTheme();
- const { getIcon } = useIcons();
-
- const { foundFieldMetadataItem, foundObjectMetadataItem } =
- useAtomFamilySelectorValue(fieldMetadataItemByIdSelector, {
- fieldMetadataItemId,
- });
-
- const hasDataModelPermission = useHasPermissionFlag(
- PermissionFlagType.DATA_MODEL,
+ const objectMetadataItem = useAtomFamilySelectorValue(
+ objectMetadataItemFamilySelector,
+ {
+ objectName: objectNameSingular,
+ objectNameType: 'singular',
+ },
);
- if (
- !isDefined(foundFieldMetadataItem) ||
- !isDefined(foundObjectMetadataItem)
- ) {
- return <span>{displayName}</span>;
- }
-
- const Icon = getIcon(foundFieldMetadataItem.icon);
+ const fieldMetadataItem = objectMetadataItem?.fields.find(
+ (field) => field.name === fieldName,
+ );
return (
- <ChatReferenceChipDisplay
+ <FieldMetadataChip
displayName={displayName}
- to={
- hasDataModelPermission
- ? getSettingsPath(SettingsPath.ObjectFieldEdit, {
- objectNamePlural: foundObjectMetadataItem.namePlural,
- fieldName: foundFieldMetadataItem.name,
- })
- : undefined
- }
- leftComponent={
- <Icon size={theme.icon.size.sm} stroke={theme.icon.stroke.sm} />
- }
+ objectMetadataItem={objectMetadataItem}
+ fieldMetadataItem={fieldMetadataItem}
/>
);
};
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
index 63d878b4a60..d0eba018413 100644
--- a/packages/twenty-front/src/modules/ai/components/__stories__/ChatReferenceChip.stories.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/ChatReferenceChip.stories.tsx
@@ -84,7 +84,7 @@ export const ExistingMetadata: Story = {
objectNameSingular: 'company',
displayName: 'Companies',
})} object is sorted by ${formatChatReference({
- kind: 'field',
+ kind: 'legacyFieldById',
fieldMetadataItemId: employeesFieldMetadataItem.id,
displayName: 'Employees',
})} in the ${formatChatReference({
@@ -113,6 +113,41 @@ export const ExistingMetadata: Story = {
},
};
+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(
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/FieldMetadataLink.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/DeprecatedFieldMetadataLinkById.test.tsx
similarity index 87%
rename from packages/twenty-front/src/modules/ai/components/__tests__/FieldMetadataLink.test.tsx
rename to packages/twenty-front/src/modules/ai/components/__tests__/DeprecatedFieldMetadataLinkById.test.tsx
index b84e7439a70..32ac5fcad9d 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/FieldMetadataLink.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/DeprecatedFieldMetadataLinkById.test.tsx
@@ -1,7 +1,7 @@
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
-import { FieldMetadataLink } from '@/ai/components/FieldMetadataLink';
+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';
@@ -27,7 +27,7 @@ const setPermissionFlags = (
});
};
-const renderFieldMetadataLink = ({
+const renderDeprecatedFieldMetadataLinkById = ({
fieldMetadataItemId,
displayName,
permissionFlags,
@@ -44,7 +44,7 @@ const renderFieldMetadataLink = ({
return render(
<MemoryRouter>
- <FieldMetadataLink
+ <DeprecatedFieldMetadataLinkById
fieldMetadataItemId={fieldMetadataItemId}
displayName={displayName}
/>
@@ -53,9 +53,9 @@ const renderFieldMetadataLink = ({
);
};
-describe('FieldMetadataLink', () => {
+describe('DeprecatedFieldMetadataLinkById', () => {
it('should link a field to its settings page', () => {
- renderFieldMetadataLink({
+ renderDeprecatedFieldMetadataLinkById({
fieldMetadataItemId: nameFieldMetadataItem.id,
displayName: 'Name',
permissionFlags: [PermissionFlagType.DATA_MODEL],
@@ -68,7 +68,7 @@ describe('FieldMetadataLink', () => {
});
it('should render a chip without a link when the user cannot access the data model', () => {
- renderFieldMetadataLink({
+ renderDeprecatedFieldMetadataLinkById({
fieldMetadataItemId: nameFieldMetadataItem.id,
displayName: 'Name',
permissionFlags: [],
@@ -79,7 +79,7 @@ describe('FieldMetadataLink', () => {
});
it('should render plain text for an unknown field id', () => {
- renderFieldMetadataLink({
+ renderDeprecatedFieldMetadataLinkById({
fieldMetadataItemId: '33333333-3333-3333-3333-333333333333',
displayName: 'Partner type',
permissionFlags: [PermissionFlagType.DATA_MODEL],
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
index 96fb0be7456..46410395f4b 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/TextWithChatReferences.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/TextWithChatReferences.test.tsx
@@ -34,13 +34,32 @@ jest.mock('@/ai/components/ObjectMetadataLink', () => ({
jest.mock('@/ai/components/FieldMetadataLink', () => ({
FieldMetadataLink: ({
+ objectNameSingular,
+ fieldName,
displayName,
- fieldMetadataItemId,
}: {
+ 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="field-link" href={`/fields/${fieldMetadataItemId}`}>
+ <a data-testid="legacy-field-link" href={`/fields/${fieldMetadataItemId}`}>
{displayName}
</a>
),
@@ -117,6 +136,18 @@ describe('TextWithChatReferences', () => {
);
});
+ 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 [[object:partner:Partners]] groups [[record:person:11111111-1111-1111-1111-111111111111:Alice]] by [[field:33333333-3333-3333-3333-333333333333:Stage]]" />,
@@ -131,7 +162,7 @@ describe('TextWithChatReferences', () => {
'/objects/partner',
);
expect(screen.getByTestId('record-link')).toHaveTextContent('Alice');
- expect(screen.getByTestId('field-link')).toHaveAttribute(
+ expect(screen.getByTestId('legacy-field-link')).toHaveAttribute(
'href',
'/fields/33333333-3333-3333-3333-333333333333',
);
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceFieldPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceFieldPattern.ts
index 7040fbe2d4b..3c523e8bf61 100644
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceFieldPattern.ts
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceFieldPattern.ts
@@ -1,4 +1,4 @@
import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
-import { CHAT_REFERENCE_UUID_PATTERN } from '@/ai/constants/ChatReferenceUuidPattern';
+import { CHAT_REFERENCE_METADATA_NAME_PATTERN } from '@/ai/constants/ChatReferenceMetadataNamePattern';
-export const CHAT_REFERENCE_FIELD_PATTERN = `\\[\\[field:(?<fieldMetadataItemId>${CHAT_REFERENCE_UUID_PATTERN}):(?<fieldLabel>${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`;
+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/ChatReferenceLegacyFieldByIdPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceLegacyFieldByIdPattern.ts
new file mode 100644
index 00000000000..0bab88ee9c3
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceLegacyFieldByIdPattern.ts
@@ -0,0 +1,4 @@
+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
new file mode 100644
index 00000000000..b7c8e358b8a
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceMalformedRegex.ts
@@ -0,0 +1,6 @@
+import { CHAT_REFERENCE_LABEL_PATTERN } from '@/ai/constants/ChatReferenceLabelPattern';
+
+export const CHAT_REFERENCE_MALFORMED_REGEX = new RegExp(
+ `\\[\\[(?:record|object|field|view):(${CHAT_REFERENCE_LABEL_PATTERN})\\]\\]`,
+ 'g',
+);
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceRegex.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceRegex.ts
index 1166c138261..9ee9c91a728 100644
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceRegex.ts
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceRegex.ts
@@ -1,4 +1,5 @@
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_VIEW_PATTERN } from '@/ai/constants/ChatReferenceViewPattern';
@@ -9,6 +10,7 @@ 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_RECORD_PATTERN,
].join('|'),
diff --git a/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts b/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts
index 3b94c825c43..268ecc9aba1 100644
--- a/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts
+++ b/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts
@@ -1,5 +1,6 @@
export type ChatReferenceIdentity =
| { kind: 'record'; objectNameSingular: string; recordId: string }
| { kind: 'object'; objectNameSingular: string }
- | { kind: 'field'; fieldMetadataItemId: string }
+ | { kind: 'field'; objectNameSingular: string; fieldName: string }
+ | { kind: 'legacyFieldById'; fieldMetadataItemId: string }
| { kind: 'view'; viewId: string };
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
index b163e88e14e..c07b6e586ef 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/findChatReferences.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/findChatReferences.test.ts
@@ -62,14 +62,27 @@ describe('findChatReferences', () => {
]);
});
- it('should find a field reference instead of reading it as a record', () => {
+ 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: 'field',
+ kind: 'legacyFieldById',
fullMatch: '[[field:33333333-3333-3333-3333-333333333333:Stage]]',
index: 4,
fieldMetadataItemId: '33333333-3333-3333-3333-333333333333',
@@ -147,7 +160,7 @@ describe('findChatReferences', () => {
'view',
'object',
'record',
- 'field',
+ 'legacyFieldById',
]);
expect(references.map((reference) => reference.displayName)).toEqual([
'Pipeline',
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 ea18219872d..e4b9de471b1 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
@@ -101,6 +101,34 @@ describe('protectChatReferencesForMarkdown', () => {
).toBe('Created [[object:opportunity:Opportunities]]].');
});
+ it('should leave a proposed field reference unchanged', () => {
+ expect(
+ protectChatReferencesForMarkdown(
+ 'add [[field:person:role:Role]] and [[field:person:leadSource:Lead source]]',
+ ),
+ ).toBe(
+ 'add [[field:person:role:Role]] and [[field:person:leadSource:Lead source]]',
+ );
+ });
+
+ it('should keep only the display name when the text is a single malformed marker', () => {
+ expect(
+ protectChatReferencesForMarkdown(
+ '[[field:person:lead source:Lead source]]',
+ ),
+ ).toBe('Lead source');
+ });
+
+ 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]]',
+ ),
+ ).toBe(
+ '[[object:person:People]] gets Lead source and [[field:33333333-3333-3333-3333-333333333333:Stage]]',
+ );
+ });
+
it('should rewrite every kind in a mixed string', () => {
expect(
protectChatReferencesForMarkdown(
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/replaceMalformedChatReferencesWithDisplayName.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/replaceMalformedChatReferencesWithDisplayName.test.ts
new file mode 100644
index 00000000000..202fbcbf295
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/replaceMalformedChatReferencesWithDisplayName.test.ts
@@ -0,0 +1,47 @@
+import { replaceMalformedChatReferencesWithDisplayName } from '@/ai/utils/replaceMalformedChatReferencesWithDisplayName';
+
+describe('replaceMalformedChatReferencesWithDisplayName', () => {
+ it('should leave plain text unchanged', () => {
+ expect(
+ replaceMalformedChatReferencesWithDisplayName('Add a role field'),
+ ).toBe('Add a role field');
+ });
+
+ it('should keep the display name of a field name no reference form accepts', () => {
+ expect(
+ replaceMalformedChatReferencesWithDisplayName(
+ 'add [[field:person:lead source:Lead source]] so the team can segment contacts',
+ ),
+ ).toBe('add Lead source so the team can segment contacts');
+ });
+
+ it('should keep the display name of every malformed reference kind', () => {
+ expect(
+ replaceMalformedChatReferencesWithDisplayName(
+ '[[object:person:sub:People]] [[view:pipeline:Pipeline]] [[record:company:acme:Acme]]',
+ ),
+ ).toBe('People Pipeline Acme');
+ });
+
+ it('should leave a marker carrying no display name unchanged', () => {
+ expect(
+ replaceMalformedChatReferencesWithDisplayName(
+ 'see [[field:33333333-3333-3333-3333-333333333333]] here',
+ ),
+ ).toBe('see [[field:33333333-3333-3333-3333-333333333333]] here');
+ });
+
+ it('should leave an unclosed reference unchanged', () => {
+ expect(
+ replaceMalformedChatReferencesWithDisplayName(
+ 'add [[field:person:role:Role and more',
+ ),
+ ).toBe('add [[field:person:role:Role and more');
+ });
+
+ it('should leave a marker without a known kind unchanged', () => {
+ expect(
+ replaceMalformedChatReferencesWithDisplayName('see [[some note]] here'),
+ ).toBe('see [[some note]] here');
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts b/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts
index 9ce2613f795..81304d27191 100644
--- a/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts
+++ b/packages/twenty-front/src/modules/ai/utils/formatChatReference.ts
@@ -9,5 +9,9 @@ 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 f36c18eee56..0df18a7bf07 100644
--- a/packages/twenty-front/src/modules/ai/utils/getChatReferenceIdentitySegment.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getChatReferenceIdentitySegment.ts
@@ -10,6 +10,8 @@ export const getChatReferenceIdentitySegment = (
case 'object':
return identity.objectNameSingular;
case 'field':
+ return `${identity.objectNameSingular}:${identity.fieldName}`;
+ case 'legacyFieldById':
return identity.fieldMetadataItemId;
case 'view':
return identity.viewId;
diff --git a/packages/twenty-front/src/modules/ai/utils/getChatReferenceMatchFromRegexMatch.ts b/packages/twenty-front/src/modules/ai/utils/getChatReferenceMatchFromRegexMatch.ts
index 7b0c7fa8048..687f3561939 100644
--- a/packages/twenty-front/src/modules/ai/utils/getChatReferenceMatchFromRegexMatch.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getChatReferenceMatchFromRegexMatch.ts
@@ -7,8 +7,11 @@ export const getChatReferenceMatchFromRegexMatch = (
const {
objectNameSingular,
objectLabel,
- fieldMetadataItemId,
+ fieldObjectNameSingular,
+ fieldName,
fieldLabel,
+ legacyFieldMetadataItemId,
+ legacyFieldLabel,
viewId,
viewLabel,
recordObjectNameSingular,
@@ -27,15 +30,25 @@ export const getChatReferenceMatchFromRegexMatch = (
};
}
- if (isDefined(fieldMetadataItemId)) {
+ if (isDefined(fieldObjectNameSingular)) {
return {
...position,
kind: 'field',
- fieldMetadataItemId,
+ objectNameSingular: fieldObjectNameSingular,
+ fieldName,
displayName: fieldLabel,
};
}
+ if (isDefined(legacyFieldMetadataItemId)) {
+ return {
+ ...position,
+ kind: 'legacyFieldById',
+ fieldMetadataItemId: legacyFieldMetadataItemId,
+ displayName: legacyFieldLabel,
+ };
+ }
+
if (isDefined(viewId)) {
return {
...position,
diff --git a/packages/twenty-front/src/modules/ai/utils/getChatReferenceSegments.ts b/packages/twenty-front/src/modules/ai/utils/getChatReferenceSegments.ts
index 0c04cc918eb..b8583bd8946 100644
--- a/packages/twenty-front/src/modules/ai/utils/getChatReferenceSegments.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getChatReferenceSegments.ts
@@ -1,5 +1,6 @@
import { type ChatReferenceMatch } from '@/ai/types/ChatReferenceMatch';
import { findChatReferences } from '@/ai/utils/findChatReferences';
+import { replaceMalformedChatReferencesWithDisplayName } from '@/ai/utils/replaceMalformedChatReferencesWithDisplayName';
export const getChatReferenceSegments = (
text: string,
@@ -10,7 +11,11 @@ export const getChatReferenceSegments = (
for (const reference of references) {
if (reference.index > lastIndex) {
- segments.push(text.slice(lastIndex, reference.index));
+ segments.push(
+ replaceMalformedChatReferencesWithDisplayName(
+ text.slice(lastIndex, reference.index),
+ ),
+ );
}
segments.push(reference);
@@ -18,7 +23,9 @@ export const getChatReferenceSegments = (
}
if (lastIndex < text.length) {
- segments.push(text.slice(lastIndex));
+ segments.push(
+ replaceMalformedChatReferencesWithDisplayName(text.slice(lastIndex)),
+ );
}
return segments;
diff --git a/packages/twenty-front/src/modules/ai/utils/protectChatReferencesForMarkdown.ts b/packages/twenty-front/src/modules/ai/utils/protectChatReferencesForMarkdown.ts
index 2c3f89fbe25..413f0e3784c 100644
--- a/packages/twenty-front/src/modules/ai/utils/protectChatReferencesForMarkdown.ts
+++ b/packages/twenty-front/src/modules/ai/utils/protectChatReferencesForMarkdown.ts
@@ -6,7 +6,7 @@ export const protectChatReferencesForMarkdown = (text: string): string => {
const segments = getChatReferenceSegments(text);
if (segments.length === 1 && typeof segments[0] === 'string') {
- return text;
+ return segments[0];
}
return segments
diff --git a/packages/twenty-front/src/modules/ai/utils/replaceMalformedChatReferencesWithDisplayName.ts b/packages/twenty-front/src/modules/ai/utils/replaceMalformedChatReferencesWithDisplayName.ts
new file mode 100644
index 00000000000..8b28ef9b76d
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/replaceMalformedChatReferencesWithDisplayName.ts
@@ -0,0 +1,20 @@
+import { CHAT_REFERENCE_MALFORMED_REGEX } from '@/ai/constants/ChatReferenceMalformedRegex';
+
+export const replaceMalformedChatReferencesWithDisplayName = (
+ text: string,
+): string => {
+ if (!text.includes('[[')) {
+ return text;
+ }
+
+ return text.replace(
+ CHAT_REFERENCE_MALFORMED_REGEX,
+ (fullMatch: string, payload: string) => {
+ const lastSeparatorIndex = payload.lastIndexOf(':');
+
+ return lastSeparatorIndex === -1
+ ? fullMatch
+ : payload.slice(lastSeparatorIndex + 1);
+ },
+ );
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.ts
index f46c83eba81..4e5362d374d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/__tests__/workspace-setup-system-prompt.constant.spec.ts
@@ -251,7 +251,9 @@ describe('WORKSPACE_SETUP_SYSTEM_PROMPT', () => {
it('should require a title per reply and chips for objects', () => {
expect(prompt).toContain('Open each reply with a short plain title');
expect(prompt).toContain('title each new step');
- expect(prompt).toContain('Write objects as chips');
+ expect(prompt).toContain('Write objects and fields as chips');
+ expect(prompt).toContain('including the ones you have not created yet');
+ expect(prompt).toContain('each written as a chip');
});
it('should carry the ask_questions shape rules the base prompt no longer provides', () => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const.ts
index a389908dff3..bac0b031571 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const.ts
@@ -89,17 +89,19 @@ Whenever you name an object, a field, or a view in your prose, write it as a met
- Object: [[object:objectNameSingular:displayName]]
- Example: [[object:company:Companies]]
- Use the \`nameSingular\` from \`get_object_metadata\` or \`create_object_metadata\` (NOT the label, NOT the plural, NOT the id)
- - This is the only reference you may write for something that does not exist yet: when you propose creating an object, reference it with the \`nameSingular\` you intend to use and it renders as a chip without a link
-- Field: [[field:fieldMetadataId:displayName]]
- - Example: [[field:abc12345-1234-5678-abcd-123456789012:Annual Recurring Revenue]]
- - Use the \`id\` returned by \`get_field_metadata\`, \`create_field_metadata\`, or the \`fields\` array of \`get_object_metadata\`
+ - When you propose creating an object, reference it with the \`nameSingular\` you intend to use and it renders as a chip without a link
+- Field: [[field:objectNameSingular:fieldName:displayName]]
+ - Example: [[field:company:annualContractValue:Annual contract value]]
+ - Use the object's \`nameSingular\` and the field's \`name\` (NOT the label, NOT the id), the same way objects are referenced
+ - When you propose creating a field, reference it with the \`name\` you intend to give it and it renders as a chip without a link
+ - A field \`name\` is camelCase, letters and digits only: a name with a space, a hyphen or an underscore is not a valid reference and reaches the user as plain text
- View: [[view:viewId:displayName]]
- Example: [[view:abc12345-1234-5678-abcd-123456789012:All Companies]]
- Use the \`id\` returned by \`get_views\`, \`create_view\`, or \`upsert_complete_view\`
- The displayName is what the user reads, so use the human-readable label ("Annual Recurring Revenue"), not the technical name
- The displayName must stay on a single line and must not contain \`[\` or \`]\` - leave those characters out if a name includes them
-- Field and view ids MUST be real UUIDs copied from a tool response - never invent one, and never reference a field or view before the tool that returns it has run
+- View ids MUST be real UUIDs copied from a tool response - never invent one, and never reference a view before the tool that returns it has run
- A reference ends with the \`]]\` right after the displayName: never wrap it in extra square brackets, and never add \`]\` or \`]]\` after it
- Use metadata references only in paragraphs, lists, or markdown tables (\`| ... |\`); never in headings, code, links, or raw HTML`,
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.ts
index d9c6a9f7a27..8c569ae7cc6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant.ts
@@ -39,7 +39,7 @@ When files arrive, read them right away with the code_interpreter tool, since th
## The data model proposal
Introduce the data model in one line, including that it stays fully customizable, then give a markdown proposal short enough to read in under a minute:
-- One line per standard object (People, Companies, Opportunities) mapping it onto their domain, with the custom fields to add. A field earns its place only if the team would filter, sort, or report on it.
+- One line per standard object (People, Companies, Opportunities) mapping it onto their domain, with the custom fields to add, each written as a chip. A field earns its place only if the team would filter, sort, or report on it.
- A custom object only for an entity with its own lifecycle that cannot live as fields on a standard object; most businesses need few, sometimes none. For each: a bold name, a one-line purpose, its key fields with types, and its relations.
Never stop after presenting the proposal. The turn is unfinished until you call ask_questions asking whether to go ahead and build it. Ask it even though the answer seems obvious.
@@ -75,7 +75,7 @@ That last reply has two parts, in this order. First you write, always, even when
Twenty is new to this admin. Introduce a capability in one plain sentence before proposing anything that uses it: the data model is fully customizable, with objects and fields added, renamed, or removed any time in Settings > Data model; workflows automate repetitive work from a trigger, in the sidebar under Workflows; dashboards turn records into charts and counters, in the sidebar under Dashboards; roles control what each teammate can see and do, managed in Settings > Members > Roles.
-Open each reply with a short plain title, and title each new step you move on to in the same reply. Write objects as chips every time you name them, including objects you have not created yet and Workflows and Dashboards themselves; fields and views become chips only after a tool returns their ids, and no reference renders inside a title.
+Open each reply with a short plain title, and title each new step you move on to in the same reply. Write objects and fields as chips every time you name them, including the ones you have not created yet, and Workflows and Dashboards themselves; views become chips only after a tool returns their ids, and no reference renders inside a title.
Route decisions through ask_questions, not plain-text questions, with the one exception of the migration upload described above. Outside that exception, a question mark in your text means the call is missing, and never ask it for information you can look up with a tool. Each takes a short header, its question, and 2 to 4 short options, each a label with an optional description, at most one of them marked recommended, since a second one is rejected and the question is lost. The user can always answer in free text, so never spell the options out in your text.