The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(ai-chat): # to reference records, @ to bring teammates into a chat (#27234)
Félix Malfaite5d5e7917970
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 848c3f8143d..ba7bbc2c4cc 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -4357,6 +4357,7 @@ type Mutation {archiveAgentChatThread(threadId: UUID!): AgentChatThreadParticipant!snoozeAgentChatThread(threadId: UUID!, snoozedUntil: DateTime!): AgentChatThreadParticipant!moveAgentChatThreadToInbox(threadId: UUID!): AgentChatThreadParticipant!+ addAgentChatThreadParticipants(threadId: UUID!, workspaceMemberIds: [UUID!]!): [UUID!]!startWorkspaceSetupChat(companyContext: JSON, personContext: JSON): StartWorkspaceSetupChatResult!sendInboxMessage(input: SendInboxMessageInput!): SendInboxMessageResult!createSkill(input: CreateSkillInput!): Skill!diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex fe57003f6d3..043f1968721 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -3731,6 +3731,7 @@ export interface Mutation {archiveAgentChatThread: AgentChatThreadParticipantsnoozeAgentChatThread: AgentChatThreadParticipantmoveAgentChatThreadToInbox: AgentChatThreadParticipant+ addAgentChatThreadParticipants: Scalars['UUID'][]startWorkspaceSetupChat: StartWorkspaceSetupChatResultsendInboxMessage: SendInboxMessageResultcreateSkill: Skill@@ -7737,6 +7738,7 @@ export interface MutationGenqlSelection{archiveAgentChatThread?: (AgentChatThreadParticipantGenqlSelection & { __args: {threadId: Scalars['UUID']} })snoozeAgentChatThread?: (AgentChatThreadParticipantGenqlSelection & { __args: {threadId: Scalars['UUID'], snoozedUntil: Scalars['DateTime']} })moveAgentChatThreadToInbox?: (AgentChatThreadParticipantGenqlSelection & { __args: {threadId: Scalars['UUID']} })+ addAgentChatThreadParticipants?: { __args: {threadId: Scalars['UUID'], workspaceMemberIds: Scalars['UUID'][]} }startWorkspaceSetupChat?: (StartWorkspaceSetupChatResultGenqlSelection & { __args?: {companyContext?: (Scalars['JSON'] | null), personContext?: (Scalars['JSON'] | null)} })sendInboxMessage?: (SendInboxMessageResultGenqlSelection & { __args: {input: SendInboxMessageInput} })createSkill?: (SkillGenqlSelection & { __args: {input: CreateSkillInput} })diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex c40ea7260e6..e953b73c23f 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -10701,6 +10701,19 @@ export default {]}],+ "addAgentChatThreadParticipants": [+ 3,+ {+ "threadId": [+ 3,+ "UUID!"+ ],+ "workspaceMemberIds": [+ 3,+ "[UUID!]!"+ ]+ }+ ],"startWorkspaceSetupChat": [391,{diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 30c5f5aabfa..4f78223d6ff 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -3070,6 +3070,7 @@ export type Mutation = {__typename?: 'Mutation';activateSkill: Skill;activateWorkspace: Workspace;+ addAgentChatThreadParticipants: Array<Scalars['UUID']['output']>;addQueryToEventStream: Scalars['Boolean']['output'];archiveAgentChatThread: AgentChatThreadParticipant;assignRoleToAgent: Scalars['Boolean']['output'];@@ -3359,6 +3360,12 @@ export type MutationActivateWorkspaceArgs = {};+export type MutationAddAgentChatThreadParticipantsArgs = {+ threadId: Scalars['UUID']['input'];+ workspaceMemberIds: Array<Scalars['UUID']['input']>;+};++export type MutationAddQueryToEventStreamArgs = {input: AddQuerySubscriptionInput;};@@ -8017,6 +8024,14 @@ export type ActivateSkillMutationVariables = Exact<{export type ActivateSkillMutation = { __typename?: 'Mutation', activateSkill: { __typename?: 'Skill', id: string, name: string, label: string, description?: string | null, icon?: string | null, content: string, isCustom: boolean, isSystem: boolean, isActive: boolean, applicationId?: string | null, createdAt: string, updatedAt: string } };+export type AddAgentChatThreadParticipantsMutationVariables = Exact<{+ threadId: Scalars['UUID']['input'];+ workspaceMemberIds: Array<Scalars['UUID']['input']> | Scalars['UUID']['input'];+}>;+++export type AddAgentChatThreadParticipantsMutation = { __typename?: 'Mutation', addAgentChatThreadParticipants: Array<string> };+export type ArchiveAgentChatThreadMutationVariables = Exact<{threadId: Scalars['UUID']['input'];}>;@@ -10697,6 +10712,7 @@ export const ResetTimelineActivityTypeDocument = {"kind":"Document","definitionsexport const UpdateTimelineActivityTypeIsActiveDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateTimelineActivityTypeIsActive"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateTimelineActivityTypeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateTimelineActivityType"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]}}]} as unknown as DocumentNode<UpdateTimelineActivityTypeIsActiveMutation, UpdateTimelineActivityTypeIsActiveMutationVariables>;export const FindManyTimelineActivityTypesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyTimelineActivityTypes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"timelineActivityTypes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"emit"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"on"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}}]}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]}}]} as unknown as DocumentNode<FindManyTimelineActivityTypesQuery, FindManyTimelineActivityTypesQueryVariables>;export const ActivateSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ActivateSkill"},"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":"activateSkill"},"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":"isSystem"}},{"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<ActivateSkillMutation, ActivateSkillMutationVariables>;+export const AddAgentChatThreadParticipantsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AddAgentChatThreadParticipants"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceMemberIds"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"addAgentChatThreadParticipants"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}},{"kind":"Argument","name":{"kind":"Name","value":"workspaceMemberIds"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceMemberIds"}}}]}]}}]} as unknown as DocumentNode<AddAgentChatThreadParticipantsMutation, AddAgentChatThreadParticipantsMutationVariables>;export const ArchiveAgentChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ArchiveAgentChatThread"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"archiveAgentChatThread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<ArchiveAgentChatThreadMutation, ArchiveAgentChatThreadMutationVariables>;export const AssignRoleToAgentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AssignRoleToAgent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"assignRoleToAgent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"agentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}}},{"kind":"Argument","name":{"kind":"Name","value":"roleId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}}}]}]}}]} as unknown as DocumentNode<AssignRoleToAgentMutation, AssignRoleToAgentMutationVariables>;export const CreateChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateChatThread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createChatThread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<CreateChatThreadMutation, CreateChatThreadMutationVariables>;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.tsxindex 1250fddbe51..dd7979e16f8 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@@ -306,19 +306,22 @@ export const Empty: Story = {export const MinimalDocument: Story = {args: {extensionSet: 'minimal',- placeholder: 'Ask anything, @ a record or / a skill...',+ placeholder: 'Ask anything, # a record, @ a teammate 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...',- ),- );- });+ await step(+ 'Verify placeholder hints at #, @ and / references',+ async () => {+ await waitFor(() =>+ expect(+ canvasElement.querySelector('[data-placeholder]'),+ ).toHaveAttribute(+ 'data-placeholder',+ 'Ask anything, # a record, @ a teammate or / a skill...',+ ),+ );+ },+ );},};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAddMenu.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAddMenu.tsxindex e5e6d57bfa3..c43af3c7863 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatAddMenu.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatAddMenu.tsx@@ -72,7 +72,7 @@ export const AiChatAddMenu = ({ editor }: AiChatAddMenuProps) => {</Dropdown.ActionItem><Dropdown.ActionItemstartIcon={<IconAddressBook />}- shortcut={['@']}+ shortcut={['#']}page={AI_CHAT_ADD_MENU_PAGE.RECORDS}>{t`Records`}diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsxindex e33796406b7..2a8222cfa6d 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx@@ -9,6 +9,7 @@ import { themeCssVariables } from 'twenty-ui/theme';import { AiChatInlineBanner } from '@/ai/components/AiChatInlineBanner';import { AiChatEmptyState } from '@/ai/components/AiChatEmptyState';+import { AiChatParticipantMentionBar } from '@/ai/components/AiChatParticipantMentionBar';import { AiChatPendingAskGate } from '@/ai/components/AiChatPendingAskGate';import { AiChatNoMoreBillingCreditsBanner } from '@/ai/components/AiChatNoMoreBillingCreditsBanner';import { AiChatUsageLimitReachedBanner } from '@/ai/components/AiChatUsageLimitReachedBanner';@@ -201,6 +202,7 @@ const EditableAiChatEditorSection = () => {)}{hasReachedAiChatCreditsCap && <AiChatNoMoreBillingCreditsBanner />}{shouldShowUsageLimitBanner && <AiChatUsageLimitReachedBanner />}+ <AiChatParticipantMentionBar editor={editor} /><AiChatPendingAskGate>{composer}</AiChatPendingAskGate></StyledInputArea><StyledComposerBottomSpacerdiff --git a/packages/twenty-front/src/modules/ai/components/AiChatParticipantMentionBar.tsx b/packages/twenty-front/src/modules/ai/components/AiChatParticipantMentionBar.tsxnew file mode 100644index 00000000000..396e9abb257--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatParticipantMentionBar.tsx@@ -0,0 +1,92 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import { type Editor } from '@tiptap/react';+import { CoreObjectNameSingular } from 'twenty-shared/types';+import { isDefined, TIPTAP_NODE_TYPES } from 'twenty-shared/utils';+import { LightButton } from 'twenty-ui/components';+import { IconUsers } from 'twenty-ui/icon';+import { themeCssVariables, useTheme } from 'twenty-ui/theme';++import { useAiChatPendingParticipantMentions } from '@/ai/hooks/useAiChatPendingParticipantMentions';++const StyledBar = styled.div`+ align-items: center;+ background: ${themeCssVariables.background.tertiary};+ border-radius: ${themeCssVariables.border.radius.md};+ box-sizing: border-box;+ color: ${themeCssVariables.font.color.secondary};+ display: flex;+ font-size: ${themeCssVariables.font.size.sm};+ gap: ${themeCssVariables.spacing[2]};+ padding: ${themeCssVariables.spacing[1]} ${themeCssVariables.spacing[1]}+ ${themeCssVariables.spacing[1]} ${themeCssVariables.spacing[2]};+ width: 100%;+`;++const StyledMessage = styled.span`+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+`;++type AiChatParticipantMentionBarProps = {+ editor: Editor | null;+};++export const AiChatParticipantMentionBar = ({+ editor,+}: AiChatParticipantMentionBarProps) => {+ const { t } = useLingui();+ const theme = useTheme();+ const pendingParticipantMentions = useAiChatPendingParticipantMentions();++ if (pendingParticipantMentions.length === 0) {+ return null;+ }++ const participantLabels = pendingParticipantMentions+ .map(({ label }) => label)+ .join(', ');+ const message =+ pendingParticipantMentions.length === 1+ ? t`${participantLabels} will be added as a participant and get access to this chat`+ : t`${participantLabels} will be added as participants and get access to this chat`;++ // The mentions stay in the message, only without bringing anyone in+ const handleUndo = () => {+ if (!isDefined(editor)) {+ return;+ }++ const { state } = editor.view;+ const transaction = state.tr;++ state.doc.descendants((node, position) => {+ if (+ node.type.name === TIPTAP_NODE_TYPES.MENTION_TAG &&+ node.attrs.objectNameSingular ===+ CoreObjectNameSingular.WorkspaceMember &&+ node.attrs.shouldAddAsParticipant === true+ ) {+ transaction.setNodeMarkup(position, undefined, {+ ...node.attrs,+ shouldAddAsParticipant: false,+ });+ }+ });++ editor.view.dispatch(transaction);+ };++ return (+ <StyledBar role="status">+ <IconUsers size={theme.icon.size.sm} />+ <StyledMessage title={message}>{message}</StyledMessage>+ <LightButton emphasis="subtle" onClick={handleUndo}>+ {t`Undo`}+ </LightButton>+ </StyledBar>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatParticipantMentionBar.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatParticipantMentionBar.test.tsxnew file mode 100644index 00000000000..8f26ccebefb--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatParticipantMentionBar.test.tsx@@ -0,0 +1,92 @@+import { i18n } from '@lingui/core';+import { I18nProvider } from '@lingui/react';+import { act, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { Editor } from '@tiptap/core';+import { Document } from '@tiptap/extension-document';+import { Paragraph } from '@tiptap/extension-paragraph';+import { Text } from '@tiptap/extension-text';+import { type Editor as ReactEditor } from '@tiptap/react';+import { CoreObjectNameSingular } from 'twenty-shared/types';++import { serializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeAdvancedTextEditorDocument';+import { AiChatParticipantMentionBar } from '@/ai/components/AiChatParticipantMentionBar';+import {+ AGENT_CHAT_NEW_THREAD_DRAFT_KEY,+ agentChatDraftsByThreadIdState,+} from '@/ai/states/agentChatDraftsByThreadIdState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { MentionTag } from '@/mention/extensions/MentionTag';+import { getMentionTagContent } from '@/mention/utils/getMentionTagContent';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';+import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';++jest.mock('@tiptap/react', () => ({+ mergeAttributes: jest.requireActual('@tiptap/react').mergeAttributes,+ ReactNodeViewRenderer: () => () => ({}),+}));++const GRACE_ID = '20202020-0000-4000-8000-000000000021';++const renderBar = (editor: Editor) => {+ const Wrapper = getJestMetadataAndApolloMocksWrapper({+ onInitializeJotaiStore: (store) => {+ store.set(currentAiChatThreadState.atom, AGENT_CHAT_NEW_THREAD_DRAFT_KEY);+ },+ });++ return render(+ <Wrapper>+ <I18nProvider i18n={i18n}>+ <AiChatParticipantMentionBar editor={editor as ReactEditor} />+ </I18nProvider>+ </Wrapper>,+ );+};++describe('AiChatParticipantMentionBar', () => {+ let editor: Editor;++ beforeEach(() => {+ editor = new Editor({+ extensions: [Document, Paragraph, Text, MentionTag],+ onUpdate: ({ editor: updatedEditor }) => {+ jotaiStore.set(agentChatDraftsByThreadIdState.atom, {+ [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]:+ serializeAdvancedTextEditorDocument(updatedEditor),+ });+ },+ });+ });++ afterEach(() => {+ editor.destroy();+ });++ it('announces a mentioned teammate and lets the sender keep them out', async () => {+ renderBar(editor);++ expect(screen.queryByRole('status')).not.toBeInTheDocument();++ act(() => {+ editor.commands.insertContent(+ getMentionTagContent({+ recordId: GRACE_ID,+ objectNameSingular: CoreObjectNameSingular.WorkspaceMember,+ label: 'Grace Hopper',+ imageUrl: '',+ shouldAddAsParticipant: true,+ }),+ );+ });++ expect(screen.getByRole('status')).toHaveTextContent(+ 'Grace Hopper will be added as a participant and get access to this chat',+ );++ await userEvent.click(screen.getByRole('button', { name: 'Undo' }));++ expect(screen.queryByRole('status')).not.toBeInTheDocument();+ expect(editor.getText()).toContain('Grace Hopper');+ });+});diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.ts b/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.tsindex c35c763bc73..b662dba62fe 100644--- a/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.ts+++ b/packages/twenty-front/src/modules/ai/constants/AiChatEditorProfile.ts@@ -1,6 +1,7 @@import { type AdvancedTextEditorProfile } from '@/advanced-text-editor/types/AdvancedTextEditorProfile';import { MentionSuggestion } from '@/mention/extensions/MentionSuggestion';import { MentionTag } from '@/mention/extensions/MentionTag';+import { WorkspaceMemberMentionSuggestion } from '@/mention/extensions/WorkspaceMemberMentionSuggestion';import { SkillSuggestion } from '@/skill-suggestion/extensions/SkillSuggestion';import { SkillTag } from '@/skill-suggestion/extensions/SkillTag';@@ -11,6 +12,7 @@ export const AI_CHAT_EDITOR_PROFILE = {buildExtensions: () => [MentionTag,MentionSuggestion,+ WorkspaceMemberMentionSuggestion,SkillTag,SkillSuggestion,],diff --git a/packages/twenty-front/src/modules/ai/graphql/mutations/addAgentChatThreadParticipants.ts b/packages/twenty-front/src/modules/ai/graphql/mutations/addAgentChatThreadParticipants.tsnew file mode 100644index 00000000000..3e1fa8b9875--- /dev/null+++ b/packages/twenty-front/src/modules/ai/graphql/mutations/addAgentChatThreadParticipants.ts@@ -0,0 +1,13 @@+import { gql } from '@apollo/client';++export const ADD_AGENT_CHAT_THREAD_PARTICIPANTS = gql`+ mutation AddAgentChatThreadParticipants(+ $threadId: UUID!+ $workspaceMemberIds: [UUID!]!+ ) {+ addAgentChatThreadParticipants(+ threadId: $threadId+ workspaceMemberIds: $workspaceMemberIds+ )+ }+`;diff --git a/packages/twenty-front/src/modules/ai/hooks/useAddAgentChatThreadParticipants.ts b/packages/twenty-front/src/modules/ai/hooks/useAddAgentChatThreadParticipants.tsnew file mode 100644index 00000000000..c17672fca22--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useAddAgentChatThreadParticipants.ts@@ -0,0 +1,77 @@+import { useApolloClient } from '@apollo/client/react';+import { t } from '@lingui/core/macro';+import { isNonEmptyString } from '@sniptt/guards';+import { useStore } from 'jotai';+import { useCallback } from 'react';+import { useToast } from 'twenty-ui/components';++import { getParticipantMentionsFromSerializedDocument } from '@/ai/utils/getParticipantMentionsFromSerializedDocument';+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';+import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';+import { AddAgentChatThreadParticipantsDocument } from '~/generated-metadata/graphql';++export const useAddAgentChatThreadParticipants = () => {+ const apolloClient = useApolloClient();+ const store = useStore();+ const { enqueueToast } = useToast();++ const addParticipantsMentionedInMessage = useCallback(+ async ({+ threadId,+ serializedMessage,+ }: {+ threadId: string;+ serializedMessage: string;+ }) => {+ const currentWorkspaceMemberId = store.get(+ currentWorkspaceMemberState.atom,+ )?.id;+ // Members already following are sent too, so the mention brings the+ // chat back to their inbox+ const participantMentions = getParticipantMentionsFromSerializedDocument(+ serializedMessage,+ ).filter(+ ({ workspaceMemberId }) =>+ workspaceMemberId !== currentWorkspaceMemberId,+ );++ if (participantMentions.length === 0) {+ return;+ }++ try {+ const { data } = await apolloClient.mutate({+ mutation: AddAgentChatThreadParticipantsDocument,+ variables: {+ threadId,+ workspaceMemberIds: participantMentions.map(+ ({ workspaceMemberId }) => workspaceMemberId,+ ),+ },+ });++ const addedWorkspaceMemberIds =+ data?.addAgentChatThreadParticipants ?? [];+ const notAddedLabels = participantMentions+ .filter(+ ({ workspaceMemberId }) =>+ !addedWorkspaceMemberIds.includes(workspaceMemberId),+ )+ .map(({ label }) => label)+ .join(', ');++ if (isNonEmptyString(notAddedLabels)) {+ enqueueToast({+ variant: 'warning',+ children: t`${notAddedLabels} could not be added to this chat because they can't reply in it.`,+ });+ }+ } catch (error) {+ enqueueToast(getToastOptionsFromError({ error }));+ }+ },+ [apolloClient, enqueueToast, store],+ );++ return { addParticipantsMentionedInMessage };+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.tsindex b041e579cb5..8ca673bb303 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts@@ -17,6 +17,7 @@ import { AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME } from '@/ai/constants/AgentChatimport { AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME } from '@/ai/constants/AgentChatRestoreEditorContentEventName';import { AGENT_CHAT_SEND_MESSAGE_EVENT_NAME } from '@/ai/constants/AgentChatSendMessageEventName';import { AGENT_CHAT_STOP_EVENT_NAME } from '@/ai/constants/AgentChatStopEventName';+import { useAddAgentChatThreadParticipants } from '@/ai/hooks/useAddAgentChatThreadParticipants';import { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';import { useAttachChatThreadToRecord } from '@/ai/hooks/useAttachChatThreadToRecord';import { useGetBrowsingContext } from '@/ai/hooks/useGetBrowsingContext';@@ -58,6 +59,8 @@ export const useAgentChat = (const { getBrowsingContext } = useGetBrowsingContext();const { applyOptimisticRestore } = useOptimisticallyRestoreOnSend();const { attachChatThreadToRecord } = useAttachChatThreadToRecord();+ const { addParticipantsMentionedInMessage } =+ useAddAgentChatThreadParticipants();const apolloClient = useApolloClient();const { enqueueToast } = useToast();const setCurrentAiChatThread = useSetAtomState(currentAiChatThreadState);@@ -207,6 +210,10 @@ export const useAgentChat = ().forEach((conversationTarget) => {void attachChatThreadToRecord({ threadId, ...conversationTarget });});+ void addParticipantsMentionedInMessage({+ threadId,+ serializedMessage: serializedContentToSend,+ });if (data?.sendChatMessage.queued === true) {removeOptimisticUserMessage();@@ -256,6 +263,7 @@ export const useAgentChat = (apolloClient,applyOptimisticRestore,attachChatThreadToRecord,+ addParticipantsMentionedInMessage,]);useListenToBrowserEvent({diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.tsindex 331f0c2e410..cd1eb368f2a 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts@@ -17,7 +17,9 @@ import { AGENT_CHAT_ENSURE_THREAD_FOR_DRAFT_EVENT_NAME } from '@/ai/constants/Agimport { AGENT_CHAT_SEND_MESSAGE_EVENT_NAME } from '@/ai/constants/AgentChatSendMessageEventName';import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';import { MENTION_SUGGESTION_PLUGIN_KEY } from '@/mention/constants/MentionSuggestionPluginKey';+import { WORKSPACE_MEMBER_MENTION_SUGGESTION_PLUGIN_KEY } from '@/mention/constants/WorkspaceMemberMentionSuggestionPluginKey';import { useMentionSearch } from '@/mention/hooks/useMentionSearch';+import { useWorkspaceMemberMentionSearch } from '@/mention/hooks/useWorkspaceMemberMentionSearch';import { SKILL_SUGGESTION_PLUGIN_KEY } from '@/skill-suggestion/constants/SkillSuggestionPluginKey';import { useSkillSuggestionSearch } from '@/skill-suggestion/hooks/useSkillSuggestionSearch';import { useListenToBrowserEvent } from '@/browser-event/hooks/useListenToBrowserEvent';@@ -33,6 +35,7 @@ export const useAiChatEditor = () => {const [agentChatDraftsByThreadId, setAgentChatDraftsByThreadId] =useAtomState(agentChatDraftsByThreadIdState);const { searchMentionRecords } = useMentionSearch();+ const { searchWorkspaceMembers } = useWorkspaceMemberMentionSearch();const { searchSkills } = useSkillSuggestionSearch();const { pushFocusItemToFocusStack } = usePushFocusItemToFocusStack();const { removeFocusItemFromFocusStackById } =@@ -42,7 +45,7 @@ export const useAiChatEditor = () => {const initialDraft = agentChatDraftsByThreadId[draftKey] ?? '';const editor = useAdvancedTextEditor({profile: AI_CHAT_EDITOR_PROFILE,- placeholder: t`Ask anything, @ a record or / a skill...`,+ placeholder: t`Ask anything, # a record, @ a teammate or / a skill...`,readonly: false,defaultValue: initialDraft,editorProps: {@@ -50,6 +53,7 @@ export const useAiChatEditor = () => {if (event.key === 'Enter' && !event.shiftKey) {const isSuggestionMenuOpen = [MENTION_SUGGESTION_PLUGIN_KEY,+ WORKSPACE_MEMBER_MENTION_SUGGESTION_PLUGIN_KEY,SKILL_SUGGESTION_PLUGIN_KEY,].some((pluginKey) => pluginKey.getState(view.state)?.active === true,@@ -111,6 +115,14 @@ export const useAiChatEditor = () => {};mentionStorage.searchMentionRecords = searchMentionRecords;+ const workspaceMemberMentionStorage = storage[+ 'workspace-member-mention-suggestion'+ ] as {+ searchWorkspaceMembers: typeof searchWorkspaceMembers;+ };+ workspaceMemberMentionStorage.searchWorkspaceMembers =+ searchWorkspaceMembers;+const skillStorage = storage['skill-suggestion'] as {searchSkills: typeof searchSkills;};diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatPendingParticipantMentions.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatPendingParticipantMentions.tsnew file mode 100644index 00000000000..baddb64210f--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatPendingParticipantMentions.ts@@ -0,0 +1,36 @@+import { useMemo } from 'react';++import {+ AGENT_CHAT_NEW_THREAD_DRAFT_KEY,+ agentChatDraftsByThreadIdState,+} from '@/ai/states/agentChatDraftsByThreadIdState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { agentChatThreadRecordFamilySelector } from '@/ai/states/selectors/agentChatThreadRecordFamilySelector';+import { filterNewParticipantMentions } from '@/ai/utils/filterNewParticipantMentions';+import { getParticipantMentionsFromSerializedDocument } from '@/ai/utils/getParticipantMentionsFromSerializedDocument';+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';+import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';++export const useAiChatPendingParticipantMentions = () => {+ const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);+ const draftKey = currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY;+ const serializedDraft =+ useAtomStateValue(agentChatDraftsByThreadIdState)[draftKey] ?? '';+ const thread = useAtomFamilySelectorValue(+ agentChatThreadRecordFamilySelector,+ draftKey,+ );+ const currentWorkspaceMember = useAtomStateValue(currentWorkspaceMemberState);++ const participantMentions = useMemo(+ () => getParticipantMentionsFromSerializedDocument(serializedDraft),+ [serializedDraft],+ );++ return filterNewParticipantMentions({+ participantMentions,+ thread,+ currentWorkspaceMemberId: currentWorkspaceMember?.id,+ });+};diff --git a/packages/twenty-front/src/modules/ai/types/AgentChatParticipantMention.ts b/packages/twenty-front/src/modules/ai/types/AgentChatParticipantMention.tsnew file mode 100644index 00000000000..8c4d3170ed6--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AgentChatParticipantMention.ts@@ -0,0 +1,4 @@+export type AgentChatParticipantMention = {+ workspaceMemberId: string;+ label: string;+};diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/filterNewParticipantMentions.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/filterNewParticipantMentions.test.tsnew file mode 100644index 00000000000..3d9c9eb47b3--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/filterNewParticipantMentions.test.ts@@ -0,0 +1,33 @@+import { filterNewParticipantMentions } from '@/ai/utils/filterNewParticipantMentions';++const participantMentions = [+ { workspaceMemberId: 'jane', label: 'Jane Austen' },+ { workspaceMemberId: 'jony', label: 'Jony Ive' },+ { workspaceMemberId: 'phil', label: 'Phil Schiller' },+ { workspaceMemberId: 'tim', label: 'Tim Apple' },+];++describe('filterNewParticipantMentions', () => {+ it('leaves out the sender, the owner and members already following', () => {+ expect(+ filterNewParticipantMentions({+ participantMentions,+ thread: {+ workspaceMemberId: 'jane',+ writerWorkspaceMemberIds: ['jony'],+ },+ currentWorkspaceMemberId: 'tim',+ }),+ ).toEqual([{ workspaceMemberId: 'phil', label: 'Phil Schiller' }]);+ });++ it('only leaves out the sender of a chat that does not exist yet', () => {+ expect(+ filterNewParticipantMentions({+ participantMentions,+ thread: null,+ currentWorkspaceMemberId: 'tim',+ }),+ ).toEqual(participantMentions.slice(0, 3));+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getParticipantMentionsFromSerializedDocument.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getParticipantMentionsFromSerializedDocument.test.tsnew file mode 100644index 00000000000..3a11c27f54a--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getParticipantMentionsFromSerializedDocument.test.ts@@ -0,0 +1,85 @@+import { CoreObjectNameSingular } from 'twenty-shared/types';++import { getParticipantMentionsFromSerializedDocument } from '@/ai/utils/getParticipantMentionsFromSerializedDocument';+import { serializeJsonContentAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeJsonContentAsAdvancedTextEditorDocument';+import { getMentionTagContent } from '@/mention/utils/getMentionTagContent';++const JANE_ID = '20202020-463f-435b-828c-107e007a2711';+const JONY_ID = '20202020-77d5-4cb6-b60a-f4a835a85d61';++const serializeParagraph = (content: ReturnType<typeof getMentionTagContent>) =>+ serializeJsonContentAsAdvancedTextEditorDocument({+ type: 'doc',+ content: [{ type: 'paragraph', content }],+ });++const mentionWorkspaceMember = ({+ recordId,+ label,+ shouldAddAsParticipant,+}: {+ recordId: string;+ label: string;+ shouldAddAsParticipant: boolean;+}) =>+ getMentionTagContent({+ recordId,+ objectNameSingular: CoreObjectNameSingular.WorkspaceMember,+ label,+ imageUrl: '',+ shouldAddAsParticipant,+ });++describe('getParticipantMentionsFromSerializedDocument', () => {+ it('returns each member mentioned to be added once', () => {+ const serializedDocument = serializeParagraph([+ ...mentionWorkspaceMember({+ recordId: JANE_ID,+ label: 'Jane Austen',+ shouldAddAsParticipant: true,+ }),+ ...mentionWorkspaceMember({+ recordId: JANE_ID,+ label: 'Jane Austen',+ shouldAddAsParticipant: true,+ }),+ ...mentionWorkspaceMember({+ recordId: JONY_ID,+ label: 'Jony Ive',+ shouldAddAsParticipant: true,+ }),+ ]);++ expect(+ getParticipantMentionsFromSerializedDocument(serializedDocument),+ ).toEqual([+ { workspaceMemberId: JANE_ID, label: 'Jane Austen' },+ { workspaceMemberId: JONY_ID, label: 'Jony Ive' },+ ]);+ });++ it('leaves out members whose addition was undone and record mentions', () => {+ const serializedDocument = serializeParagraph([+ ...mentionWorkspaceMember({+ recordId: JANE_ID,+ label: 'Jane Austen',+ shouldAddAsParticipant: false,+ }),+ ...getMentionTagContent({+ recordId: JONY_ID,+ objectNameSingular: CoreObjectNameSingular.Person,+ label: 'Jony Ive',+ imageUrl: '',+ shouldAddAsParticipant: true,+ }),+ ]);++ expect(+ getParticipantMentionsFromSerializedDocument(serializedDocument),+ ).toEqual([]);+ });++ it('returns nothing for an empty draft', () => {+ expect(getParticipantMentionsFromSerializedDocument('')).toEqual([]);+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/filterNewParticipantMentions.ts b/packages/twenty-front/src/modules/ai/utils/filterNewParticipantMentions.tsnew file mode 100644index 00000000000..e74740438a2--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/filterNewParticipantMentions.ts@@ -0,0 +1,29 @@+import { type AgentChatParticipantMention } from '@/ai/types/AgentChatParticipantMention';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';++export const filterNewParticipantMentions = ({+ participantMentions,+ thread,+ currentWorkspaceMemberId,+}: {+ participantMentions: AgentChatParticipantMention[];+ thread:+ | Pick<+ AgentChatThreadRecord,+ 'workspaceMemberId' | 'writerWorkspaceMemberIds'+ >+ | null+ | undefined;+ currentWorkspaceMemberId: string | undefined;+}): AgentChatParticipantMention[] => {+ const existingParticipantIds = [+ currentWorkspaceMemberId,+ thread?.workspaceMemberId,+ ...(thread?.writerWorkspaceMemberIds ?? []),+ ];++ return participantMentions.filter(+ ({ workspaceMemberId }) =>+ !existingParticipantIds.includes(workspaceMemberId),+ );+};diff --git a/packages/twenty-front/src/modules/ai/utils/getParticipantMentionsFromSerializedDocument.ts b/packages/twenty-front/src/modules/ai/utils/getParticipantMentionsFromSerializedDocument.tsnew file mode 100644index 00000000000..ae64e03f392--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getParticipantMentionsFromSerializedDocument.ts@@ -0,0 +1,50 @@+import { isNonEmptyString } from '@sniptt/guards';+import { CoreObjectNameSingular } from 'twenty-shared/types';+import {+ isDefined,+ parseCanonicalTipTapJsonDocument,+ TIPTAP_NODE_TYPES,+ type TipTapNode,+} from 'twenty-shared/utils';++import { type AgentChatParticipantMention } from '@/ai/types/AgentChatParticipantMention';++const getParticipantMentionsFromNode = (+ node: TipTapNode,+): AgentChatParticipantMention[] => {+ const workspaceMemberId = node.attrs?.recordId;+ const label = node.attrs?.label;++ const isParticipantMention =+ node.type === TIPTAP_NODE_TYPES.MENTION_TAG &&+ node.attrs?.objectNameSingular === CoreObjectNameSingular.WorkspaceMember &&+ node.attrs?.shouldAddAsParticipant === true &&+ isNonEmptyString(workspaceMemberId);++ return [+ ...(isParticipantMention+ ? [{ workspaceMemberId, label: isNonEmptyString(label) ? label : '' }]+ : []),+ ...(node.content ?? []).flatMap(getParticipantMentionsFromNode),+ ];+};++export const getParticipantMentionsFromSerializedDocument = (+ serializedDocument: string,+): AgentChatParticipantMention[] => {+ const document = parseCanonicalTipTapJsonDocument(serializedDocument);++ if (!isDefined(document)) {+ return [];+ }++ const participantMentions = getParticipantMentionsFromNode(document);++ return participantMentions.filter(+ ({ workspaceMemberId }, index) =>+ participantMentions.findIndex(+ (participantMention) =>+ participantMention.workspaceMemberId === workspaceMemberId,+ ) === index,+ );+};diff --git a/packages/twenty-front/src/modules/mention/constants/WorkspaceMemberMentionSuggestionPluginKey.ts b/packages/twenty-front/src/modules/mention/constants/WorkspaceMemberMentionSuggestionPluginKey.tsnew file mode 100644index 00000000000..e87b395c923--- /dev/null+++ b/packages/twenty-front/src/modules/mention/constants/WorkspaceMemberMentionSuggestionPluginKey.ts@@ -0,0 +1,5 @@+import { PluginKey } from '@tiptap/pm/state';++export const WORKSPACE_MEMBER_MENTION_SUGGESTION_PLUGIN_KEY = new PluginKey(+ 'workspace-member-mention-suggestion',+);diff --git a/packages/twenty-front/src/modules/mention/extensions/MentionSuggestion.ts b/packages/twenty-front/src/modules/mention/extensions/MentionSuggestion.tsindex ba674871430..667bf3f68a3 100644--- a/packages/twenty-front/src/modules/mention/extensions/MentionSuggestion.ts+++ b/packages/twenty-front/src/modules/mention/extensions/MentionSuggestion.ts@@ -29,7 +29,7 @@ export const MentionSuggestion = Extension.create<MentionSuggestionOptions>({Suggestion<MentionSearchResult>({pluginKey: MENTION_SUGGESTION_PLUGIN_KEY,editor: this.editor,- char: '@',+ char: '#',items: async ({ query }) => {try {return await this.storage.searchMentionRecords(query);diff --git a/packages/twenty-front/src/modules/mention/extensions/MentionTag.ts b/packages/twenty-front/src/modules/mention/extensions/MentionTag.tsindex 63cdbc0f0c6..da457bb7071 100644--- a/packages/twenty-front/src/modules/mention/extensions/MentionTag.ts+++ b/packages/twenty-front/src/modules/mention/extensions/MentionTag.ts@@ -2,6 +2,7 @@ import { formatRecordReference } from '@/ai/utils/formatRecordReference';import { MentionChip } from '@/mention/components/MentionChip';import { Node } from '@tiptap/core';import { mergeAttributes, ReactNodeViewRenderer } from '@tiptap/react';+import { CoreObjectNameSingular } from 'twenty-shared/types';export const MentionTag = Node.create({name: 'mentionTag',@@ -43,6 +44,10 @@ export const MentionTag = Node.create({default: false,rendered: false,},+ shouldAddAsParticipant: {+ default: false,+ rendered: false,+ },}),renderHTML: ({ node, HTMLAttributes }) => {@@ -52,7 +57,7 @@ export const MentionTag = Node.create({'data-type': 'mentionTag',class: 'mention-tag',}),- `@${node.attrs.label}`,+ `${node.attrs.objectNameSingular === CoreObjectNameSingular.WorkspaceMember ? '@' : '#'}${node.attrs.label}`,];},diff --git a/packages/twenty-front/src/modules/mention/extensions/WorkspaceMemberMentionSuggestion.ts b/packages/twenty-front/src/modules/mention/extensions/WorkspaceMemberMentionSuggestion.tsnew file mode 100644index 00000000000..baa663009dd--- /dev/null+++ b/packages/twenty-front/src/modules/mention/extensions/WorkspaceMemberMentionSuggestion.ts@@ -0,0 +1,64 @@+import { Extension } from '@tiptap/core';+import Suggestion from '@tiptap/suggestion';++import { MentionSuggestionMenu } from '@/mention/components/MentionSuggestionMenu';+import { WORKSPACE_MEMBER_MENTION_SUGGESTION_PLUGIN_KEY } from '@/mention/constants/WorkspaceMemberMentionSuggestionPluginKey';+import type { MentionSearchResult } from '@/mention/types/MentionSearchResult';+import { getMentionTagContent } from '@/mention/utils/getMentionTagContent';+import { createSuggestionRenderLifecycle } from '@/ui/suggestion/components/createSuggestionRenderLifecycle';++type WorkspaceMemberMentionSuggestionOptions = {+ searchWorkspaceMembers: (query: string) => MentionSearchResult[];+};++export const WorkspaceMemberMentionSuggestion =+ Extension.create<WorkspaceMemberMentionSuggestionOptions>({+ name: 'workspace-member-mention-suggestion',++ addOptions: () => ({+ searchWorkspaceMembers: () => [],+ }),++ addStorage() {+ return {+ searchWorkspaceMembers: this.options.searchWorkspaceMembers,+ };+ },++ addProseMirrorPlugins() {+ return [+ Suggestion<MentionSearchResult>({+ pluginKey: WORKSPACE_MEMBER_MENTION_SUGGESTION_PLUGIN_KEY,+ editor: this.editor,+ char: '@',+ items: ({ query }) => this.storage.searchWorkspaceMembers(query),+ command: ({ editor, range, props: selectedItem }) => {+ editor+ .chain()+ .focus()+ .deleteRange(range)+ .insertContent(+ getMentionTagContent({+ ...selectedItem,+ shouldAddAsParticipant: true,+ }),+ )+ .run();+ },+ render: () =>+ createSuggestionRenderLifecycle(+ {+ component: MentionSuggestionMenu,+ getMenuProps: ({ items, onSelect, editor, range }) => ({+ items,+ onSelect,+ editor,+ range,+ }),+ },+ this.editor,+ ),+ }),+ ];+ },+ });diff --git a/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionSuggestion.test.ts b/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionSuggestion.test.tsindex 0b3dcbeddcb..175a6c3b0a4 100644--- a/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionSuggestion.test.ts+++ b/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionSuggestion.test.ts@@ -61,12 +61,12 @@ describe('MentionSuggestion', () => {expect(hasSuggestionPlugin).toBe(true);});- it('should accept @ character in editor content', () => {+ it('should accept # character in editor content', () => {editor.commands.setContent('<p></p>');editor.commands.focus();- editor.commands.insertContent('@');+ editor.commands.insertContent('#');- expect(editor.getText()).toContain('@');+ expect(editor.getText()).toContain('#');});it('should use default empty search function when not configured', () => {diff --git a/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionTag.test.ts b/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionTag.test.tsindex eea702c983a..d45738252dd 100644--- a/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionTag.test.ts+++ b/packages/twenty-front/src/modules/mention/extensions/__tests__/MentionTag.test.ts@@ -182,5 +182,45 @@ describe('MentionTag', () => {expect(html).toContain('data-type="mentionTag"');expect(html).toContain('class="mention-tag"');});++ it('should prefix records with # and workspace members with @', () => {+ editor.commands.setContent({+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [+ {+ type: 'mentionTag',+ attrs: {+ recordId: 'person-id',+ objectNameSingular: 'person',+ label: 'Linus',+ },+ },+ {+ type: 'mentionTag',+ attrs: {+ recordId: 'member-id',+ objectNameSingular: 'workspaceMember',+ label: 'Grace',+ shouldAddAsParticipant: true,+ },+ },+ ],+ },+ ],+ });++ const html = editor.getHTML();+ const renderedMentionTexts = Array.from(+ new DOMParser()+ .parseFromString(html, 'text/html')+ .querySelectorAll('.mention-tag'),+ ).map((mention) => mention.textContent);++ expect(renderedMentionTexts).toEqual(['#Linus', '@Grace']);+ expect(html).not.toContain('shouldAddAsParticipant');+ });});});diff --git a/packages/twenty-front/src/modules/mention/hooks/useWorkspaceMemberMentionSearch.ts b/packages/twenty-front/src/modules/mention/hooks/useWorkspaceMemberMentionSearch.tsnew file mode 100644index 00000000000..7e0824fed99--- /dev/null+++ b/packages/twenty-front/src/modules/mention/hooks/useWorkspaceMemberMentionSearch.ts@@ -0,0 +1,43 @@+import { useCallback } from 'react';+import { CoreObjectNameSingular } from 'twenty-shared/types';++import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';+import type { MentionSearchResult } from '@/mention/types/MentionSearchResult';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';++const WORKSPACE_MEMBER_MENTION_SEARCH_LIMIT = 50;++export const useWorkspaceMemberMentionSearch = () => {+ const currentWorkspaceMembers = useAtomStateValue(+ currentWorkspaceMembersState,+ );++ const searchWorkspaceMembers = useCallback(+ (query: string): MentionSearchResult[] => {+ const normalizedQuery = query.trim().toLowerCase();++ return currentWorkspaceMembers+ .map((workspaceMember) => ({+ workspaceMember,+ fullName:+ `${workspaceMember.name.firstName} ${workspaceMember.name.lastName}`.trim(),+ }))+ .filter(({ workspaceMember, fullName }) =>+ `${fullName} ${workspaceMember.userEmail}`+ .toLowerCase()+ .includes(normalizedQuery),+ )+ .slice(0, WORKSPACE_MEMBER_MENTION_SEARCH_LIMIT)+ .map(({ workspaceMember, fullName }) => ({+ recordId: workspaceMember.id,+ objectNameSingular: CoreObjectNameSingular.WorkspaceMember,+ objectLabelSingular: workspaceMember.userEmail,+ label: fullName || workspaceMember.userEmail,+ imageUrl: workspaceMember.avatarUrl ?? '',+ }));+ },+ [currentWorkspaceMembers],+ );++ return { searchWorkspaceMembers };+};diff --git a/packages/twenty-front/src/modules/mention/utils/getMentionTagContent.ts b/packages/twenty-front/src/modules/mention/utils/getMentionTagContent.tsindex 4e47ebfbadf..72bcc989a1c 100644--- a/packages/twenty-front/src/modules/mention/utils/getMentionTagContent.ts+++ b/packages/twenty-front/src/modules/mention/utils/getMentionTagContent.ts@@ -8,10 +8,14 @@ export const getMentionTagContent = ({label,imageUrl,isConversationTarget = false,+ shouldAddAsParticipant = false,}: Pick<SearchRecord,'recordId' | 'objectNameSingular' | 'label' | 'imageUrl'-> & { isConversationTarget?: boolean }): JSONContent[] => [+> & {+ isConversationTarget?: boolean;+ shouldAddAsParticipant?: boolean;+}): JSONContent[] => [{type: 'mentionTag',attrs: {@@ -20,6 +24,7 @@ export const getMentionTagContent = ({label,imageUrl: imageUrl ?? '',isConversationTarget,+ shouldAddAsParticipant,},},{ type: 'text', text: ' ' },diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.tsindex aaa1648fcd7..57e0fd404a5 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.ts@@ -1,5 +1,6 @@import { Module } from '@nestjs/common';+import { RecordShareModule } from 'src/engine/core-modules/record-share/record-share.module';import { RecordShareStorageModule } from 'src/engine/core-modules/record-share/record-share-storage.module';import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';import { AgentChatThreadLifecycleModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module';@@ -20,6 +21,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheAgentChatThreadLifecycleModule,AgentHistoryModule,PermissionsModule,+ RecordShareModule,RecordShareStorageModule,UserWorkspaceModule,WorkspaceCacheModule,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-thread-participant.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-thread-participant.resolver.tsindex 7cfe16895cd..d7f8f8d99d4 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-thread-participant.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-thread-participant.resolver.ts@@ -13,6 +13,7 @@ import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { AgentChatThreadParticipantDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread-participant.dto';import { AgentChatThreadParticipantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service';+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';@UseGuards(@@ -35,6 +36,7 @@ import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/aiexport class AgentChatThreadParticipantResolver {constructor(private readonly participantService: AgentChatThreadParticipantService,+ private readonly threadService: AgentChatThreadService,) {}@Query(() => [AgentChatThreadParticipantDTO])@@ -114,4 +116,21 @@ export class AgentChatThreadParticipantResolver {workspaceId,});}++ // Returns the members who were added, leaving out those who cannot reply in the chat+ @Mutation(() => [UUIDScalarType])+ async addAgentChatThreadParticipants(+ @Args('threadId', { type: () => UUIDScalarType }) threadId: string,+ @Args('workspaceMemberIds', { type: () => [UUIDScalarType] })+ participantWorkspaceMemberIds: string[],+ @AuthWorkspaceMemberId() workspaceMemberId: string,+ @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ ): Promise<string[]> {+ return this.threadService.addParticipants({+ threadId,+ participantWorkspaceMemberIds,+ workspaceMemberId,+ workspaceId,+ });+ }}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.tsindex ab1917a12d4..4991c6062df 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts@@ -7,10 +7,13 @@ import { Injectable } from '@nestjs/common';import chunk from 'lodash.chunk';import { PermissionFlagType } from 'twenty-shared/constants';+import { RecordShareAccessLevel } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { buildRecordShareLockKey } from 'src/engine/core-modules/record-share/utils/build-record-share-lock-key.util';+import { RecordShareException } from 'src/engine/core-modules/record-share/record-share.exception';import { RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';+import { RecordSharingService } from 'src/engine/core-modules/record-share/services/record-sharing.service';import { UserWorkspaceAuthContextService } from 'src/engine/core-modules/user-workspace/services/user-workspace-auth-context.service';import { type AgentChatThreadAccessArgs } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-access-args.type';import { findAgentChatFlatObjectMetadata } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-agent-chat-flat-object-metadata.util';@@ -29,6 +32,11 @@ import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/worksconst READABLE_THREAD_IDS_BATCH_SIZE = 1000;+const EDIT_ACCESS_LEVELS: (RecordShareAccessLevel | null | undefined)[] = [+ RecordShareAccessLevel.READ_WRITE,+ RecordShareAccessLevel.FULL,+];+@Injectable()export class AgentChatSharingService {constructor(@@ -36,6 +44,7 @@ export class AgentChatSharingService {private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,private readonly userAuthContextService: UserWorkspaceAuthContextService,private readonly recordShareStorageService: RecordShareStorageService,+ private readonly recordSharingService: RecordSharingService,private readonly workspaceCacheService: WorkspaceCacheService,private readonly permissionsService: PermissionsService,private readonly workspaceOrmManager: WorkspaceOrmManager,@@ -125,6 +134,70 @@ export class AgentChatSharingService {}, authContext);}+ // Members join as editors so they can reply. Sharing is left to whoever may+ // manage it, so only the members who can reply afterwards are returned+ async shareThreadWithMembers({+ memberIds,+ ...args+ }: AgentChatThreadAccessArgs & {+ memberIds: string[];+ }): Promise<string[]> {+ const chatMemberIds = await this.filterMemberIds(memberIds, (memberId) =>+ this.getAuthContext({+ workspaceId: args.workspaceId,+ workspaceMemberId: memberId,+ }).then(() => true),+ );++ if (chatMemberIds.length === 0) {+ return [];+ }++ const objectMetadata = await this.getThreadObjectMetadata(args.workspaceId);+ const recordTarget = {+ objectMetadataId: objectMetadata.id,+ recordId: args.threadId,+ authContext: await this.getAuthContext(args),+ };+ const sharing = await this.recordSharingService.getSharing(recordTarget);++ if (+ sharing.canManageSharing &&+ !EDIT_ACCESS_LEVELS.includes(sharing.generalAccessLevel)+ ) {+ for (const memberId of chatMemberIds) {+ const memberShare = sharing.shares.find(+ ({ principalId }) => principalId === memberId,+ );++ if (EDIT_ACCESS_LEVELS.includes(memberShare?.accessLevel)) {+ continue;+ }++ // A member whose role cannot reach chats is refused the share+ await this.recordSharingService+ .setShare({+ ...recordTarget,+ principal: { workspaceMemberId: memberId },+ accessLevel: RecordShareAccessLevel.READ_WRITE,+ })+ .catch((error: unknown) => {+ if (!(error instanceof RecordShareException)) {+ throw error;+ }+ });+ }+ }++ return this.filterMemberIds(chatMemberIds, (memberId) =>+ this.getThreadWithAccess({+ ...args,+ workspaceMemberId: memberId,+ operationType: 'update',+ }).then(() => true),+ );+ }+async createThread(args: {workspaceId: string;workspaceMemberId: string;@@ -296,6 +369,29 @@ export class AgentChatSharingService {}}+ private async filterMemberIds(+ memberIds: string[],+ isKept: (memberId: string) => Promise<boolean>,+ ): Promise<string[]> {+ const keptMemberIds = await Promise.all(+ memberIds.map(async (memberId) => {+ try {+ return (await isKept(memberId)) ? memberId : null;+ } catch (error) {+ if (+ error instanceof AiException &&+ error.code === AiExceptionCode.THREAD_NOT_FOUND+ ) {+ return null;+ }+ throw error;+ }+ }),+ );++ return keptMemberIds.filter(isDefined);+ }+private async getThreadObjectMetadata(workspaceId: string) {const { flatObjectMetadataMaps } =await this.workspaceCacheService.getOrRecompute(workspaceId, [diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.tsindex da8dcc8d2be..964402de77f 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.ts@@ -128,6 +128,25 @@ export class AgentChatThreadParticipantService {);}+ // A mention brings the chat back unread for the mentioned member, who the+ // caller has already checked can reply in it+ async markAsMentioned(+ args: AgentChatThreadAccessArgs,+ ): Promise<AgentChatThreadParticipantRow | null> {+ return this.writeOne(+ args,+ ({ participantTable }) =>+ `INSERT INTO ${participantTable} AS participant ("threadId", "workspaceMemberId")+ VALUES ($1, $2)+ ON CONFLICT ("threadId", "workspaceMemberId") DO UPDATE SET+ "lastReadAt" = NULL,+ "archivedAt" = NULL,+ "snoozedUntil" = NULL,+ "updatedAt" = now()+ RETURNING *`,+ );+ }+archive(args: AgentChatThreadAccessArgs,): Promise<AgentChatThreadParticipantDTO> {diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.tsindex 4f62f00aedc..c561d4e933b 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts@@ -98,6 +98,66 @@ export class AgentChatThreadService {await this.emitThreadActivityUpdated({ workspaceId, thread, activity });}+ // A mentioned member follows the chat like one who wrote in it, and finds+ // it unread in their inbox even if they had read or archived it+ async addParticipants({+ participantWorkspaceMemberIds,+ ...args+ }: AgentChatThreadAccessArgs & {+ participantWorkspaceMemberIds: string[];+ }): Promise<string[]> {+ const thread = await this.getWritableThread(args);+ const candidateMemberIds = [+ ...new Set(participantWorkspaceMemberIds),+ ].filter((memberId) => memberId !== args.workspaceMemberId);++ if (candidateMemberIds.length === 0) {+ return [];+ }++ const participantMemberIds =+ await this.sharingService.shareThreadWithMembers({+ ...args,+ memberIds: candidateMemberIds,+ });++ if (+ participantMemberIds.length === 0 ||+ !(await this.sharingService.hasInboxState(args.workspaceId))+ ) {+ return participantMemberIds;+ }++ await this.threadRepository.query(args.workspaceId, ({ manager, table }) =>+ manager.query(+ `UPDATE ${table('agentChatThread')}+ SET "updatedAt" = now(),+ "writerWorkspaceMemberIds" = COALESCE("writerWorkspaceMemberIds", '{}') || ARRAY(+ SELECT member_id FROM unnest($2::text[]) AS member_id+ WHERE NOT member_id = ANY(COALESCE("writerWorkspaceMemberIds", '{}'))+ AND member_id IS DISTINCT FROM "workspaceMemberId"::text+ )+ WHERE id = $1`,+ [args.threadId, participantMemberIds],+ ),+ );++ for (const participantMemberId of participantMemberIds) {+ await this.participantService.markAsMentioned({+ workspaceId: args.workspaceId,+ threadId: args.threadId,+ workspaceMemberId: participantMemberId,+ });+ }++ await this.threadRecordEventService.emitThreadUpdated({+ workspaceId: args.workspaceId,+ threadBefore: thread,+ });++ return participantMemberIds;+ }+// Activity no member wrote, such as an agent turn or an application's// message, leaves the chat unread for everyoneasync recordThreadActivity({diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snapindex 05a071ea6f1..317f566075a 100644--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap@@ -71,6 +71,7 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an"AgentChatResolver.sendChatMessage {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AgentChatResolver.stopAgentChatStream {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AgentChatSubscriptionResolver.onAgentChatEvent {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",+ "AgentChatThreadParticipantResolver.addAgentChatThreadParticipants {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AgentChatThreadParticipantResolver.archiveAgentChatThread {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AgentChatThreadParticipantResolver.markAgentChatThreadAsRead {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AgentChatThreadParticipantResolver.markAgentChatThreadAsUnread {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.tsindex b844184e9f7..d1c60499fb0 100644--- a/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.ts@@ -48,6 +48,20 @@ const SNOOZE = parse(const buildFutureSnoozedUntil = () =>new Date(Date.now() + 30_000).toISOString();+const ADD_PARTICIPANTS = parse(+ `mutation AddParticipants($threadId: UUID!, $workspaceMemberIds: [UUID!]!) { addAgentChatThreadParticipants(threadId: $threadId, workspaceMemberIds: $workspaceMemberIds) }`,+);++const addParticipants = (+ threadId: string,+ workspaceMemberIds: string[],+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,+) =>+ makeMetadataApiRequest(+ { query: ADD_PARTICIPANTS, variables: { threadId, workspaceMemberIds } },+ token,+ );+type Participant = {id: string;threadId: string;@@ -164,7 +178,31 @@ const listParticipantRecordIds = async (token: string): Promise<string[]> => {);};-const setShareWithJony = async (threadId: string, enabled: boolean) => {+type ManualShare = {+ threadId: string;+ workspaceMemberId: string;+ accessLevel: RecordShareAccessLevel;+};++// Destroying a chat keeps its grants, so every grant a test enables is+// disabled again after it+const enabledManualShares: ManualShare[] = [];++const setShareWithMember = async ({+ threadId,+ workspaceMemberId,+ accessLevel,+ enabled,+}: {+ threadId: string;+ workspaceMemberId: string;+ accessLevel: RecordShareAccessLevel;+ enabled: boolean;+}) => {+ if (enabled) {+ enabledManualShares.push({ threadId, workspaceMemberId, accessLevel });+ }+const { flatObjectMetadataMaps } =await getAppProviderByClassName<WorkspaceCacheService>('WorkspaceCacheService',@@ -178,15 +216,23 @@ const setShareWithJony = async (threadId: string, enabled: boolean) => {STANDARD_OBJECTS.agentChatThread.universalIdentifier]!.id,recordId: threadId,- principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ principalId: workspaceMemberId,principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,- accessLevel: RecordShareAccessLevel.READ,+ accessLevel,sourceId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,},enabled,});};+const setShareWithJony = (threadId: string, enabled: boolean) =>+ setShareWithMember({+ threadId,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ accessLevel: RecordShareAccessLevel.READ,+ enabled,+ });+describe('Chat thread participant state through the authenticated API', () => {const createdThreadIds: string[] = [];@@ -201,6 +247,10 @@ describe('Chat thread participant state through the authenticated API', () => {afterEach(async () => {jest.restoreAllMocks();+ for (const manualShare of enabledManualShares.splice(0)) {+ await setShareWithMember({ ...manualShare, enabled: false });+ }+ // Mentions share chats with Jony from the code under testfor (const threadId of createdThreadIds.splice(0)) {await setShareWithJony(threadId, false);await destroyAgentChatThread({ threadId });@@ -667,4 +717,116 @@ describe('Chat thread participant state through the authenticated API', () => {await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),).toBeUndefined();});++ it('shares the thread with a mentioned member and brings it to their inbox unread', async () => {+ const threadId = await createTestThread();++ expect(+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),+ ).toBeUndefined();++ const response = await addParticipants(threadId, [+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ ]);++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.addAgentChatThreadParticipants).toEqual([+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ ]);+ expect(+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),+ ).toMatchObject({ lastReadAt: null, archivedAt: null, snoozedUntil: null });+ expect(+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds,+ ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);++ // Editors can mention others too; the owner keeps following as owner+ const addedByJony = await addParticipants(+ threadId,+ [WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ );++ expect(addedByJony.body.errors).toBeUndefined();+ expect(addedByJony.body.data.addAgentChatThreadParticipants).toEqual([+ WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ ]);+ expect(await findMyParticipant(threadId)).toMatchObject({+ lastReadAt: null,+ });+ expect(+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds,+ ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);+ });++ it('brings the thread back unread for a participant who had read and archived it', async () => {+ const threadId = await createTestThread();++ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);+ await runThreadMutation(+ 'markAgentChatThreadAsRead',+ threadId,+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ );+ await runThreadMutation(+ 'archiveAgentChatThread',+ threadId,+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ );+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);++ expect(+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),+ ).toMatchObject({ lastReadAt: null, archivedAt: null, snoozedUntil: null });+ expect(+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds,+ ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);+ });++ it('refuses a member who can only read the thread', async () => {+ const threadId = await createTestThread();++ await setShareWithJony(threadId, true);++ const response = await addParticipants(+ threadId,+ [WORKSPACE_MEMBER_DATA_SEED_IDS.TIM],+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ );++ expect(response.body.errors[0].extensions.code).toBe('NOT_FOUND');+ expect(+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds ?? [],+ ).toEqual([]);+ });++ it('leaves out a member who could only read the thread when the sender cannot share it', async () => {+ const threadId = await createTestThread();++ await setShareWithMember({+ threadId,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ accessLevel: RecordShareAccessLevel.READ_WRITE,+ enabled: true,+ });+ await setShareWithMember({+ threadId,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,+ accessLevel: RecordShareAccessLevel.READ,+ enabled: true,+ });++ const response = await addParticipants(+ threadId,+ [WORKSPACE_MEMBER_DATA_SEED_IDS.TIM],+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ );++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.addAgentChatThreadParticipants).toEqual([]);+ expect(+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds ?? [],+ ).toEqual([]);+ });});