Skip to content

The open alternative to Salesforce, designed for AI.

feat(ai-chat): hint @ and / in composer placeholder, add / skill suggestions (#25778)

Félix Malfait5d7ffd7694c2
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 9197c8fc7d6..79f724b5d01 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -7556,6 +7556,11 @@ export type FindManySkillsQueryVariables = Exact<{ [key: string]: never; }>;
export type FindManySkillsQuery = { __typename?: 'Query', skills: Array<{ __typename?: 'Skill', id: string, name: string, label: string, description?: string | null, icon?: string | null, content: string, isCustom: boolean, isActive: boolean, applicationId?: string | null, createdAt: string, updatedAt: string }> };
+export type FindManySkillsForSuggestionQueryVariables = Exact<{ [key: string]: never; }>;
+
+
+export type FindManySkillsForSuggestionQuery = { __typename?: 'Query', skills: Array<{ __typename?: 'Skill', id: string, name: string, label: string, description?: string | null, icon?: string | null, isActive: boolean }> };
+
export type FindOneAgentQueryVariables = Exact<{
id: Scalars['UUID']['input'];
}>;
@@ -9898,6 +9903,7 @@ export const UpdateOneAgentDocument = {"kind":"Document","definitions":[{"kind":
export const UpdateSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateSkill"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateSkillInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateSkill"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SkillFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SkillFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Skill"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<UpdateSkillMutation, UpdateSkillMutationVariables>;
export const FindManyAgentsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyAgents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findManyAgents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Agent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"prompt"}},{"kind":"Field","name":{"kind":"Name","value":"modelId"}},{"kind":"Field","name":{"kind":"Name","value":"responseFormat"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"modelConfiguration"}},{"kind":"Field","name":{"kind":"Name","value":"evaluationInputs"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<FindManyAgentsQuery, FindManyAgentsQueryVariables>;
export const FindManySkillsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManySkills"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"skills"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SkillFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SkillFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Skill"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<FindManySkillsQuery, FindManySkillsQueryVariables>;
+export const FindManySkillsForSuggestionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManySkillsForSuggestion"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"skills"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]}}]} as unknown as DocumentNode<FindManySkillsForSuggestionQuery, FindManySkillsForSuggestionQueryVariables>;
export const FindOneAgentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneAgent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findOneAgent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}]}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Agent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"prompt"}},{"kind":"Field","name":{"kind":"Name","value":"modelId"}},{"kind":"Field","name":{"kind":"Name","value":"responseFormat"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"modelConfiguration"}},{"kind":"Field","name":{"kind":"Name","value":"evaluationInputs"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<FindOneAgentQuery, FindOneAgentQueryVariables>;
export const FindOneSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneSkill"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"skill"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SkillFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SkillFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Skill"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<FindOneSkillQuery, FindOneSkillQueryVariables>;
export const FindWorkspaceAiStatsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindWorkspaceAiStats"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findWorkspaceAiStats"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"conversationsCount"}},{"kind":"Field","name":{"kind":"Name","value":"skillsCount"}},{"kind":"Field","name":{"kind":"Name","value":"toolsCount"}}]}}]}}]} as unknown as DocumentNode<FindWorkspaceAiStatsQuery, FindWorkspaceAiStatsQueryVariables>;
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx
index 39eb4148876..ce2e830a5b8 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/__stories__/AdvancedTextEditor.stories.tsx
@@ -307,7 +307,19 @@ export const Empty: Story = {
export const MinimalDocument: Story = {
args: {
extensionSet: 'minimal',
- placeholder: 'Ask, search or make anything...',
+ placeholder: 'Ask anything, @ a record or / a skill...',
+ },
+ play: async ({ canvasElement, step }) => {
+ await step('Verify placeholder hints at @ and / references', async () => {
+ await waitFor(() =>
+ expect(
+ canvasElement.querySelector('[data-placeholder]'),
+ ).toHaveAttribute(
+ 'data-placeholder',
+ 'Ask anything, @ a record or / a skill...',
+ ),
+ );
+ });
},
};
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
index 3f024e0fcb6..c2d28fb07f0 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChip.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChip.test.tsx
@@ -11,7 +11,10 @@ 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 {
+ FindManySkillsForSuggestionDocument,
+ PermissionFlagType,
+} from '~/generated-metadata/graphql';
import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
import { setTestViewsInMetadataStore } from '~/testing/utils/setTestViewsInMetadataStore';
@@ -37,6 +40,7 @@ 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 SKILL_ID = '88888888-8888-4888-8888-888888888888';
const UNKNOWN_ID = '77777777-7777-4777-8777-777777777777';
const allCompaniesView = {
@@ -51,8 +55,30 @@ const ALL_PERMISSION_FLAGS = [
PermissionFlagType.DATA_MODEL,
PermissionFlagType.ROLES,
PermissionFlagType.APPLICATIONS,
+ PermissionFlagType.AI_SETTINGS,
];
+// The skill chip reads its icon from the skill catalog
+const skillsApolloMock = {
+ request: { query: FindManySkillsForSuggestionDocument },
+ result: {
+ data: {
+ skills: [
+ {
+ __typename: 'Skill',
+ id: SKILL_ID,
+ name: 'workflow-building',
+ label: 'Workflow building',
+ description: null,
+ icon: 'IconSettingsAutomation',
+ isActive: true,
+ },
+ ],
+ },
+ },
+ maxUsageCount: Number.POSITIVE_INFINITY,
+};
+
const asMatch = (
reference: ChatReferenceIdentity & { displayName: string },
): ChatReferenceMatch => ({ ...reference, fullMatch: '', index: 0 });
@@ -120,6 +146,15 @@ const referenceCases: Array<{
href: `/settings/applications/${APPLICATION_ID}`,
permissionFlag: PermissionFlagType.APPLICATIONS,
},
+ {
+ reference: asMatch({
+ kind: 'skill',
+ skillId: SKILL_ID,
+ displayName: 'Workflow building',
+ }),
+ href: `/settings/ai/skills/${SKILL_ID}`,
+ permissionFlag: PermissionFlagType.AI_SETTINGS,
+ },
];
const findCase = (kind: ChatReferenceIdentity['kind']) =>
@@ -153,7 +188,7 @@ const renderWithReferences = (
} = {},
) => {
const Wrapper = getJestMetadataAndApolloMocksWrapper({
- apolloMocks: [],
+ apolloMocks: [skillsApolloMock],
onInitializeJotaiStore: (store) => {
setTestViewsInMetadataStore(store, views);
store.set(currentUserWorkspaceState.atom, {
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.ts b/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.ts
index ead175d3fe0..c35c763bc73 100644
--- a/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.ts
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.ts
@@ -1,10 +1,17 @@
import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';
import { MentionSuggestion } from '@/mention/extensions/MentionSuggestion';
import { MentionTag } from '@/mention/extensions/MentionTag';
+import { SkillSuggestion } from '@/skill-suggestion/extensions/SkillSuggestion';
+import { SkillTag } from '@/skill-suggestion/extensions/SkillTag';
export const AI_CHAT_EDITOR_PROFILE = {
chrome: 'document',
minHeight: 0,
enableFullScreen: false,
- buildExtensions: () => [MentionTag, MentionSuggestion],
+ buildExtensions: () => [
+ MentionTag,
+ MentionSuggestion,
+ SkillTag,
+ SkillSuggestion,
+ ],
} satisfies AdvancedTextEditorProfile;
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceIdentityShapeByKind.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceIdentityShapeByKind.ts
index 476ef9a5362..b4b62020316 100644
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceIdentityShapeByKind.ts
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceIdentityShapeByKind.ts
@@ -16,4 +16,5 @@ export const CHAT_REFERENCE_IDENTITY_SHAPE_BY_KIND: Record<
view: [CHAT_REFERENCE_UUID_REGEX],
role: [CHAT_REFERENCE_UUID_REGEX],
app: [CHAT_REFERENCE_UUID_REGEX],
+ skill: [CHAT_REFERENCE_UUID_REGEX],
};
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferencePermissionFlagByKind.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferencePermissionFlagByKind.ts
index fdfa2943c10..f7d2a836f8f 100644
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferencePermissionFlagByKind.ts
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferencePermissionFlagByKind.ts
@@ -8,4 +8,5 @@ export const CHAT_REFERENCE_PERMISSION_FLAG_BY_KIND: Partial<
field: PermissionFlagType.DATA_MODEL,
role: PermissionFlagType.ROLES,
app: PermissionFlagType.APPLICATIONS,
+ skill: PermissionFlagType.AI_SETTINGS,
};
diff --git a/packages/twenty-front/src/modules/ai/graphql/queries/findManySkillsForSuggestion.ts b/packages/twenty-front/src/modules/ai/graphql/queries/findManySkillsForSuggestion.ts
new file mode 100644
index 00000000000..e115a88d76c
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/graphql/queries/findManySkillsForSuggestion.ts
@@ -0,0 +1,14 @@
+import { gql } from '@apollo/client';
+
+export const FIND_MANY_SKILLS_FOR_SUGGESTION = gql`
+ query FindManySkillsForSuggestion {
+ skills {
+ id
+ name
+ label
+ description
+ icon
+ isActive
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
index a319a8debd8..d6e00241bbb 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
@@ -18,6 +18,8 @@ import { dispatchAgentChatEnsureThreadForDraftEvent } from '@/ai/utils/dispatchA
import { dispatchAgentChatSendMessageEvent } from '@/ai/utils/dispatchAgentChatSendMessageEvent';
import { MENTION_SUGGESTION_PLUGIN_KEY } from '@/mention/constants/MentionSuggestionPluginKey';
import { useMentionSearch } from '@/mention/hooks/useMentionSearch';
+import { SKILL_SUGGESTION_PLUGIN_KEY } from '@/skill-suggestion/constants/SkillSuggestionPluginKey';
+import { useSkillSuggestionSearch } from '@/skill-suggestion/hooks/useSkillSuggestionSearch';
import { useListenToBrowserEvent } from '@/browser-event/hooks/useListenToBrowserEvent';
import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';
import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';
@@ -33,6 +35,7 @@ export const useAiChatEditor = () => {
const [agentChatDraftsByThreadId, setAgentChatDraftsByThreadId] =
useAtomState(agentChatDraftsByThreadIdState);
const { searchMentionRecords } = useMentionSearch();
+ const { searchSkills } = useSkillSuggestionSearch();
const { pushFocusItemToFocusStack } = usePushFocusItemToFocusStack();
const { removeFocusItemFromFocusStackById } =
useRemoveFocusItemFromFocusStackById();
@@ -41,16 +44,19 @@ export const useAiChatEditor = () => {
const initialDraft = agentChatDraftsByThreadId[draftKey] ?? '';
const editor = useAdvancedTextEditor({
profile: AI_CHAT_EDITOR_PROFILE,
- placeholder: t`Ask, search or make anything...`,
+ placeholder: t`Ask anything, @ a record or / a skill...`,
readonly: false,
defaultValue: initialDraft,
editorProps: {
handleKeyDown: (view, event) => {
if (event.key === 'Enter' && !event.shiftKey) {
- const suggestionState = MENTION_SUGGESTION_PLUGIN_KEY.getState(
- view.state,
+ const isSuggestionMenuOpen = [
+ MENTION_SUGGESTION_PLUGIN_KEY,
+ SKILL_SUGGESTION_PLUGIN_KEY,
+ ].some(
+ (pluginKey) => pluginKey.getState(view.state)?.active === true,
);
- if (suggestionState?.active === true) {
+ if (isSuggestionMenuOpen) {
return false;
}
@@ -97,7 +103,7 @@ export const useAiChatEditor = () => {
},
});
- // Keep search function in sync via Tiptap extension storage,
+ // Keep search functions in sync via Tiptap extension storage,
// avoiding stale closures without useRef
if (isDefined(editor)) {
const storage = editor.extensionStorage as unknown as Record<
@@ -108,6 +114,11 @@ export const useAiChatEditor = () => {
searchMentionRecords: typeof searchMentionRecords;
};
mentionStorage.searchMentionRecords = searchMentionRecords;
+
+ const skillStorage = storage['skill-suggestion'] as {
+ searchSkills: typeof searchSkills;
+ };
+ skillStorage.searchSkills = searchSkills;
}
const handleRestoreEditorContent = useCallback(
diff --git a/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx b/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
index d4e09d8389a..7a54731fcc5 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
@@ -23,6 +23,8 @@ import { useOpenRecordInSidePanel } from '@/side-panel/hooks/useOpenRecordInSide
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 { DEFAULT_SKILL_ICON } from '@/skill-suggestion/constants/DefaultSkillIcon';
+import { useSkillIcon } from '@/skill-suggestion/hooks/useSkillIcon';
import { useViewById } from '@/views/hooks/useViewById';
const PROPOSED_OBJECT_METADATA_ICON = 'IconListNumbers';
@@ -63,6 +65,9 @@ export const useChatReferenceTarget = (
const { view } = useViewById(
reference.kind === 'view' ? reference.viewId : null,
);
+ const skillIcon = useSkillIcon(
+ reference.kind === 'skill' ? reference.skillId : null,
+ );
const iconSize = theme.icon.size.sm;
const iconStroke = theme.icon.stroke.sm;
@@ -190,6 +195,16 @@ export const useChatReferenceTarget = (
}),
leftComponent: <IconApps size={iconSize} stroke={iconStroke} />,
};
+ case 'skill': {
+ const SkillIcon = getIcon(skillIcon ?? DEFAULT_SKILL_ICON);
+
+ return {
+ path: getSettingsPath(SettingsPath.AiSkillDetail, {
+ skillId: reference.skillId,
+ }),
+ leftComponent: <SkillIcon size={iconSize} stroke={iconStroke} />,
+ };
+ }
default:
return assertUnreachable(reference);
}
diff --git a/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts b/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts
index 6364a71ca79..feb5a4d6e49 100644
--- a/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts
+++ b/packages/twenty-front/src/modules/ai/types/ChatReferenceIdentity.ts
@@ -5,4 +5,5 @@ export type ChatReferenceIdentity =
| { kind: 'field'; objectNameSingular: string; fieldName: string }
| { kind: 'view'; viewId: string }
| { kind: 'role'; roleId: string }
- | { kind: 'app'; applicationId: string };
+ | { kind: 'app'; applicationId: string }
+ | { kind: 'skill'; skillId: string };
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
index 441000b3239..e59166befea 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/parseChatReferences.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/parseChatReferences.test.ts
@@ -185,13 +185,25 @@ describe('parseChatReferences', () => {
displayName: 'Twenty',
},
},
+ {
+ name: 'a skill',
+ text: 'Use [[skill:88888888-8888-4888-8888-888888888888:Workflow building]]',
+ reference: {
+ kind: 'skill',
+ fullMatch:
+ '[[skill:88888888-8888-4888-8888-888888888888:Workflow building]]',
+ index: 4,
+ skillId: '88888888-8888-4888-8888-888888888888',
+ displayName: 'Workflow building',
+ },
+ },
])('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]]',
+ '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]] with [[skill:88888888-8888-4888-8888-888888888888:Workflow building]]',
);
expect(references.map((reference) => reference.kind)).toEqual([
@@ -202,6 +214,7 @@ describe('parseChatReferences', () => {
'field',
'role',
'app',
+ 'skill',
]);
expect(references.map((reference) => reference.displayName)).toEqual([
'Pipeline',
@@ -211,6 +224,7 @@ describe('parseChatReferences', () => {
'Stage',
'Admin',
'Twenty',
+ 'Workflow building',
]);
});
diff --git a/packages/twenty-front/src/modules/ai/utils/getChatReferenceIdentitySegment.ts b/packages/twenty-front/src/modules/ai/utils/getChatReferenceIdentitySegment.ts
index 96df9306385..1f736440464 100644
--- a/packages/twenty-front/src/modules/ai/utils/getChatReferenceIdentitySegment.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getChatReferenceIdentitySegment.ts
@@ -19,6 +19,8 @@ export const getChatReferenceIdentitySegment = (
return identity.roleId;
case 'app':
return identity.applicationId;
+ case 'skill':
+ return identity.skillId;
default:
return assertUnreachable(identity);
}
diff --git a/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts b/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts
index 6664c3b4a98..69571e24da1 100644
--- a/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts
+++ b/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts
@@ -38,6 +38,8 @@ const getChatReferenceIdentity = ({
return { kind, roleId: firstSegment };
case 'app':
return { kind, applicationId: firstSegment };
+ case 'skill':
+ return { kind, skillId: firstSegment };
default:
return assertUnreachable(kind);
}
diff --git a/packages/twenty-front/src/modules/skill-suggestion/components/SkillChip.tsx b/packages/twenty-front/src/modules/skill-suggestion/components/SkillChip.tsx
new file mode 100644
index 00000000000..c44b0ad1635
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/components/SkillChip.tsx
@@ -0,0 +1,18 @@
+import { type NodeViewProps } from '@tiptap/core';
+import { NodeViewWrapper } from '@tiptap/react';
+
+import { SkillReferenceChip } from '@/skill-suggestion/components/SkillReferenceChip';
+
+type SkillChipProps = Pick<NodeViewProps, 'node'>;
+
+export const SkillChip = ({ node }: SkillChipProps) => {
+ const skillId = node.attrs.skillId as string;
+ const label = node.attrs.label as string;
+ const icon = (node.attrs.icon as string | null) ?? null;
+
+ return (
+ <NodeViewWrapper as="span" style={{ display: 'inline' }}>
+ <SkillReferenceChip skillId={skillId} label={label} icon={icon} />
+ </NodeViewWrapper>
+ );
+};
diff --git a/packages/twenty-front/src/modules/skill-suggestion/components/SkillReferenceChip.tsx b/packages/twenty-front/src/modules/skill-suggestion/components/SkillReferenceChip.tsx
new file mode 100644
index 00000000000..1c48414aa5a
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/components/SkillReferenceChip.tsx
@@ -0,0 +1,34 @@
+import { SettingsPath } from 'twenty-shared/types';
+import { getSettingsPath } from 'twenty-shared/utils';
+import { ChipVariant, LinkChip } from 'twenty-ui/data-display';
+import { useIcons } from 'twenty-ui/icon';
+import { useTheme } from 'twenty-ui/theme-constants';
+
+import { DEFAULT_SKILL_ICON } from '@/skill-suggestion/constants/DefaultSkillIcon';
+
+type SkillReferenceChipProps = {
+ skillId: string;
+ label: string;
+ icon: string | null;
+};
+
+export const SkillReferenceChip = ({
+ skillId,
+ label,
+ icon,
+}: SkillReferenceChipProps) => {
+ const theme = useTheme();
+ const { getIcon } = useIcons();
+ const Icon = getIcon(icon ?? DEFAULT_SKILL_ICON);
+
+ return (
+ <LinkChip
+ label={label}
+ to={getSettingsPath(SettingsPath.AiSkillDetail, { skillId })}
+ variant={ChipVariant.Highlighted}
+ leftComponent={
+ <Icon size={theme.icon.size.sm} stroke={theme.icon.stroke.sm} />
+ }
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/skill-suggestion/components/SkillSuggestionMenu.tsx b/packages/twenty-front/src/modules/skill-suggestion/components/SkillSuggestionMenu.tsx
new file mode 100644
index 00000000000..f2adf14ca2e
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/components/SkillSuggestionMenu.tsx
@@ -0,0 +1,39 @@
+import { forwardRef } from 'react';
+
+import { SkillSuggestionMenuItem } from '@/skill-suggestion/components/SkillSuggestionMenuItem';
+import { SkillSuggestionPreviewCard } from '@/skill-suggestion/components/SkillSuggestionPreviewCard';
+import { SKILL_SUGGESTION_PREVIEW_WIDTH } from '@/skill-suggestion/constants/SkillSuggestionPreviewWidth';
+import type { SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+import type { SkillSuggestionMenuProps } from '@/skill-suggestion/types/SkillSuggestionMenuProps';
+import { SuggestionMenu } from '@/ui/suggestion/components/SuggestionMenu';
+
+const getItemKey = (item: SkillSuggestionItem) => item.id;
+
+export const SkillSuggestionMenu = forwardRef<
+ unknown,
+ SkillSuggestionMenuProps
+>((props, ref) => {
+ const { items, onSelect, editor, range } = props;
+
+ return (
+ <SuggestionMenu
+ ref={ref}
+ items={items}
+ onSelect={onSelect}
+ editor={editor}
+ range={range}
+ getItemKey={getItemKey}
+ renderItem={(item, isSelected) => (
+ <SkillSuggestionMenuItem
+ item={item}
+ isSelected={isSelected}
+ onSelect={onSelect}
+ />
+ )}
+ selectedItemPreview={{
+ render: (item) => <SkillSuggestionPreviewCard skill={item} />,
+ width: SKILL_SUGGESTION_PREVIEW_WIDTH,
+ }}
+ />
+ );
+});
diff --git a/packages/twenty-front/src/modules/skill-suggestion/components/SkillSuggestionMenuItem.tsx b/packages/twenty-front/src/modules/skill-suggestion/components/SkillSuggestionMenuItem.tsx
new file mode 100644
index 00000000000..6694dbe3621
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/components/SkillSuggestionMenuItem.tsx
@@ -0,0 +1,30 @@
+import { useIcons } from 'twenty-ui/icon';
+import { MenuItemSuggestion } from 'twenty-ui/navigation';
+
+import { DEFAULT_SKILL_ICON } from '@/skill-suggestion/constants/DefaultSkillIcon';
+import type { SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+
+type SkillSuggestionMenuItemProps = {
+ item: SkillSuggestionItem;
+ isSelected: boolean;
+ onSelect: (item: SkillSuggestionItem) => void;
+};
+
+export const SkillSuggestionMenuItem = ({
+ item,
+ isSelected,
+ onSelect,
+}: SkillSuggestionMenuItemProps) => {
+ const { getIcon } = useIcons();
+
+ return (
+ <MenuItemSuggestion
+ LeftIcon={getIcon(item.icon ?? DEFAULT_SKILL_ICON)}
+ text={item.label}
+ selected={isSelected}
+ onClick={() => {
+ onSelect(item);
+ }}
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/skill-suggestion/components/SkillSuggestionPreviewCard.tsx b/packages/twenty-front/src/modules/skill-suggestion/components/SkillSuggestionPreviewCard.tsx
new file mode 100644
index 00000000000..4b33e97988f
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/components/SkillSuggestionPreviewCard.tsx
@@ -0,0 +1,78 @@
+import { styled } from '@linaria/react';
+import { isNonEmptyString } from '@sniptt/guards';
+import { useIcons } from 'twenty-ui/icon';
+import { themeCssVariables, useTheme } from 'twenty-ui/theme-constants';
+
+import { DEFAULT_SKILL_ICON } from '@/skill-suggestion/constants/DefaultSkillIcon';
+import { SKILL_SUGGESTION_PREVIEW_WIDTH } from '@/skill-suggestion/constants/SkillSuggestionPreviewWidth';
+import type { SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+
+const StyledCard = styled.div`
+ background: ${themeCssVariables.background.primary};
+ border-radius: ${themeCssVariables.border.radius.md};
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ width: ${SKILL_SUGGESTION_PREVIEW_WIDTH}px;
+`;
+
+const StyledHeader = styled.div`
+ align-items: center;
+ border-bottom: 1px solid ${themeCssVariables.border.color.light};
+ box-sizing: border-box;
+ color: ${themeCssVariables.font.color.primary};
+ display: flex;
+ font-size: ${themeCssVariables.font.size.md};
+ font-weight: ${themeCssVariables.font.weight.medium};
+ gap: ${themeCssVariables.spacing[2]};
+ height: 40px;
+ padding: 0 ${themeCssVariables.spacing[3]};
+`;
+
+const StyledTitleText = styled.div`
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+`;
+
+const StyledName = styled.span`
+ color: ${themeCssVariables.font.color.light};
+ flex-shrink: 0;
+ font-weight: ${themeCssVariables.font.weight.regular};
+`;
+
+const StyledDescription = styled.div`
+ color: ${themeCssVariables.font.color.secondary};
+ font-size: ${themeCssVariables.font.size.md};
+ line-height: 1.5;
+ max-height: calc(50dvh / var(--t-zoom, 1));
+ overflow-y: auto;
+ padding: ${themeCssVariables.spacing[3]};
+ white-space: pre-wrap;
+`;
+
+type SkillSuggestionPreviewCardProps = {
+ skill: SkillSuggestionItem;
+};
+
+export const SkillSuggestionPreviewCard = ({
+ skill,
+}: SkillSuggestionPreviewCardProps) => {
+ const theme = useTheme();
+ const { getIcon } = useIcons();
+ const Icon = getIcon(skill.icon ?? DEFAULT_SKILL_ICON);
+
+ return (
+ <StyledCard>
+ <StyledHeader>
+ <Icon size={theme.icon.size.md} stroke={theme.icon.stroke.sm} />
+ <StyledTitleText>{skill.label}</StyledTitleText>
+ <StyledName>/{skill.name}</StyledName>
+ </StyledHeader>
+ {isNonEmptyString(skill.description) && (
+ <StyledDescription>{skill.description}</StyledDescription>
+ )}
+ </StyledCard>
+ );
+};
diff --git a/packages/twenty-front/src/modules/skill-suggestion/constants/DefaultSkillIcon.ts b/packages/twenty-front/src/modules/skill-suggestion/constants/DefaultSkillIcon.ts
new file mode 100644
index 00000000000..3c5ab0e2825
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/constants/DefaultSkillIcon.ts
@@ -0,0 +1 @@
+export const DEFAULT_SKILL_ICON = 'IconBook';
diff --git a/packages/twenty-front/src/modules/skill-suggestion/constants/SkillSuggestionPluginKey.ts b/packages/twenty-front/src/modules/skill-suggestion/constants/SkillSuggestionPluginKey.ts
new file mode 100644
index 00000000000..69fd660360e
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/constants/SkillSuggestionPluginKey.ts
@@ -0,0 +1,3 @@
+import { PluginKey } from '@tiptap/pm/state';
+
+export const SKILL_SUGGESTION_PLUGIN_KEY = new PluginKey('skill-suggestion');
diff --git a/packages/twenty-front/src/modules/skill-suggestion/constants/SkillSuggestionPreviewWidth.ts b/packages/twenty-front/src/modules/skill-suggestion/constants/SkillSuggestionPreviewWidth.ts
new file mode 100644
index 00000000000..f177815468c
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/constants/SkillSuggestionPreviewWidth.ts
@@ -0,0 +1 @@
+export const SKILL_SUGGESTION_PREVIEW_WIDTH = 320;
diff --git a/packages/twenty-front/src/modules/skill-suggestion/extensions/SkillSuggestion.ts b/packages/twenty-front/src/modules/skill-suggestion/extensions/SkillSuggestion.ts
new file mode 100644
index 00000000000..1edacd28d09
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/extensions/SkillSuggestion.ts
@@ -0,0 +1,72 @@
+import { Extension } from '@tiptap/core';
+import Suggestion from '@tiptap/suggestion';
+
+import { SkillSuggestionMenu } from '@/skill-suggestion/components/SkillSuggestionMenu';
+import { SKILL_SUGGESTION_PLUGIN_KEY } from '@/skill-suggestion/constants/SkillSuggestionPluginKey';
+import type { SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+import { createSuggestionRenderLifecycle } from '@/ui/suggestion/components/createSuggestionRenderLifecycle';
+
+type SkillSuggestionOptions = {
+ searchSkills: (query: string) => Promise<SkillSuggestionItem[]>;
+};
+
+export const SkillSuggestion = Extension.create<SkillSuggestionOptions>({
+ name: 'skill-suggestion',
+
+ addOptions: () => ({
+ searchSkills: async () => [],
+ }),
+
+ addStorage() {
+ return {
+ searchSkills: this.options.searchSkills,
+ };
+ },
+
+ addProseMirrorPlugins() {
+ return [
+ Suggestion<SkillSuggestionItem>({
+ pluginKey: SKILL_SUGGESTION_PLUGIN_KEY,
+ editor: this.editor,
+ char: '/',
+ items: async ({ query }) => {
+ try {
+ return await this.storage.searchSkills(query);
+ } catch {
+ return [];
+ }
+ },
+ command: ({ editor, range, props: selectedItem }) => {
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .insertContent({
+ type: 'skillTag',
+ attrs: {
+ skillId: selectedItem.id,
+ name: selectedItem.name,
+ label: selectedItem.label,
+ icon: selectedItem.icon,
+ },
+ })
+ .insertContent(' ')
+ .run();
+ },
+ render: () =>
+ createSuggestionRenderLifecycle(
+ {
+ component: SkillSuggestionMenu,
+ getMenuProps: ({ items, onSelect, editor, range }) => ({
+ items,
+ onSelect,
+ editor,
+ range,
+ }),
+ },
+ this.editor,
+ ),
+ }),
+ ];
+ },
+});
diff --git a/packages/twenty-front/src/modules/skill-suggestion/extensions/SkillTag.ts b/packages/twenty-front/src/modules/skill-suggestion/extensions/SkillTag.ts
new file mode 100644
index 00000000000..cf34436b517
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/extensions/SkillTag.ts
@@ -0,0 +1,64 @@
+import { Node } from '@tiptap/core';
+import { mergeAttributes, ReactNodeViewRenderer } from '@tiptap/react';
+import { formatSkillReference } from 'twenty-shared/ai';
+
+import { SkillChip } from '@/skill-suggestion/components/SkillChip';
+
+export const SkillTag = Node.create({
+ name: 'skillTag',
+ group: 'inline',
+ inline: true,
+ atom: true,
+
+ addAttributes: () => ({
+ skillId: {
+ default: null,
+ parseHTML: (element) => element.getAttribute('data-skill-id'),
+ renderHTML: (attributes) => ({
+ 'data-skill-id': attributes.skillId,
+ }),
+ },
+ name: {
+ default: '',
+ parseHTML: (element) => element.getAttribute('data-name'),
+ renderHTML: (attributes) => ({
+ 'data-name': attributes.name,
+ }),
+ },
+ label: {
+ default: '',
+ parseHTML: (element) => element.getAttribute('data-label'),
+ renderHTML: (attributes) => ({
+ 'data-label': attributes.label,
+ }),
+ },
+ icon: {
+ default: null,
+ parseHTML: (element) => element.getAttribute('data-icon'),
+ renderHTML: (attributes) => ({
+ 'data-icon': attributes.icon,
+ }),
+ },
+ }),
+
+ renderHTML: ({ node, HTMLAttributes }) => {
+ return [
+ 'span',
+ mergeAttributes(HTMLAttributes, {
+ 'data-type': 'skillTag',
+ class: 'skill-tag',
+ }),
+ `/${node.attrs.name}`,
+ ];
+ },
+
+ addNodeView: () => {
+ return ReactNodeViewRenderer(SkillChip);
+ },
+
+ renderText: ({ node }) => {
+ const { skillId, label } = node.attrs;
+
+ return formatSkillReference({ skillId, label });
+ },
+});
diff --git a/packages/twenty-front/src/modules/skill-suggestion/extensions/__tests__/SkillSuggestion.test.ts b/packages/twenty-front/src/modules/skill-suggestion/extensions/__tests__/SkillSuggestion.test.ts
new file mode 100644
index 00000000000..e7f2d482e23
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/extensions/__tests__/SkillSuggestion.test.ts
@@ -0,0 +1,120 @@
+import { Editor } from '@tiptap/core';
+import { Document } from '@tiptap/extension-document';
+import { HardBreak } from '@tiptap/extension-hard-break';
+import { Paragraph } from '@tiptap/extension-paragraph';
+import { Text } from '@tiptap/extension-text';
+
+import { SKILL_SUGGESTION_PLUGIN_KEY } from '@/skill-suggestion/constants/SkillSuggestionPluginKey';
+import { SkillSuggestion } from '@/skill-suggestion/extensions/SkillSuggestion';
+
+// Mock ReactRenderer (DOM-dependent)
+jest.mock('@tiptap/react', () => ({
+ mergeAttributes: jest.requireActual('@tiptap/react').mergeAttributes,
+ ReactNodeViewRenderer: () => () => ({}),
+ ReactRenderer: jest.fn().mockImplementation(() => ({
+ element: document.createElement('div'),
+ ref: null,
+ updateProps: jest.fn(),
+ destroy: jest.fn(),
+ })),
+}));
+
+describe('SkillSuggestion', () => {
+ let editor: Editor;
+ let mockSearchSkills: jest.Mock;
+
+ beforeEach(() => {
+ mockSearchSkills = jest.fn().mockResolvedValue([]);
+
+ editor = new Editor({
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ SkillSuggestion.configure({
+ searchSkills: mockSearchSkills,
+ }),
+ ],
+ content: '<p></p>',
+ });
+ });
+
+ afterEach(() => {
+ editor?.destroy();
+ });
+
+ it('should register the extension', () => {
+ const extension = editor.extensionManager.extensions.find(
+ (ext) => ext.name === 'skill-suggestion',
+ );
+
+ expect(extension).toBeDefined();
+ });
+
+ it('should add the suggestion ProseMirror plugin', () => {
+ const hasSuggestionPlugin = editor.state.plugins.some(
+ (plugin) =>
+ (plugin as unknown as { key: string }).key === 'skill-suggestion$',
+ );
+
+ expect(hasSuggestionPlugin).toBe(true);
+ });
+
+ it('should expose the search function through storage', () => {
+ const storage = editor.extensionStorage as unknown as Record<
+ string,
+ { searchSkills: jest.Mock }
+ >;
+
+ expect(storage['skill-suggestion'].searchSkills).toBe(mockSearchSkills);
+ });
+
+ const isSuggestionActive = () =>
+ SKILL_SUGGESTION_PLUGIN_KEY.getState(editor.state)?.active === true;
+
+ it('should open the suggestion when / is typed at the start of a line', () => {
+ editor.commands.focus('end');
+ editor.commands.insertContent('/');
+
+ expect(isSuggestionActive()).toBe(true);
+ });
+
+ it('should open the suggestion when / follows a space', () => {
+ editor.commands.focus('end');
+ editor.commands.insertContent('Use /');
+
+ expect(isSuggestionActive()).toBe(true);
+ });
+
+ it('should open the suggestion when / follows a hard break', () => {
+ editor.commands.focus('end');
+ editor.commands.insertContent('first line');
+ editor.commands.setHardBreak();
+ editor.commands.insertContent('/');
+
+ expect(isSuggestionActive()).toBe(true);
+ });
+
+ it('should not open the suggestion when / is part of a word such as a URL', () => {
+ editor.commands.focus('end');
+ editor.commands.insertContent('https:/');
+
+ expect(isSuggestionActive()).toBe(false);
+ });
+
+ it('should use default empty search function when not configured', () => {
+ const unconfiguredEditor = new Editor({
+ extensions: [Document, Paragraph, Text, SkillSuggestion],
+ content: '<p></p>',
+ });
+
+ const extension = unconfiguredEditor.extensionManager.extensions.find(
+ (ext) => ext.name === 'skill-suggestion',
+ );
+
+ expect(extension?.options.searchSkills).toBeDefined();
+
+ unconfiguredEditor.destroy();
+ });
+});
diff --git a/packages/twenty-front/src/modules/skill-suggestion/extensions/__tests__/SkillTag.test.ts b/packages/twenty-front/src/modules/skill-suggestion/extensions/__tests__/SkillTag.test.ts
new file mode 100644
index 00000000000..e707c41fbcd
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/extensions/__tests__/SkillTag.test.ts
@@ -0,0 +1,63 @@
+import { Editor } from '@tiptap/core';
+import { Document } from '@tiptap/extension-document';
+import { Paragraph } from '@tiptap/extension-paragraph';
+import { Text } from '@tiptap/extension-text';
+
+import { SkillTag } from '@/skill-suggestion/extensions/SkillTag';
+
+// Mock ReactNodeViewRenderer since we're testing in a non-DOM environment
+jest.mock('@tiptap/react', () => ({
+ mergeAttributes: jest.requireActual('@tiptap/react').mergeAttributes,
+ ReactNodeViewRenderer: () => () => ({}),
+}));
+
+describe('SkillTag', () => {
+ let editor: Editor;
+
+ beforeEach(() => {
+ editor = new Editor({
+ extensions: [Document, Paragraph, Text, SkillTag],
+ content: '<p></p>',
+ });
+ });
+
+ afterEach(() => {
+ editor?.destroy();
+ });
+
+ it('should register as an inline atom node', () => {
+ const skillTagType = editor.schema.nodes.skillTag;
+
+ expect(skillTagType).toBeDefined();
+ expect(skillTagType.isInline).toBe(true);
+ expect(skillTagType.isAtom).toBe(true);
+ });
+
+ it('should serialize a skill tag to the [[skill:...]] reference format', () => {
+ editor.commands.setContent({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Use ' },
+ {
+ type: 'skillTag',
+ attrs: {
+ skillId: 'skill-123',
+ name: 'workflow-building',
+ label: 'Workflow building',
+ icon: 'IconSettingsAutomation',
+ },
+ },
+ { type: 'text', text: ' now' },
+ ],
+ },
+ ],
+ });
+
+ expect(editor.getText()).toBe(
+ 'Use [[skill:skill-123:Workflow building]] now',
+ );
+ });
+});
diff --git a/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillIcon.ts b/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillIcon.ts
new file mode 100644
index 00000000000..1cc6a149c9a
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillIcon.ts
@@ -0,0 +1,17 @@
+import { useQuery } from '@apollo/client/react';
+import { isDefined } from 'twenty-shared/utils';
+
+import { FindManySkillsForSuggestionDocument } from '~/generated-metadata/graphql';
+
+// Skill references only carry an id and a label, so the icon comes from the
+// cached skill catalog; the query is skipped when no skill is referenced.
+export const useSkillIcon = (skillId: string | null): string | null => {
+ const { data } = useQuery(FindManySkillsForSuggestionDocument, {
+ skip: !isDefined(skillId),
+ fetchPolicy: 'cache-first',
+ });
+
+ const skill = data?.skills.find((candidate) => candidate.id === skillId);
+
+ return skill?.icon ?? null;
+};
diff --git a/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts b/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts
new file mode 100644
index 00000000000..3ff36b25f23
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts
@@ -0,0 +1,43 @@
+import { useApolloClient } from '@apollo/client/react';
+import { useCallback } from 'react';
+
+import type { SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+import { FindManySkillsForSuggestionDocument } from '~/generated-metadata/graphql';
+import { normalizeSearchText } from '~/utils/normalizeSearchText';
+
+export const useSkillSuggestionSearch = () => {
+ const apolloMetadataClient = useApolloClient();
+
+ const searchSkills = useCallback(
+ async (query: string): Promise<SkillSuggestionItem[]> => {
+ // Settings can delete or deactivate a skill without refetching the
+ // catalog, so the list is refreshed when the menu opens (empty query)
+ // and served from cache while the user narrows it down.
+ const { data } = await apolloMetadataClient.query({
+ query: FindManySkillsForSuggestionDocument,
+ fetchPolicy: query === '' ? 'network-only' : 'cache-first',
+ });
+
+ const normalizedQuery = normalizeSearchText(query);
+
+ return (data?.skills ?? [])
+ .filter(
+ (skill) =>
+ skill.isActive &&
+ (normalizeSearchText(skill.name).includes(normalizedQuery) ||
+ normalizeSearchText(skill.label).includes(normalizedQuery)),
+ )
+ .sort((skillA, skillB) => skillA.label.localeCompare(skillB.label))
+ .map((skill) => ({
+ id: skill.id,
+ name: skill.name,
+ label: skill.label,
+ description: skill.description ?? null,
+ icon: skill.icon ?? null,
+ }));
+ },
+ [apolloMetadataClient],
+ );
+
+ return { searchSkills };
+};
diff --git a/packages/twenty-front/src/modules/skill-suggestion/types/SkillSuggestionItem.ts b/packages/twenty-front/src/modules/skill-suggestion/types/SkillSuggestionItem.ts
new file mode 100644
index 00000000000..e7868da5c27
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/types/SkillSuggestionItem.ts
@@ -0,0 +1,7 @@
+export type SkillSuggestionItem = {
+ id: string;
+ name: string;
+ label: string;
+ description: string | null;
+ icon: string | null;
+};
diff --git a/packages/twenty-front/src/modules/skill-suggestion/types/SkillSuggestionMenuProps.ts b/packages/twenty-front/src/modules/skill-suggestion/types/SkillSuggestionMenuProps.ts
new file mode 100644
index 00000000000..d99b9945f85
--- /dev/null
+++ b/packages/twenty-front/src/modules/skill-suggestion/types/SkillSuggestionMenuProps.ts
@@ -0,0 +1,10 @@
+import type { Editor, Range } from '@tiptap/core';
+
+import type { SkillSuggestionItem } from '@/skill-suggestion/types/SkillSuggestionItem';
+
+export type SkillSuggestionMenuProps = {
+ items: SkillSuggestionItem[];
+ onSelect: (item: SkillSuggestionItem) => void;
+ editor: Editor;
+ range: Range;
+};
diff --git a/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx b/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx
index 94c5a67bf63..c6660d426fa 100644
--- a/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx
+++ b/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx
@@ -5,6 +5,7 @@ import {
shift,
useFloating,
} from '@floating-ui/react';
+import { css } from '@linaria/core';
import { motion } from 'framer-motion';
import {
forwardRef,
@@ -20,6 +21,20 @@ import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent
import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
import { OverlayContainer } from '@/ui/layout/overlay/components/OverlayContainer';
import type { SuggestionMenuProps } from '@/ui/suggestion/types/SuggestionMenuProps';
+import { getSuggestionMenuItemAnchorId } from '@/ui/suggestion/utils/getSuggestionMenuItemAnchorId';
+import { useIsMobile } from '@/ui/utilities/responsive/hooks/useIsMobile';
+import { AppTooltip, TooltipDelay } from 'twenty-ui/surfaces';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+// The preview card brings its own surface, so the tooltip only contributes
+// the shadow. Tooltips render at 0.9 opacity, which would make it translucent.
+const previewTooltipClass = css`
+ background: transparent !important;
+ border-radius: ${themeCssVariables.border.radius.md} !important;
+ box-shadow: ${themeCssVariables.boxShadow.strong} !important;
+ opacity: 1 !important;
+ padding: 0 !important;
+`;
type SuggestionMenuInnerProps<TItem> = SuggestionMenuProps<TItem>;
@@ -28,14 +43,34 @@ const SuggestionMenuInner = <TItem,>(
props: SuggestionMenuInnerProps<TItem>,
parentRef: React.ForwardedRef<unknown>,
) => {
- const { items, onSelect, editor, range, getItemKey, renderItem, onKeyDown } =
- props;
+ const {
+ items,
+ onSelect,
+ editor,
+ range,
+ getItemKey,
+ renderItem,
+ selectedItemPreview,
+ onKeyDown,
+ } = props;
+
+ const isMobile = useIsMobile();
const [selectedIndex, setSelectedIndex] = useState(0);
const clampedSelectedIndex =
items.length > 0 ? Math.min(selectedIndex, items.length - 1) : 0;
+ const selectedItem = items[clampedSelectedIndex];
+
+ const [isSelectedItemVisible, setIsSelectedItemVisible] = useState(true);
+
+ const shouldDisplayPreview =
+ !isMobile &&
+ isSelectedItemVisible &&
+ selectedItemPreview !== undefined &&
+ selectedItem !== undefined;
+
const activeItemRef = useRef<HTMLDivElement>(null);
const listContainerRef = useRef<HTMLDivElement>(null);
@@ -137,6 +172,35 @@ const SuggestionMenuInner = <TItem,>(
scrollableContainer.scrollTop = offsetTop - offsetHeight;
}, [clampedSelectedIndex]);
+ // The preview is anchored to the selected row, so once the user scrolls that
+ // row out of the list it would float detached from the menu.
+ useLayoutEffect(() => {
+ const scrollableContainer =
+ listContainerRef.current?.firstElementChild ?? null;
+ const activeItemContainer = activeItemRef.current;
+
+ if (
+ !scrollableContainer ||
+ !activeItemContainer ||
+ typeof IntersectionObserver === 'undefined'
+ ) {
+ return;
+ }
+
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ setIsSelectedItemVisible(entry.isIntersecting);
+ },
+ { root: scrollableContainer, threshold: 0.99 },
+ );
+
+ observer.observe(activeItemContainer);
+
+ return () => {
+ observer.disconnect();
+ };
+ }, [clampedSelectedIndex, items]);
+
return (
<motion.div
initial={{ opacity: 0 }}
@@ -159,6 +223,7 @@ const SuggestionMenuInner = <TItem,>(
return (
<div
key={getItemKey(item)}
+ id={getSuggestionMenuItemAnchorId(getItemKey(item))}
ref={isSelected ? activeItemRef : null}
onMouseDown={(event) => {
event.preventDefault();
@@ -171,6 +236,21 @@ const SuggestionMenuInner = <TItem,>(
</DropdownMenuItemsContainer>
</DropdownContent>
</OverlayContainer>
+ {shouldDisplayPreview && (
+ <AppTooltip
+ anchorSelect={`#${getSuggestionMenuItemAnchorId(getItemKey(selectedItem))}`}
+ place="right-start"
+ offset={16}
+ noArrow
+ interactive
+ isOpen
+ delay={TooltipDelay.noDelay}
+ className={previewTooltipClass}
+ maxWidth={`${selectedItemPreview.width}px`}
+ >
+ {selectedItemPreview.render(selectedItem)}
+ </AppTooltip>
+ )}
</motion.div>
);
};
diff --git a/packages/twenty-front/src/modules/ui/suggestion/types/SuggestionMenuProps.ts b/packages/twenty-front/src/modules/ui/suggestion/types/SuggestionMenuProps.ts
index d9faeeb8063..d66206abf65 100644
--- a/packages/twenty-front/src/modules/ui/suggestion/types/SuggestionMenuProps.ts
+++ b/packages/twenty-front/src/modules/ui/suggestion/types/SuggestionMenuProps.ts
@@ -1,6 +1,11 @@
import type { Editor, Range } from '@tiptap/core';
import type { ReactNode } from 'react';
+export type SuggestionMenuSelectedItemPreview<TItem> = {
+ render: (item: TItem) => ReactNode;
+ width: number;
+};
+
export type SuggestionMenuProps<TItem> = {
items: TItem[];
onSelect: (item: TItem) => void;
@@ -8,6 +13,7 @@ export type SuggestionMenuProps<TItem> = {
range: Range;
getItemKey: (item: TItem) => string;
renderItem: (item: TItem, isSelected: boolean) => ReactNode;
+ selectedItemPreview?: SuggestionMenuSelectedItemPreview<TItem>;
onKeyDown?: (
event: KeyboardEvent,
selectedIndex: number,
diff --git a/packages/twenty-front/src/modules/ui/suggestion/utils/getSuggestionMenuItemAnchorId.ts b/packages/twenty-front/src/modules/ui/suggestion/utils/getSuggestionMenuItemAnchorId.ts
new file mode 100644
index 00000000000..6a53c503ea1
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/suggestion/utils/getSuggestionMenuItemAnchorId.ts
@@ -0,0 +1,2 @@
+export const getSuggestionMenuItemAnchorId = (itemKey: string) =>
+ `suggestion-menu-item-${itemKey.replace(/[^a-zA-Z0-9-_]/g, '_')}`;
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 037ca6f424b..5f0b1522385 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
@@ -18,6 +18,8 @@ Examples:
For simple CRUD operations (find/create/update/delete a record), you do NOT need a skill — but you still MUST call \`learn_tools\` first to learn the tool schema, then \`execute_tool\` to run it.
+When the user tags a skill in their message, it appears as \`[[skill:skillId:label]]\`: they are explicitly asking you to use that skill. Its full instructions are already inlined under "Referenced Skills", so follow them directly without calling \`load_skills\` for it.
+
## Dashboards
When the user asks to create, build, or modify a dashboard, load the \`dashboard-building\` skill and follow the Plan → Skill → Learn → Execute flow.
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
index 639bd87adba..fae956d6833 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
@@ -72,6 +72,7 @@ import { buildWorkspaceSetupChatThreadId } from 'src/engine/metadata-modules/ai/
import { buildFullSystemPrompt } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util';
import { hasNoAssistantMessage } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-no-assistant-message.util';
import { hasSucceededWorkspaceSetupCompletion } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-succeeded-workspace-setup-completion.util';
+import { collectReferencedSkillIds } from 'src/engine/metadata-modules/ai/ai-chat/utils/collect-referenced-skill-ids.util';
import { collectUploadedFileReferences } from 'src/engine/metadata-modules/ai/ai-chat/utils/collect-uploaded-file-references.util';
import { extractCodeInterpreterFiles } from 'src/engine/metadata-modules/ai/ai-chat/utils/extract-code-interpreter-files.util';
import { injectMessageTimestamps } from 'src/engine/metadata-modules/ai/ai-chat/utils/inject-message-timestamps.util';
@@ -283,6 +284,13 @@ export class ChatExecutionService {
const uploadedFiles = collectUploadedFileReferences(messages);
+ // Skills the user tagged with / are inlined into the prompt so the model
+ // does not spend a round trip calling load_skills for them.
+ const referencedSkills = await this.skillService.findFlatSkillsByIds(
+ collectReferencedSkillIds(messages),
+ workspace.id,
+ );
+
let processedMessages: ExtendedUIMessage[] = replaceUnsupportedFileParts(
messages,
modelConfig.modalities,
@@ -327,6 +335,7 @@ export class ChatExecutionService {
const systemPrompt = buildFullSystemPrompt({
toolCatalog,
skillCatalog,
+ referencedSkills,
preloadedTools: preloadedToolNames,
uploadedFilesContext: {
uploadedFiles,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-full-system-prompt.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-full-system-prompt.util.spec.ts
index 922f142eb5f..dd31a06b098 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-full-system-prompt.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-full-system-prompt.util.spec.ts
@@ -1,4 +1,5 @@
import { buildFullSystemPrompt } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util';
+import { type ReferencedSkill } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-referenced-skills-section.util';
const WORKSPACE_INSTRUCTIONS_DOCUMENT = JSON.stringify({
type: 'doc',
@@ -28,7 +29,37 @@ const buildPrompt = (isWorkspaceSetupThread?: boolean) =>
isWorkspaceSetupThread,
});
+const REFERENCED_SKILL: ReferencedSkill = {
+ name: 'workflow-building',
+ label: 'Workflow building',
+ content: JSON.stringify({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Always create a trigger first.' }],
+ },
+ ],
+ }),
+};
+
describe('buildFullSystemPrompt', () => {
+ it('should inline referenced skills after the skill catalog', () => {
+ const prompt = buildFullSystemPrompt({
+ toolCatalog: [],
+ skillCatalog: [],
+ referencedSkills: [REFERENCED_SKILL],
+ preloadedTools: [],
+ });
+
+ expect(prompt).toContain('## Referenced Skills (already loaded)');
+ expect(prompt).toContain('Always create a trigger first.');
+ });
+
+ it('should omit the referenced skills section when nothing is referenced', () => {
+ expect(buildPrompt(false)).not.toContain('## Referenced Skills');
+ });
+
it('should keep the standard composition for regular threads', () => {
const prompt = buildPrompt(false);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-referenced-skills-section.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-referenced-skills-section.util.spec.ts
new file mode 100644
index 00000000000..13d618dcf67
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-referenced-skills-section.util.spec.ts
@@ -0,0 +1,35 @@
+import {
+ buildReferencedSkillsSection,
+ type ReferencedSkill,
+} from 'src/engine/metadata-modules/ai/ai-chat/utils/build-referenced-skills-section.util';
+
+const SKILL_CONTENT = JSON.stringify({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'Always create a trigger first.' }],
+ },
+ ],
+});
+
+const skill: ReferencedSkill = {
+ name: 'workflow-building',
+ label: 'Workflow building',
+ content: SKILL_CONTENT,
+};
+
+describe('buildReferencedSkillsSection', () => {
+ it('should return an empty string without referenced skills', () => {
+ expect(buildReferencedSkillsSection([])).toBe('');
+ });
+
+ it('should inline each referenced skill with its markdown content', () => {
+ const section = buildReferencedSkillsSection([skill]);
+
+ expect(section).toContain('## Referenced Skills (already loaded)');
+ expect(section).toContain('### Workflow building (`workflow-building`)');
+ expect(section).toContain('Always create a trigger first.');
+ expect(section).toContain('do NOT call `load_skills` for them');
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/collect-referenced-skill-ids.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/collect-referenced-skill-ids.util.spec.ts
new file mode 100644
index 00000000000..29b4602b796
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/collect-referenced-skill-ids.util.spec.ts
@@ -0,0 +1,55 @@
+import {
+ collectReferencedSkillIds,
+ type ReferencedSkillSourceMessage,
+} from 'src/engine/metadata-modules/ai/ai-chat/utils/collect-referenced-skill-ids.util';
+
+const SKILL_ID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
+const OTHER_SKILL_ID = '11111111-2222-3333-4444-555555555555';
+
+const userMessage = (text: string): ReferencedSkillSourceMessage => ({
+ role: 'user',
+ parts: [{ type: 'text', text }],
+});
+
+describe('collectReferencedSkillIds', () => {
+ it('should return the ids of skills referenced in user messages', () => {
+ expect(
+ collectReferencedSkillIds([
+ userMessage(`Use [[skill:${SKILL_ID}:Workflow building]] here`),
+ ]),
+ ).toEqual([SKILL_ID]);
+ });
+
+ it('should deduplicate ids across messages and keep first-seen order', () => {
+ expect(
+ collectReferencedSkillIds([
+ userMessage(
+ `[[skill:${SKILL_ID}:A]] and [[skill:${OTHER_SKILL_ID}:B]]`,
+ ),
+ userMessage(`Again [[skill:${SKILL_ID}:A]]`),
+ ]),
+ ).toEqual([SKILL_ID, OTHER_SKILL_ID]);
+ });
+
+ it('should match a reference whose label contains brackets', () => {
+ expect(
+ collectReferencedSkillIds([
+ userMessage(`Use [[skill:${SKILL_ID}:Research [beta]]] now`),
+ ]),
+ ).toEqual([SKILL_ID]);
+ });
+
+ it('should ignore assistant messages and other reference kinds', () => {
+ expect(
+ collectReferencedSkillIds([
+ {
+ role: 'assistant',
+ parts: [{ type: 'text', text: `[[skill:${SKILL_ID}:A]]` }],
+ },
+ userMessage(
+ `[[record:company:${SKILL_ID}:Acme]] [[skill:not-a-uuid:A]]`,
+ ),
+ ]),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util.ts
index d5e68a89513..6a3935299b3 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-full-system-prompt.util.ts
@@ -6,6 +6,10 @@ import { buildToolCatalogSection } from 'src/engine/core-modules/tool-provider/u
import { type UserContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
import { CHAT_SYSTEM_PROMPTS } from 'src/engine/metadata-modules/ai/ai-chat/constants/chat-system-prompts.const';
import { WORKSPACE_SETUP_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-system-prompt.constant';
+import {
+ buildReferencedSkillsSection,
+ type ReferencedSkill,
+} from 'src/engine/metadata-modules/ai/ai-chat/utils/build-referenced-skills-section.util';
import { buildSkillCatalogSection } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-skill-catalog-section.util';
import { buildUploadedFilesSection } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-uploaded-files-section.util';
import { buildUserContextSection } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-user-context-section.util';
@@ -16,6 +20,7 @@ import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/fla
export const buildFullSystemPrompt = ({
toolCatalog,
skillCatalog,
+ referencedSkills = [],
preloadedTools,
uploadedFilesContext,
workspaceInstructions,
@@ -24,6 +29,7 @@ export const buildFullSystemPrompt = ({
}: {
toolCatalog: ToolIndexEntry[];
skillCatalog: FlatSkill[];
+ referencedSkills?: ReferencedSkill[];
preloadedTools: string[];
uploadedFilesContext?: {
uploadedFiles: UploadedFileReference[];
@@ -63,6 +69,13 @@ export const buildFullSystemPrompt = ({
parts.push(skillSection);
}
+ const referencedSkillsSection =
+ buildReferencedSkillsSection(referencedSkills);
+
+ if (isNonEmptyString(referencedSkillsSection)) {
+ parts.push(referencedSkillsSection);
+ }
+
if (
isDefined(uploadedFilesContext) &&
isNonEmptyArray(uploadedFilesContext.uploadedFiles)
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-referenced-skills-section.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-referenced-skills-section.util.ts
new file mode 100644
index 00000000000..a75e8ffae42
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-referenced-skills-section.util.ts
@@ -0,0 +1,29 @@
+import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';
+
+import { LOAD_SKILL_TOOL_NAME } from 'src/engine/core-modules/tool-provider/tools';
+import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
+
+export type ReferencedSkill = Pick<FlatSkill, 'name' | 'label' | 'content'>;
+
+export const buildReferencedSkillsSection = (
+ referencedSkills: ReferencedSkill[],
+): string => {
+ if (referencedSkills.length === 0) {
+ return '';
+ }
+
+ const skillSections = referencedSkills
+ .map(
+ (skill) => `### ${skill.label} (\`${skill.name}\`)
+
+${tipTapDocumentToMarkdown(skill.content)}`,
+ )
+ .join('\n\n');
+
+ return `
+## Referenced Skills (already loaded)
+
+The user explicitly referenced these skills with [[skill:...]] in their messages. Their full instructions are below, so follow them directly: do NOT call \`${LOAD_SKILL_TOOL_NAME}\` for them.
+
+${skillSections}`;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/collect-referenced-skill-ids.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/collect-referenced-skill-ids.util.ts
new file mode 100644
index 00000000000..a4a50dd24c1
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/collect-referenced-skill-ids.util.ts
@@ -0,0 +1,37 @@
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+// Matches the [[skill:<uuid>:<label>]] references the composer inserts when a
+// user picks a skill from the / menu. Only the id prefix is matched so a label
+// containing brackets cannot break the lookup.
+const SKILL_REFERENCE_REGEX =
+ /\[\[skill:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}):/g;
+
+export type ReferencedSkillSourceMessage = Pick<
+ ExtendedUIMessage,
+ 'role' | 'parts'
+>;
+
+export const collectReferencedSkillIds = (
+ messages: ReferencedSkillSourceMessage[],
+): string[] => {
+ const skillIds = new Set<string>();
+
+ for (const message of messages) {
+ if (message.role !== 'user' || !isDefined(message.parts)) {
+ continue;
+ }
+
+ for (const part of message.parts) {
+ if (part.type !== 'text') {
+ continue;
+ }
+
+ for (const match of part.text.matchAll(SKILL_REFERENCE_REGEX)) {
+ skillIds.add(match[1]);
+ }
+ }
+ }
+
+ return [...skillIds];
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts
index bd071afa6d8..2d8c13b26c9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts
@@ -16,10 +16,9 @@ import { SkillGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules
import { SkillService } from 'src/engine/metadata-modules/skill/skill.service';
import { WorkspaceMigrationGraphqlApiExceptionInterceptor } from 'src/engine/workspace-manager/workspace-migration/interceptors/workspace-migration-graphql-api-exception.interceptor';
-@UseGuards(
- WorkspaceAuthGuard,
- SettingsPermissionGuard(PermissionFlagType.AI_SETTINGS),
-)
+// Reads are open to chat users so the composer can list skills; mutations
+// stay behind AI settings.
+@UseGuards(WorkspaceAuthGuard, SettingsPermissionGuard(PermissionFlagType.AI))
@UseInterceptors(
WorkspaceMigrationGraphqlApiExceptionInterceptor,
SkillGraphqlApiExceptionInterceptor,
@@ -44,6 +43,7 @@ export class SkillResolver {
}
@Mutation(() => SkillDTO)
+ @UseGuards(SettingsPermissionGuard(PermissionFlagType.AI_SETTINGS))
async createSkill(
@Args('input') input: CreateSkillInput,
@AuthWorkspace() workspace: WorkspaceEntity,
@@ -52,6 +52,7 @@ export class SkillResolver {
}
@Mutation(() => SkillDTO)
+ @UseGuards(SettingsPermissionGuard(PermissionFlagType.AI_SETTINGS))
async updateSkill(
@Args('input') input: UpdateSkillInput,
@AuthWorkspace() workspace: WorkspaceEntity,
@@ -60,6 +61,7 @@ export class SkillResolver {
}
@Mutation(() => SkillDTO)
+ @UseGuards(SettingsPermissionGuard(PermissionFlagType.AI_SETTINGS))
async deleteSkill(
@Args('id', { type: () => UUIDScalarType }) id: string,
@AuthWorkspace() workspace: WorkspaceEntity,
@@ -68,6 +70,7 @@ export class SkillResolver {
}
@Mutation(() => SkillDTO)
+ @UseGuards(SettingsPermissionGuard(PermissionFlagType.AI_SETTINGS))
async activateSkill(
@Args('id', { type: () => UUIDScalarType }) id: string,
@AuthWorkspace() workspace: WorkspaceEntity,
@@ -76,6 +79,7 @@ export class SkillResolver {
}
@Mutation(() => SkillDTO)
+ @UseGuards(SettingsPermissionGuard(PermissionFlagType.AI_SETTINGS))
async deactivateSkill(
@Args('id', { type: () => UUIDScalarType }) id: string,
@AuthWorkspace() workspace: WorkspaceEntity,
diff --git a/packages/twenty-server/src/engine/metadata-modules/skill/skill.service.ts b/packages/twenty-server/src/engine/metadata-modules/skill/skill.service.ts
index da0ee2ae86a..6e487b103ca 100644
--- a/packages/twenty-server/src/engine/metadata-modules/skill/skill.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/skill/skill.service.ts
@@ -266,6 +266,27 @@ export class SkillService {
);
}
+ async findFlatSkillsByIds(
+ ids: string[],
+ workspaceId: string,
+ ): Promise<FlatSkill[]> {
+ if (ids.length === 0) {
+ return [];
+ }
+
+ const { flatSkillMaps } =
+ await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
+ {
+ workspaceId,
+ flatMapsKeys: ['flatSkillMaps'],
+ },
+ );
+
+ return Object.values(flatSkillMaps.byUniversalIdentifier)
+ .filter(isDefined)
+ .filter((flatSkill) => ids.includes(flatSkill.id) && flatSkill.isActive);
+ }
+
async activate(id: string, workspaceId: string): Promise<SkillDTO> {
const { workspaceCustomFlatApplication } =
await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.ts
index 0096bab5e3a..bb6e0ee9522 100644
--- a/packages/twenty-shared/src/ai/index.ts
+++ b/packages/twenty-shared/src/ai/index.ts
@@ -63,6 +63,7 @@ export type { ExtendedUIMessagePart } from './types/ExtendedUIMessagePart';
export type { ModelConfiguration } from './types/model-configuration.type';
export type { NavigateAppToolOutput } from './types/NavigateAppToolOutput';
export { formatRecordReference } from './utils/format-record-reference.util';
+export { formatSkillReference } from './utils/format-skill-reference.util';
export { getAiModelTierFromModelId } from './utils/get-ai-model-tier-from-model-id.util';
export { inferAiSdkPackage } from './utils/infer-ai-sdk-package.util';
export { isAiModelEffort } from './utils/is-ai-model-effort.util';
diff --git a/packages/twenty-shared/src/ai/utils/__tests__/format-skill-reference.util.spec.ts b/packages/twenty-shared/src/ai/utils/__tests__/format-skill-reference.util.spec.ts
new file mode 100644
index 00000000000..ce6811b91c0
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/__tests__/format-skill-reference.util.spec.ts
@@ -0,0 +1,12 @@
+import { formatSkillReference } from '@/ai/utils/format-skill-reference.util';
+
+describe('formatSkillReference', () => {
+ it('should format a skill reference with its id and label', () => {
+ expect(
+ formatSkillReference({
+ skillId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
+ label: 'Workflow building',
+ }),
+ ).toBe('[[skill:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Workflow building]]');
+ });
+});
diff --git a/packages/twenty-shared/src/ai/utils/format-skill-reference.util.ts b/packages/twenty-shared/src/ai/utils/format-skill-reference.util.ts
new file mode 100644
index 00000000000..e298637268f
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/format-skill-reference.util.ts
@@ -0,0 +1,7 @@
+export const formatSkillReference = ({
+ skillId,
+ label,
+}: {
+ skillId: string;
+ label: string;
+}): string => `[[skill:${skillId}:${label}]]`;
diff --git a/packages/twenty-shared/src/utils/tiptap/__tests__/tiptap-document.test.ts b/packages/twenty-shared/src/utils/tiptap/__tests__/tiptap-document.test.ts
index ba534ea77e1..a0580280051 100644
--- a/packages/twenty-shared/src/utils/tiptap/__tests__/tiptap-document.test.ts
+++ b/packages/twenty-shared/src/utils/tiptap/__tests__/tiptap-document.test.ts
@@ -120,6 +120,30 @@ describe('TipTap document primitives', () => {
);
});
+ it('projects skill tags to skill references in Markdown', () => {
+ expect(
+ tipTapDocumentToMarkdown({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Use ' },
+ {
+ type: 'skillTag',
+ attrs: {
+ skillId: 'skill-id',
+ name: 'workflow-building',
+ label: 'Workflow building',
+ },
+ },
+ ],
+ },
+ ],
+ }),
+ ).toBe('Use [[skill:skill-id:Workflow building]]');
+ });
+
it('preserves nested list hierarchy in Markdown projections', () => {
expect(
tipTapDocumentToMarkdown({
diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts
index bdb7797b6d9..dfd841124dc 100644
--- a/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts
+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts
@@ -1,4 +1,5 @@
import { formatRecordReference } from '@/ai/utils/format-record-reference.util';
+import { formatSkillReference } from '@/ai/utils/format-skill-reference.util';
import { parseTipTapJsonDocument } from './parse-tiptap-json-document';
import { type TipTapDocument } from './tiptap-document';
@@ -76,6 +77,17 @@ const renderMention = (node: TipTapNode): string => {
return '';
};
+const renderSkillTag = (node: TipTapNode): string => {
+ const skillId = node.attrs?.skillId;
+ const label = node.attrs?.label;
+
+ if (typeof skillId === 'string' && typeof label === 'string') {
+ return formatSkillReference({ skillId, label });
+ }
+
+ return typeof label === 'string' ? label : '';
+};
+
const renderListItem = (item: TipTapNode, marker: string): string => {
const [firstLine = '', ...continuationLines] = renderChildren(item)
.trim()
@@ -111,6 +123,8 @@ const renderTipTapNodeToMarkdown = (node: TipTapNode): string => {
: '';
case TIPTAP_NODE_TYPES.MENTION_TAG:
return renderMention(node);
+ case TIPTAP_NODE_TYPES.SKILL_TAG:
+ return renderSkillTag(node);
case TIPTAP_NODE_TYPES.HEADING: {
const level =
typeof node.attrs?.level === 'number' ? node.attrs.level : 1;
diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts
index 2381459a0cd..b696e3ee4ef 100644
--- a/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts
+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-node-types.ts
@@ -5,6 +5,7 @@ export const TIPTAP_NODE_TYPES = {
HEADING: 'heading',
VARIABLE_TAG: 'variableTag',
MENTION_TAG: 'mentionTag',
+ SKILL_TAG: 'skillTag',
IMAGE: 'image',
BULLET_LIST: 'bulletList',
ORDERED_LIST: 'orderedList',