The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Agent engine: read a conversation's wait in one query (#28308)
Félix Malfait71cc93e38468
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.tsindex 85544dbd15f..fa40ef035df 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-caller-conversation.service.spec.ts@@ -40,7 +40,9 @@ const buildService = ({ isCreated = true } = {}) => {),};const agentRunSuspensionService = {- isConversationWaiting: jest.fn().mockResolvedValue(false),+ findConversationWait: jest+ .fn()+ .mockResolvedValue({ suspendedRun: null, hasPostedCall: false }),};const service = new AgentCallerConversationService(@@ -208,9 +210,12 @@ describe('AgentCallerConversationService', () => {thread: { id: 'suspended-thread-id' },isCreated: false,});- agentRunSuspensionService.isConversationWaiting.mockImplementation(- async ({ threadId }: { threadId: string }) =>- threadId === 'suspended-thread-id',+ agentRunSuspensionService.findConversationWait.mockImplementation(+ async ({ threadId }: { threadId: string }) => ({+ suspendedRun:+ threadId === 'suspended-thread-id' ? { id: 'wake-up-id' } : null,+ hasPostedCall: false,+ }),);await expect(diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.tsindex 8cc5d2c1323..ede6a0740c1 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-caller-conversation.service.ts@@ -125,10 +125,15 @@ export class AgentCallerConversationService {!isDefined(keyedConversation) ||isDefined(keyedConversation.thread.deletedAt) ||isDefined(keyedConversation.thread.pendingQuestionMessageId) ||- (await this.agentRunSuspensionService.isConversationWaiting({- workspaceId,- threadId: keyedConversation.thread.id,- }));+ (await this.agentRunSuspensionService+ .findConversationWait({+ workspaceId,+ threadId: keyedConversation.thread.id,+ })+ .then(+ ({ suspendedRun, hasPostedCall }) =>+ isDefined(suspendedRun) || hasPostedCall,+ ));const { thread, isCreated } = isKeyedConversationUnavailable? await openThreadUnderKey(fallbackThreadKey): keyedConversation;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.tsindex 1ca7634de70..07e3b8ef685 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service.ts@@ -88,75 +88,56 @@ export class AgentRunSuspensionService {});}- // a run waiting in the conversation would read another run's prompt on continuing, and a caller- // waiting on a call it posted there would see the run close it- async isConversationWaiting({+ // a run waiting in the conversation would read another run's prompt on continuing, and a call+ // a caller such as a workflow step posted there waits on its own answer+ async findConversationWait({workspaceId,threadId,}: {workspaceId: string;threadId: string;- }): Promise<boolean> {- return this.wakeUpRepository.exists(workspaceId, {+ }): Promise<{+ suspendedRun: Pick<PendingWakeUpEntity, 'id'> | null;+ hasPostedCall: boolean;+ }> {+ const wakeUps = await this.wakeUpRepository.find(workspaceId, {where: [{ ownerType: 'AGENT_RUN', ownerId: threadId },{ condition: buildAnswerInThreadCondition(threadId) },],+ select: ['id', 'ownerType', 'ownerId'],});- }- async assertConversationNotSuspended({- workspaceId,- threadId,- }: {- workspaceId: string;- threadId: string;- }): Promise<void> {- if (await this.isConversationWaiting({ workspaceId, threadId })) {- throw new AiException(- 'The conversation is waiting on an earlier run; send the next message once it has finished',- AiExceptionCode.THREAD_AWAITING_ANSWER,- );- }+ return {+ suspendedRun:+ wakeUps.find(+ ({ ownerType, ownerId }) =>+ ownerType === 'AGENT_RUN' && ownerId === threadId,+ ) ?? null,+ hasPostedCall: wakeUps.some(({ ownerType }) => ownerType !== 'AGENT_RUN'),+ };}- // a caller, such as a workflow step, waits on the answer to a call it posted, which a message- // would leave unanswered- async assertNoPostedCallAwaited({+ async assertConversationNotSuspended({workspaceId,threadId,}: {workspaceId: string;threadId: string;}): Promise<void> {- const isAwaited = await this.wakeUpRepository.exists(workspaceId, {- where: {- ownerType: Not('AGENT_RUN'),- condition: buildAnswerInThreadCondition(threadId),- },+ const { suspendedRun, hasPostedCall } = await this.findConversationWait({+ workspaceId,+ threadId,});- if (isAwaited) {+ if (isDefined(suspendedRun) || hasPostedCall) {throw new AiException(- 'The conversation is waiting on an answer; answer it before sending a message',+ 'The conversation is waiting on an earlier run; send the next message once it has finished',AiExceptionCode.THREAD_AWAITING_ANSWER,);}}- async findSuspendedRun({- workspaceId,- threadId,- }: {- workspaceId: string;- threadId: string;- }): Promise<Pick<PendingWakeUpEntity, 'id'> | null> {- return this.wakeUpRepository.findOne(workspaceId, {- where: { ownerType: 'AGENT_RUN', ownerId: threadId },- select: ['id'],- });- }-// the wake-up stays while its run goes on, so another resolution of it is let go rather than queued behind itasync scheduleContinuation(jobData: ContinueAgentRunJobData): Promise<void> {await this.messageQueueService.add<ContinueAgentRunJobData>(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.tsindex 3777004ea86..de7bd4d2a67 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@@ -112,14 +112,20 @@ export class AgentChatStreamingService {const threadId = thread.id;const workspaceId = workspace.id;- const [, hasQueuedBacklog, suspendedRun] = await Promise.all([- this.settlePendingToolCallsBeforeSending({ thread, workspaceId }),- this.agentChatService.hasQueuedMessages({ threadId, workspaceId }),- this.agentRunSuspensionService.findSuspendedRun({- workspaceId,- threadId,- }),- ]);+ const [{ suspendedRun, hasPostedCall }, hasQueuedBacklog] =+ await Promise.all([+ this.agentRunSuspensionService.findConversationWait({+ workspaceId,+ threadId,+ }),+ this.agentChatService.hasQueuedMessages({ threadId, workspaceId }),+ ]);++ await this.settlePendingToolCallsBeforeSending({+ thread,+ workspaceId,+ hasPostedCall,+ });const streamId = generateId();@@ -512,9 +518,9 @@ export class AgentChatStreamingService {return;}- const [queuedMessages, suspendedRun] = await Promise.all([+ const [queuedMessages, { suspendedRun }] = await Promise.all([this.agentChatService.getQueuedMessages({ threadId, workspaceId }),- this.agentRunSuspensionService.findSuspendedRun({+ this.agentRunSuspensionService.findConversationWait({workspaceId,threadId,}),@@ -679,19 +685,23 @@ export class AgentChatStreamingService {private async settlePendingToolCallsBeforeSending({thread,workspaceId,+ hasPostedCall,}: {thread: Pick<AgentChatThreadWorkspaceEntity,'id' | 'pendingQuestionMessageId'>;workspaceId: string;+ hasPostedCall: boolean;}): Promise<void> {const messageId = thread.pendingQuestionMessageId;- await this.agentRunSuspensionService.assertNoPostedCallAwaited({- workspaceId,- threadId: thread.id,- });+ if (hasPostedCall) {+ throw new AiException(+ 'The conversation is waiting on an answer; answer it before sending a message',+ AiExceptionCode.THREAD_AWAITING_ANSWER,+ );+ }if (!isDefined(messageId)) {return;