Skip to content

The open alternative to Salesforce, designed for AI.

Resolve mentions when members reply or answer (#29214)

Raphaël Bosia8b8468fe6ff
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useOptimisticallyRestoreOnSend.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useOptimisticallyRestoreOnSend.test.tsx
index bb81e3b05a0..ba97791562f 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useOptimisticallyRestoreOnSend.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useOptimisticallyRestoreOnSend.test.tsx
@@ -15,14 +15,21 @@ const ARCHIVED_PARTICIPANT = {
archivedAt: '2026-10-01T11:00:00.000Z',
snoozedUntil: null,
isSubscribed: true,
- lastMentionedAt: null,
+ lastMentionedAt: LAST_ACTIVITY_AT,
mentionsResolvedAt: null,
id: 'participant-id',
updatedAt: '2026-10-01T11:00:00.000Z',
};
+const renderRestoreHook = (store: ReturnType<typeof createStore>) =>
+ renderHook(() => useOptimisticallyRestoreOnSend(), {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <Provider store={store}>{children}</Provider>
+ ),
+ });
+
describe('useOptimisticallyRestoreOnSend', () => {
- it('moves a thread the member writes in back to their inbox, and undoes it if sending fails', () => {
+ it('resolves the mention and restores the inbox on send, and undoes both if sending fails', async () => {
const store = createStore();
store.set(recordStoreFamilyState.atomFamily(THREAD_ID), {
@@ -34,20 +41,14 @@ describe('useOptimisticallyRestoreOnSend', () => {
[THREAD_ID]: ARCHIVED_PARTICIPANT,
});
- const { result } = renderHook(() => useOptimisticallyRestoreOnSend(), {
- wrapper: ({ children }: { children: ReactNode }) => (
- <Provider store={store}>{children}</Provider>
- ),
- });
+ const { result } = renderRestoreHook(store);
const sentAt = '2026-10-01T12:00:00.000Z';
- let rollback: () => void = () => undefined;
-
- act(() => {
- rollback = result.current.applyOptimisticRestore({
+ const rollback = await act(() =>
+ result.current.applyOptimisticRestore({
threadId: THREAD_ID,
optimisticUpdatedAt: sentAt,
- });
- });
+ }),
+ );
expect(
store.get(recordStoreFamilyState.atomFamily(THREAD_ID)),
@@ -61,8 +62,8 @@ describe('useOptimisticallyRestoreOnSend', () => {
archivedAt: null,
snoozedUntil: null,
isSubscribed: true,
- lastMentionedAt: null,
- mentionsResolvedAt: null,
+ lastMentionedAt: LAST_ACTIVITY_AT,
+ mentionsResolvedAt: LAST_ACTIVITY_AT,
id: 'participant-id',
updatedAt: ARCHIVED_PARTICIPANT.updatedAt,
});
@@ -76,4 +77,36 @@ describe('useOptimisticallyRestoreOnSend', () => {
store.get(agentChatThreadParticipantsState.atom)?.[THREAD_ID],
).toEqual(ARCHIVED_PARTICIPANT);
});
+
+ it('preserves a newer participant event when sending fails', async () => {
+ const store = createStore();
+
+ store.set(agentChatThreadParticipantsState.atom, {
+ [THREAD_ID]: ARCHIVED_PARTICIPANT,
+ });
+
+ const { result } = renderRestoreHook(store);
+ const rollback = await act(() =>
+ result.current.applyOptimisticRestore({
+ threadId: THREAD_ID,
+ optimisticUpdatedAt: '2026-10-01T12:00:00.000Z',
+ }),
+ );
+
+ const mentionedAgainParticipant = {
+ ...ARCHIVED_PARTICIPANT,
+ lastMentionedAt: '2026-10-01T12:01:00.000Z',
+ updatedAt: '2026-10-01T12:01:00.000Z',
+ };
+
+ store.set(agentChatThreadParticipantsState.atom, {
+ [THREAD_ID]: mentionedAgainParticipant,
+ });
+
+ act(() => rollback());
+
+ expect(
+ store.get(agentChatThreadParticipantsState.atom)?.[THREAD_ID],
+ ).toEqual(mentionedAgainParticipant);
+ });
});
diff --git a/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.ts b/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.ts
index 33ddd59e845..fc977b910c1 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.ts
@@ -1,4 +1,5 @@
import { useStore } from 'jotai';
+import { getAgentChatMentionsResolvedAt } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
import { AGENT_CHAT_THREAD_PARTICIPANT_UNSAVED_UPDATED_AT } from '@/ai/constants/AgentChatThreadParticipantUnsavedUpdatedAt';
@@ -45,6 +46,9 @@ export const useOptimisticallyRestoreOnSend = () => {
...participants[threadId],
threadId,
lastReadAt: optimisticUpdatedAt,
+ mentionsResolvedAt: getAgentChatMentionsResolvedAt(
+ previousParticipant ?? {},
+ ),
archivedAt: null,
snoozedUntil: null,
isSubscribed: true,
@@ -60,6 +64,9 @@ export const useOptimisticallyRestoreOnSend = () => {
? { ...visit, isUnread: false, isKeptUnread: false }
: visit,
);
+ const optimisticParticipant = store.get(
+ agentChatThreadParticipantsState.atom,
+ )?.[threadId];
return () => {
applyAgentChatThreadUpdate({
@@ -71,7 +78,10 @@ export const useOptimisticallyRestoreOnSend = () => {
...(isDefined(thread?.deletedAt) && { deletedAt: thread.deletedAt }),
});
store.set(agentChatThreadParticipantsState.atom, (participants) => {
- if (!isDefined(participants)) {
+ if (
+ !isDefined(participants) ||
+ participants[threadId] !== optimisticParticipant
+ ) {
return participants;
}
diff --git a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
index 670b26a5e94..8c52126cbd7 100644
--- a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
+++ b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
@@ -239,16 +239,17 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
chatRecordEvents as never,
conversationWriter,
chatThreadService,
+ { resolveMentionInTransaction: jest.fn() } as never,
);
const createQueueService = (messageRepository: typeof messages) =>
new AgentChatQueueService(
turns,
messageRepository,
- messageParts,
{} as never,
conversationWriter,
chatThreadService,
+ { resolveMentionInTransaction: jest.fn() } as never,
);
const createActorService = (messageRepository: typeof messages) =>
@@ -811,7 +812,8 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
const openingTurn = await turns.insertAndReturnOne(WORKSPACE_ID, {
threadId: thread.id,
});
- const message = await chat.addMessage({
+ const message = await chat.addMessageAndResolveMention({
+ workspaceMemberId: MEMBER_ID,
workspaceId: WORKSPACE_ID,
userWorkspaceId: OWNER_ID,
threadId: thread.id,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.thread-contexts.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.thread-contexts.spec.ts
index 85d76284d0d..6aa40ea863d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.thread-contexts.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.thread-contexts.spec.ts
@@ -33,6 +33,7 @@ const buildService = () => {
{} as never,
{} as never,
{} as never,
+ {} as never,
);
return { service, threadRepository, messageRepository };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-queue.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-queue.service.ts
index 1f4aaf69cdb..e329f1da372 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-queue.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-queue.service.ts
@@ -1,10 +1,13 @@
import { Injectable } from '@nestjs/common';
+import { randomUUID } from 'node:crypto';
+
import { FileFolder } from 'twenty-shared/types';
import { isNonEmptyArray } from 'twenty-shared/utils';
import { In, Like } from 'typeorm';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
+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 { type AiChatFileAttachment } from 'src/engine/metadata-modules/ai/ai-chat/types/ai-chat-file-attachment.type';
import { resolveMessageSenderApplicationId } from 'src/engine/metadata-modules/ai/ai-chat/utils/resolve-message-sender-application-id.util';
@@ -14,7 +17,6 @@ import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
-import { AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
import { AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
import { AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
@@ -27,12 +29,11 @@ export class AgentChatQueueService {
private readonly turnRepository: AgentHistoryRepository<AgentTurnWorkspaceEntity>,
@InjectAgentHistoryRepository('agentMessage')
private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,
- @InjectAgentHistoryRepository('agentMessagePart')
- private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
@InjectWorkspaceScopedRepository(FileEntity)
private readonly fileRepository: WorkspaceScopedRepository<FileEntity>,
private readonly conversationWriterService: AgentConversationWriterService,
private readonly threadService: AgentChatThreadService,
+ private readonly participantService: AgentChatThreadParticipantService,
) {}
async queueMessage({
@@ -53,7 +54,7 @@ export class AgentChatQueueService {
workspaceMemberId: string;
}) {
const messageValues = {
- ...(id ? { id } : {}),
+ id: id ?? randomUUID(),
threadId,
turnId: null,
role: AgentMessageRole.USER,
@@ -66,13 +67,6 @@ export class AgentChatQueueService {
}),
};
- const insertResult = await this.messageRepository.insert(
- workspaceId,
- messageValues,
- );
-
- const savedMessageId = (id ?? insertResult.identifiers[0].id) as string;
-
const validFiles = isNonEmptyArray(fileAttachments)
? await this.fileRepository.find(workspaceId, {
where: {
@@ -87,7 +81,7 @@ export class AgentChatQueueService {
const parts = [
{
- messageId: savedMessageId,
+ messageId: messageValues.id,
orderIndex: 0,
type: 'text',
textContent: text,
@@ -95,7 +89,7 @@ export class AgentChatQueueService {
...(fileAttachments ?? [])
.filter((attachment) => validFileIds.has(attachment.id))
.map((attachment, index) => ({
- messageId: savedMessageId,
+ messageId: messageValues.id,
orderIndex: index + 1,
type: 'file',
fileId: attachment.id,
@@ -103,7 +97,19 @@ export class AgentChatQueueService {
})),
];
- await this.messagePartRepository.insert(workspaceId, parts);
+ await this.conversationWriterService.runInTransaction(
+ workspaceId,
+ async (scope) => {
+ await this.participantService.resolveMentionInTransaction({
+ workspaceId,
+ workspaceMemberId,
+ threadId,
+ scope,
+ });
+ await scope.insert('agentMessage', messageValues);
+ await scope.insert('agentMessagePart', parts);
+ },
+ );
await this.threadService.notifyThreadActivityUpdated({
threadId,
@@ -112,10 +118,7 @@ export class AgentChatQueueService {
text,
});
- return {
- id: savedMessageId,
- ...messageValues,
- };
+ return messageValues;
}
async hasQueuedMessages({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
index 8ad389e6a57..35f55a57cc0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
@@ -512,17 +512,19 @@ export class AgentChatStreamingService {
workspaceId,
);
- const savedMessage = await this.agentChatService.addMessage({
- threadId,
- userWorkspaceId,
- id: messageId,
- uiMessage: {
- role: AgentMessageRole.USER,
- parts: [{ type: 'text' as const, text }, ...fileParts],
- },
- turnStatus,
- workspaceId,
- });
+ const savedMessage =
+ await this.agentChatService.addMessageAndResolveMention({
+ threadId,
+ workspaceMemberId,
+ userWorkspaceId,
+ id: messageId,
+ uiMessage: {
+ role: AgentMessageRole.USER,
+ parts: [{ type: 'text' as const, text }, ...fileParts],
+ },
+ turnStatus,
+ workspaceId,
+ });
await this.eventPublisherService.publish({
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.ts
index a891b6c2247..da8d922dc0b 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
@@ -17,12 +17,14 @@ import { END_AGENT_CHAT_THREAD_SNOOZE_JOB_NAME } from 'src/engine/metadata-modul
import { type EndAgentChatThreadSnoozeJobData } from 'src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job.types';
import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';
import { AgentChatThreadParticipantEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant-event.service';
+import { type AgentHistoryTransactionScope } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type';
import { type AgentChatThreadAccessArgs } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-access-args.type';
import { type AgentChatThreadWriteStep } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-write-step.type';
import { type AgentChatThreadParticipantRow } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-participant-row.type';
import { type AgentChatThreadActivity } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-activity.type';
import { buildAgentChatThreadParticipantOwnerShareInsert } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-owner-share-insert.util';
import { buildAgentChatThreadActivitySetClause } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-activity-set-clause.util';
+import { buildAgentChatThreadParticipantLockKey } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-lock-key.util';
import { getAgentChatThreadParticipantTable } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-agent-chat-thread-participant-table.util';
import { throwAgentChatThreadNotFound } from 'src/engine/metadata-modules/ai/ai-chat/utils/throw-agent-chat-thread-not-found.util';
import { findAgentChatSnoozeRemainingDelay } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-agent-chat-snooze-remaining-delay.util';
@@ -50,6 +52,9 @@ const ALL_MENTIONS_RESOLVED_AT = `GREATEST(participant."mentionsResolvedAt", par
const IS_IN_INBOX = `(participant."isSubscribed" AND (participant."archivedAt" IS NULL OR thread."lastActivityAt" > participant."archivedAt"))`;
+const PARTICIPANT_LOCK_QUERY =
+ 'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))';
+
// Saved as ended when already due, since its queued end may have run before this write
const buildSnoozeQuery: BuildParticipantWriteQuery = ({ participantTable }) =>
`INSERT INTO ${participantTable} AS participant ("threadId", "workspaceMemberId", "archivedAt", "snoozedUntil", "isSubscribed")
@@ -61,6 +66,17 @@ const buildSnoozeQuery: BuildParticipantWriteQuery = ({ participantTable }) =>
"updatedAt" = ${NEXT_PARTICIPANT_UPDATED_AT}
RETURNING *`;
+const buildMentionResolutionQuery = ({
+ participantTable,
+}: {
+ participantTable: string;
+}) =>
+ `UPDATE ${participantTable} AS participant
+ SET "mentionsResolvedAt" = ${ALL_MENTIONS_RESOLVED_AT}, "updatedAt" = ${NEXT_PARTICIPANT_UPDATED_AT}
+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2
+ AND ${AGENT_CHAT_HAS_UNRESOLVED_MENTION_PREDICATE}
+ RETURNING *`;
+
// Mirrored by applyAgentChatInboxAction for the optimistic copy
const INBOX_ACTION_QUERIES: Record<
AgentChatInboxAction,
@@ -266,6 +282,41 @@ export class AgentChatThreadParticipantService {
);
}
+ async resolveMention({
+ writeResponse,
+ ...args
+ }: AgentChatThreadAccessArgs & {
+ writeResponse: AgentChatThreadWriteStep;
+ }): Promise<void> {
+ await this.write(
+ { ...args, threadIds: [args.threadId] },
+ buildMentionResolutionQuery,
+ [],
+ writeResponse,
+ );
+ }
+
+ async resolveMentionInTransaction({
+ scope,
+ ...args
+ }: AgentChatThreadAccessArgs & {
+ scope: Pick<AgentHistoryTransactionScope, 'executeRawQuery'>;
+ }): Promise<void> {
+ await this.sharingService.assertHasMentionResolutionOrThrow(
+ args.workspaceId,
+ );
+ // Taken by the writes on the other pool too, so before and after stay this write's
+ await scope.executeRawQuery(PARTICIPANT_LOCK_QUERY, [
+ buildAgentChatThreadParticipantLockKey(args),
+ ]);
+ await scope.executeRawQuery(
+ buildMentionResolutionQuery({
+ participantTable: getAgentChatThreadParticipantTable(args.workspaceId),
+ }),
+ [args.threadId, args.workspaceMemberId],
+ );
+ }
+
// An assignee follows the chat and finds it in their inbox, unread unless
// they assigned it to themselves
// The assignment is written by writeAssignment in the same transaction, so
@@ -601,12 +652,13 @@ export class AgentChatThreadParticipantService {
// Also taken when the row does not exist yet, so two first writes cannot
// both send it as created
if (lock) {
- await manager.query(
- 'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))',
- [
- `agent-chat-thread-participant:${workspaceId}:${threadId}:${workspaceMemberId}`,
- ],
- );
+ await manager.query(PARTICIPANT_LOCK_QUERY, [
+ buildAgentChatThreadParticipantLockKey({
+ workspaceId,
+ threadId,
+ workspaceMemberId,
+ }),
+ ]);
}
const [participant] = await manager.query<AgentChatThreadParticipantRow[]>(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
index a116430461a..1603402663b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
@@ -23,9 +23,20 @@ import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/a
import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service';
import { filterPartsOfTurnActedByOthers } from 'src/engine/metadata-modules/ai/ai-history/utils/filter-parts-of-turn-acted-by-others.util';
import { resolveMessageSenderApplicationId } from 'src/engine/metadata-modules/ai/ai-chat/utils/resolve-message-sender-application-id.util';
+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 { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
import { AgentTitleGenerationService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-title-generation.service';
+import { type AgentHistoryTransactionScope } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type';
+
+type AddMessageArgs = {
+ threadId: string;
+ uiMessage: Omit<ExtendedUIMessage, 'id'>;
+ turnStatus?: AgentTurnStatus;
+ id?: string;
+ workspaceId: string;
+ userWorkspaceId?: string;
+};
@Injectable()
export class AgentChatService {
@@ -41,6 +52,7 @@ export class AgentChatService {
private readonly threadRecordEventService: AgentChatThreadRecordEventService,
private readonly conversationWriterService: AgentConversationWriterService,
private readonly threadService: AgentChatThreadService,
+ private readonly participantService: AgentChatThreadParticipantService,
) {}
private getMessageSenderValues({
@@ -84,20 +96,15 @@ export class AgentChatService {
id,
workspaceId,
userWorkspaceId,
- }: {
- threadId: string;
- uiMessage: Omit<ExtendedUIMessage, 'id'>;
- turnStatus?: AgentTurnStatus;
- id?: string;
- workspaceId: string;
- userWorkspaceId?: string;
- }) {
+ scope,
+ }: AddMessageArgs & { scope?: AgentHistoryTransactionScope }) {
const turnId = await this.conversationWriterService.insertTurn({
workspaceId,
threadId,
agentId: null,
status: turnStatus,
createdBy: this.getMessageSenderActor({ workspaceId, userWorkspaceId }),
+ scope,
});
const senderValues = this.getMessageSenderValues({
@@ -116,6 +123,7 @@ export class AgentChatService {
...senderValues,
processedAt,
parts: uiMessage.parts ?? [],
+ scope,
});
return {
@@ -129,6 +137,25 @@ export class AgentChatService {
};
}
+ async addMessageAndResolveMention({
+ workspaceMemberId,
+ ...message
+ }: AddMessageArgs & { workspaceMemberId: string }) {
+ return this.conversationWriterService.runInTransaction(
+ message.workspaceId,
+ async (scope) => {
+ await this.participantService.resolveMentionInTransaction({
+ workspaceId: message.workspaceId,
+ workspaceMemberId,
+ threadId: message.threadId,
+ scope,
+ });
+
+ return this.addMessage({ ...message, scope });
+ },
+ );
+ }
+
// the contexts are the thread owner's, so the turns of other participants run without them
async getThreadContexts({
threadId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-lock-key.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-lock-key.util.ts
new file mode 100644
index 00000000000..9089a83e385
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-lock-key.util.ts
@@ -0,0 +1,8 @@
+import { type AgentChatThreadAccessArgs } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-access-args.type';
+
+export const buildAgentChatThreadParticipantLockKey = ({
+ workspaceId,
+ threadId,
+ workspaceMemberId,
+}: AgentChatThreadAccessArgs): string =>
+ `agent-chat-thread-participant:${workspaceId}:${threadId}:${workspaceMemberId}`;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service.ts
index 9a82b9c3330..d7acbbf080b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service.ts
@@ -25,6 +25,7 @@ export class AgentHistoryTransactionService {
);
return work({
+ executeRawQuery: transactionScope.executeRawQuery,
insert: async (name, values) => {
await getRepository(name).insert(values);
},
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type.ts
index 3f3e097f6e4..62897d8ec4f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type.ts
@@ -1,8 +1,10 @@
import { type ObjectLiteral } from 'typeorm';
import { type AgentHistoryObjectName } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-object-name.type';
+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/types/workspace-transaction-scope.type';
export type AgentHistoryTransactionScope = {
+ executeRawQuery: WorkspaceTransactionScope['executeRawQuery'];
insert: (
name: AgentHistoryObjectName,
values: ObjectLiteral | ObjectLiteral[],
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer-recorder.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer-recorder.service.spec.ts
index 7f2460cc791..b3e2d28eee5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer-recorder.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer-recorder.service.spec.ts
@@ -19,6 +19,7 @@ const buildService = () => {
const service = new ToolCallAnswerRecorderService(
messagePartRepository as never,
threadRecordEventService as never,
+ {} as never,
);
return { service, messagePartRepository, threadRecordEventService };
@@ -31,6 +32,7 @@ describe('ToolCallAnswerRecorderService recordToolCallAnswer', () => {
partId: 'part-id',
toolOutput: { result: { status: 'answered' } },
workspaceId: 'workspace-id',
+ resolveMentionForWorkspaceMemberId: null,
};
it('tells open chat lists once the last answer stops the wait', async () => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer-recorder.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer-recorder.service.ts
index 6b3c2c1949e..cc184a0bcac 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer-recorder.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer-recorder.service.ts
@@ -3,12 +3,15 @@ import { Injectable } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
import { findAwaitingPausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool.util';
+import { AgentChatThreadParticipantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service';
import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service';
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { type AgentHistoryStorageContext } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';
import { AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
import { buildEndWaitingAgentTurnQuery } from 'src/engine/metadata-modules/ai/ai-history/utils/build-end-waiting-agent-turn-query.util';
+import { buildToolCallNotPendingException } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/utils/build-tool-call-not-pending-exception.util';
@Injectable()
export class ToolCallAnswerRecorderService {
@@ -16,6 +19,7 @@ export class ToolCallAnswerRecorderService {
@InjectAgentHistoryRepository('agentMessagePart')
private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
private readonly threadRecordEventService: AgentChatThreadRecordEventService,
+ private readonly participantService: AgentChatThreadParticipantService,
) {}
async findAwaitingToolParts({
@@ -36,26 +40,35 @@ export class ToolCallAnswerRecorderService {
}
// only a still-pending call is claimed, so two answers never both run it
- async claimToolCallAnswer({
+ async claimToolCallAnswerOrThrow({
+ threadId,
partId,
toolOutput,
workspaceId,
+ workspaceMemberId,
}: {
+ threadId: string;
partId: string;
toolOutput: Record<string, unknown>;
workspaceId: string;
- }): Promise<boolean> {
- const claimedParts = await this.messagePartRepository.query(
+ workspaceMemberId: string;
+ }): Promise<void> {
+ await this.participantService.resolveMention({
+ threadId,
workspaceId,
- ({ manager, table }) =>
- manager.query<{ id: string }[]>(
+ workspaceMemberId,
+ writeResponse: async ({ manager, table }) => {
+ const claimedParts = await manager.query<{ id: string }[]>(
`WITH claimed_part AS (UPDATE ${table('agentMessagePart')} SET "toolOutput" = "toolOutput" || $2::jsonb, "updatedAt" = now()
WHERE id = $1 AND "toolOutput"->'result'->>'status' = 'pending' RETURNING id) SELECT id FROM claimed_part`,
[partId, JSON.stringify(toolOutput)],
- ),
- );
+ );
- return claimedParts.length === 1;
+ if (claimedParts.length !== 1) {
+ throw buildToolCallNotPendingException();
+ }
+ },
+ });
}
// written together so an answer never strands a conversation waiting on answered calls
@@ -66,6 +79,7 @@ export class ToolCallAnswerRecorderService {
toolOutput,
isLastAnswer,
workspaceId,
+ resolveMentionForWorkspaceMemberId,
}: {
threadId: string;
messageId: string;
@@ -73,40 +87,54 @@ export class ToolCallAnswerRecorderService {
toolOutput: Record<string, unknown>;
isLastAnswer: boolean;
workspaceId: string;
+ resolveMentionForWorkspaceMemberId: string | null;
}): Promise<void> {
- const isPendingQuestionCleared = await this.messagePartRepository.query(
- workspaceId,
- async ({ manager, table }) => {
- await manager.query(
- `UPDATE ${table('agentMessagePart')} SET "toolOutput" = $2::jsonb, "updatedAt" = now() WHERE id = $1`,
- [partId, JSON.stringify(toolOutput)],
- );
+ let isPendingQuestionCleared = false;
- if (!isLastAnswer) {
- return false;
- }
+ const writeResponse = async ({
+ manager,
+ table,
+ }: AgentHistoryStorageContext) => {
+ await manager.query(
+ `UPDATE ${table('agentMessagePart')} SET "toolOutput" = $2::jsonb, "updatedAt" = now() WHERE id = $1`,
+ [partId, JSON.stringify(toolOutput)],
+ );
- const clearedThreads = await manager.query<{ id: string }[]>(
- `WITH cleared AS (
- UPDATE ${table('agentChatThread')} SET "pendingQuestionMessageId" = NULL, "updatedAt" = now()
- WHERE id = $1 AND "pendingQuestionMessageId" = $2
- RETURNING id
- ) SELECT id FROM cleared`,
- [threadId, messageId],
- );
+ if (!isLastAnswer) {
+ return;
+ }
- if (clearedThreads.length === 0) {
- return false;
- }
+ const clearedThreads = await manager.query<{ id: string }[]>(
+ `WITH cleared AS (
+ UPDATE ${table('agentChatThread')} SET "pendingQuestionMessageId" = NULL, "updatedAt" = now()
+ WHERE id = $1 AND "pendingQuestionMessageId" = $2
+ RETURNING id
+ ) SELECT id FROM cleared`,
+ [threadId, messageId],
+ );
- await manager.query(buildEndWaitingAgentTurnQuery({ table }), [
- messageId,
- AgentTurnStatus.COMPLETED,
- ]);
+ if (clearedThreads.length === 0) {
+ return;
+ }
- return true;
- },
- );
+ await manager.query(buildEndWaitingAgentTurnQuery({ table }), [
+ messageId,
+ AgentTurnStatus.COMPLETED,
+ ]);
+
+ isPendingQuestionCleared = true;
+ };
+
+ if (isDefined(resolveMentionForWorkspaceMemberId)) {
+ await this.participantService.resolveMention({
+ workspaceId,
+ workspaceMemberId: resolveMentionForWorkspaceMemberId,
+ threadId,
+ writeResponse,
+ });
+ } else {
+ await this.messagePartRepository.query(workspaceId, writeResponse);
+ }
if (isPendingQuestionCleared) {
await this.threadRecordEventService.emitPendingQuestionCleared({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
index 41047aff0c6..32be5c9b8e6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
@@ -41,6 +41,7 @@ import {
} from 'src/engine/metadata-modules/ai/ai.exception';
import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
+import { buildToolCallNotPendingException } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/utils/build-tool-call-not-pending-exception.util';
type AnswerToolCallArgs = {
threadId: string;
@@ -131,7 +132,7 @@ export class ToolCallAnswerService {
});
if (!isToolCallPending) {
- throw this.notPending();
+ throw buildToolCallNotPendingException();
}
const validation = pausingToolCall.validate(args.response);
@@ -178,7 +179,7 @@ export class ToolCallAnswerService {
});
if (!awaitingToolParts.some((part) => part.id === toolPart.id)) {
- throw this.notPending();
+ throw buildToolCallNotPendingException();
}
if (isDefined(wakeUp)) {
@@ -211,7 +212,7 @@ export class ToolCallAnswerService {
wakeUpId: wakeUp.id,
});
- throw this.notPending();
+ throw buildToolCallNotPendingException();
}
}
@@ -220,15 +221,13 @@ export class ToolCallAnswerService {
);
if (isDefined(runningToolResult)) {
- if (
- !(await this.toolCallAnswerRecorderService.claimToolCallAnswer({
- partId: toolPart.id,
- toolOutput: runningToolResult,
- workspaceId,
- }))
- ) {
- throw this.notPending();
- }
+ await this.toolCallAnswerRecorderService.claimToolCallAnswerOrThrow({
+ threadId,
+ partId: toolPart.id,
+ toolOutput: runningToolResult,
+ workspaceId,
+ workspaceMemberId: args.workspaceMemberId,
+ });
isClaimedAsRunning = true;
}
@@ -251,6 +250,9 @@ export class ToolCallAnswerService {
toolOutput: completion.toolResult,
isLastAnswer,
workspaceId,
+ resolveMentionForWorkspaceMemberId: isClaimedAsRunning
+ ? null
+ : args.workspaceMemberId,
});
answerText = completion.answerText;
@@ -572,13 +574,6 @@ export class ToolCallAnswerService {
}
}
- private notPending(): AiException {
- return new AiException(
- 'This tool call is no longer waiting for an answer',
- AiExceptionCode.TOOL_CALL_NOT_PENDING,
- );
- }
-
private async publishToolCallResolved({
threadId,
toolCallId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/utils/build-tool-call-not-pending-exception.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/utils/build-tool-call-not-pending-exception.util.ts
new file mode 100644
index 00000000000..a0a6b4e7268
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/utils/build-tool-call-not-pending-exception.util.ts
@@ -0,0 +1,10 @@
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+export const buildToolCallNotPendingException = (): AiException =>
+ new AiException(
+ 'This tool call is no longer waiting for an answer',
+ AiExceptionCode.TOOL_CALL_NOT_PENDING,
+ );
diff --git a/packages/twenty-server/test/integration/ai/utils/wait-for-blocked-database-query-or-throw.util.ts b/packages/twenty-server/test/integration/ai/utils/wait-for-blocked-database-query-or-throw.util.ts
index 1326f9b7a9d..4b80be22843 100644
--- a/packages/twenty-server/test/integration/ai/utils/wait-for-blocked-database-query-or-throw.util.ts
+++ b/packages/twenty-server/test/integration/ai/utils/wait-for-blocked-database-query-or-throw.util.ts
@@ -24,5 +24,5 @@ export const waitForBlockedDatabaseQueryOrThrow = async (
);
}
- fail('The competing conversation creation did not wait for its ID');
+ fail('No query waited for the blocking database process');
};
diff --git a/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts
index 9fcefe55b28..49db681f946 100644
--- a/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts
@@ -1,6 +1,7 @@
import { randomUUID } from 'node:crypto';
import { parse } from 'graphql';
+import { buildFallbackProposedToolCall } from 'twenty-shared/ai';
import { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.util';
import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';
@@ -8,9 +9,12 @@ import { getAppProviderByClassName } from 'test/integration/utils/get-app-provid
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { type MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import { type ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
import { getQueueToken } from 'src/engine/core-modules/message-queue/utils/get-queue-token.util';
+import { buildProposeToolCallPendingOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-tool-call.pausing-tool';
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { type AgentChatThreadParticipantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service';
import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
import { type AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
import { createAskQuestionTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool';
@@ -34,6 +38,12 @@ const QUESTION = {
options: [{ label: 'Pro' }, { label: 'Team' }],
};
+const PROPOSAL_INPUT = {
+ toolName: 'create_company',
+ arguments: { name: 'Acme' },
+ summary: 'Create Acme',
+};
+
describe('Answering a chat tool call', () => {
const threadId = randomUUID();
let chat: AgentChatService;
@@ -80,6 +90,25 @@ describe('Answering a chat tool call', () => {
return { assistantMessageId };
};
+ const pauseOnProposal = async (toolCallId: string) => {
+ await pauseOnQuestions(toolCallId);
+ await global.testDataSource.query(
+ `UPDATE "${schema}"."agentMessagePart"
+ SET "toolName" = 'propose_tool_call', "toolInput" = $2::jsonb,
+ "toolOutput" = $3::jsonb
+ WHERE "toolCallId" = $1`,
+ [
+ toolCallId,
+ JSON.stringify(PROPOSAL_INPUT),
+ JSON.stringify(
+ buildProposeToolCallPendingOutput(
+ buildFallbackProposedToolCall(PROPOSAL_INPUT),
+ ),
+ ),
+ ],
+ );
+ };
+
const answerQuestions = (toolCallId: string) =>
answerToolCall({
toolCall: { threadId, toolCallId },
@@ -102,6 +131,30 @@ describe('Answering a chat tool call', () => {
)
)[0]?.toolOutput?.result?.status;
+ const markAsMentioned = () =>
+ getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).markAsMentioned({ workspaceId, workspaceMemberId, threadId });
+
+ const readMentionState = async (memberId = workspaceMemberId) => {
+ const [participant]: {
+ lastMentionedAt: Date | null;
+ mentionsResolvedAt: Date | null;
+ }[] = await global.testDataSource.query(
+ `SELECT "lastMentionedAt", "mentionsResolvedAt" FROM "${schema}"."agentChatThreadParticipant"
+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
+ [threadId, memberId],
+ );
+
+ return participant;
+ };
+
+ const expectMentionResolved = async () => {
+ const participant = await readMentionState();
+
+ expect(participant.mentionsResolvedAt).toEqual(participant.lastMentionedAt);
+ };
+
const stopStream = () =>
makeMetadataApiRequest({
query: parse(
@@ -214,6 +267,73 @@ describe('Answering a chat tool call', () => {
);
});
+ it('resolves only the answering member while another request remains pending', async () => {
+ await pauseOnQuestions('mention-first-answer', 'mention-pending-answer');
+ await getAgentChatThreadService().mentionParticipants({
+ workspaceId,
+ workspaceMemberId,
+ threadId,
+ participantWorkspaceMemberIds: [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY],
+ });
+ await markAsMentioned();
+
+ const otherMemberBefore = await readMentionState(
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ );
+ const response = await answerQuestions('mention-first-answer');
+
+ expect(response.body.errors).toBeUndefined();
+
+ await expectMentionResolved();
+ expect(await readMentionState(WORKSPACE_MEMBER_DATA_SEED_IDS.JONY)).toEqual(
+ otherMemberBefore,
+ );
+ expect(await readToolCallStatus('mention-pending-answer')).toBe('pending');
+ expect(await readPendingQuestionMessageId()).not.toBeNull();
+ });
+
+ it('preserves a new mention arriving while an accepted approval executes', async () => {
+ const toolCallId = 'mention-during-approved-execution';
+
+ await pauseOnProposal(toolCallId);
+ await markAsMentioned();
+
+ const acceptedMention = await readMentionState();
+ const toolRegistry = getAppProviderByClassName<ToolRegistryService>(
+ 'ToolRegistryService',
+ );
+ const executeTool = jest
+ .spyOn(toolRegistry, 'resolveAndExecute')
+ .mockImplementationOnce(async () => {
+ await expectMentionResolved();
+ expect(await readToolCallStatus(toolCallId)).toBe('running');
+
+ await markAsMentioned();
+
+ return { success: true, message: 'Company created', result: {} };
+ });
+
+ spies.push(executeTool);
+
+ const response = await answerToolCall({
+ toolCall: { threadId, toolCallId },
+ response: { decision: 'approve' },
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ expect(executeTool).toHaveBeenCalledTimes(1);
+ expect(await readToolCallStatus(toolCallId)).toBe('approved');
+
+ const participant = await readMentionState();
+
+ expect(participant.mentionsResolvedAt).toEqual(
+ acceptedMention.lastMentionedAt,
+ );
+ expect(participant.lastMentionedAt!.getTime()).toBeGreaterThan(
+ participant.mentionsResolvedAt!.getTime(),
+ );
+ });
+
it('answers the questions of a step in any order', async () => {
await pauseOnQuestions(
'unordered-first',
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.ts
index ee34424a08f..3871fbe91e0 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
@@ -1,4 +1,5 @@
import { randomUUID } from 'node:crypto';
+import { EventEmitter, once } from 'node:events';
import { parse } from 'graphql';
import {
@@ -11,6 +12,7 @@ import {
RecordSharePrincipalType,
} from 'twenty-shared/types';
+import { waitForBlockedDatabaseQueryOrThrow } from 'test/integration/ai/utils/wait-for-blocked-database-query-or-throw.util';
import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
@@ -19,7 +21,11 @@ import { getAppProviderByClassName } from 'test/integration/utils/get-app-provid
import { setManualRecordShare } from 'test/integration/utils/set-manual-record-share.util';
import { AgentChatInboxAction } from 'src/engine/metadata-modules/ai/ai-chat/enums/agent-chat-inbox-action.enum';
+import { type AgentChatQueueService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-queue.service';
import { type AgentChatThreadParticipantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service';
+import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@@ -30,6 +36,12 @@ import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev
const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+const buildJonyThreadAccess = (threadId: string) => ({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ threadId,
+});
+
const PARTICIPANT_FIELDS =
'id threadId lastReadAt archivedAt snoozedUntil isSubscribed lastMentionedAt mentionsResolvedAt updatedAt';
@@ -1260,6 +1272,41 @@ describe('Chat thread participant state through the authenticated API', () => {
}
});
+ it('resolves only the member who successfully sends a reply', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+ await addParticipants(
+ threadId,
+ [WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ );
+
+ await getAppProviderByClassName<AgentChatService>(
+ 'AgentChatService',
+ ).addMessageAndResolveMention({
+ ...buildJonyThreadAccess(threadId),
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ uiMessage: {
+ role: AgentMessageRole.USER,
+ parts: [{ type: 'text', text: 'I have handled this.' }],
+ },
+ });
+
+ const repliedParticipant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(repliedParticipant!.mentionsResolvedAt).toBe(
+ repliedParticipant!.lastMentionedAt,
+ );
+ expect(await findMyParticipant(threadId)).toMatchObject({
+ lastMentionedAt: expect.any(String),
+ mentionsResolvedAt: null,
+ });
+ });
+
it('keeps a mention resolved after Done until an explicit new mention arrives', async () => {
const threadId = await createTestThread();
@@ -1326,6 +1373,88 @@ describe('Chat thread participant state through the authenticated API', () => {
});
});
+ describe('queued replies to a mention', () => {
+ const queueReply = (threadId: string) =>
+ getAppProviderByClassName<AgentChatQueueService>(
+ 'AgentChatQueueService',
+ ).queueMessage({
+ ...buildJonyThreadAccess(threadId),
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ text: 'On it',
+ });
+
+ const deleteQueuedReply = (messageId: string) =>
+ getAppProviderByClassName<AgentChatQueueService>(
+ 'AgentChatQueueService',
+ ).deleteQueuedMessage({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ messageId,
+ });
+
+ it('resolves the mention when the member queues a reply and keeps it after the reply is deleted', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const reply = await queueReply(threadId);
+ const repliedParticipant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(repliedParticipant!.mentionsResolvedAt).toBe(
+ repliedParticipant!.lastMentionedAt,
+ );
+
+ await deleteQueuedReply(reply.id);
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({
+ mentionsResolvedAt: repliedParticipant!.lastMentionedAt,
+ });
+ });
+
+ it('queues a reply while another write of the member locks the chat', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const writeEvents = new EventEmitter();
+ const writeStarted = once(writeEvents, 'started');
+ const writeResumed = once(writeEvents, 'resumed');
+ const write =
+ getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).resolveMention({
+ ...buildJonyThreadAccess(threadId),
+ writeResponse: async ({ manager, table }) => {
+ const [{ backendProcessId }] = await manager.query<
+ { backendProcessId: number }[]
+ >('SELECT pg_backend_pid() AS "backendProcessId"');
+
+ writeEvents.emit('started', backendProcessId);
+ await writeResumed;
+ await manager.query(
+ `SELECT id FROM ${table('agentChatThread')} WHERE id = $1 FOR UPDATE`,
+ [threadId],
+ );
+ },
+ });
+
+ const [blockingProcessId] = await writeStarted;
+ const reply = queueReply(threadId);
+
+ await waitForBlockedDatabaseQueryOrThrow(blockingProcessId);
+ writeEvents.emit('resumed');
+
+ await expect(Promise.all([write, reply])).resolves.toEqual([
+ undefined,
+ expect.objectContaining({ threadId }),
+ ]);
+ });
+ });
+
it('delivers app recipients without creating or clearing an explicit mention', async () => {
const threadId = await createTestThread();
const threadService = getAppProviderByClassName<AgentChatThreadService>(
@@ -1366,6 +1495,66 @@ describe('Chat thread participant state through the authenticated API', () => {
});
});
+ it('rolls mention resolution back when a response cannot be recorded', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ await expect(
+ getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).resolveMention({
+ ...buildJonyThreadAccess(threadId),
+ writeResponse: async () => {
+ throw new Error('The response is invalid');
+ },
+ }),
+ ).rejects.toThrow('The response is invalid');
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({ mentionsResolvedAt: null });
+ });
+
+ it('preserves a newer mention when an older response finishes first', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const responseEvents = new EventEmitter();
+ const responseStarted = once(responseEvents, 'started');
+ const responseFinished = once(responseEvents, 'finished');
+ const participantService =
+ getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ );
+ const response = participantService.resolveMention({
+ ...buildJonyThreadAccess(threadId),
+ writeResponse: async () => {
+ responseEvents.emit('started');
+ await responseFinished;
+ },
+ });
+
+ await responseStarted;
+
+ const laterMention = participantService.markAsMentioned(
+ buildJonyThreadAccess(threadId),
+ );
+
+ responseEvents.emit('finished');
+ await Promise.all([response, laterMention]);
+
+ const participant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(new Date(participant!.lastMentionedAt!).getTime()).toBeGreaterThan(
+ new Date(participant!.mentionsResolvedAt!).getTime(),
+ );
+ });
+
it('orders a new mention after the resolved cursor at millisecond precision', async () => {
const threadId = await createTestThread();
const resolvedAt = new Date(Date.now() + 60_000).toISOString();