Skip to content

The open alternative to Salesforce, designed for AI.

Agent engine: read whether a conversation is waiting from one query (#28499)

Félix Malfaitfb236626d587
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.ts
index fa40ef035df..e1c9edcdb16 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,9 +40,12 @@ const buildService = ({ isCreated = true } = {}) => {
),
};
const agentRunSuspensionService = {
- findConversationWait: jest
- .fn()
- .mockResolvedValue({ suspendedRun: null, hasPostedCall: false }),
+ findConversationWait: jest.fn().mockResolvedValue({
+ pendingQuestionMessageId: null,
+ suspendedRun: null,
+ hasPostedCall: false,
+ isWaiting: false,
+ }),
};
const service = new AgentCallerConversationService(
@@ -184,15 +187,23 @@ describe('AgentCallerConversationService', () => {
});
it('starts its own conversation while the one its key names waits on another answer', async () => {
- const { service, agentInboxService } = buildService();
+ const { service, agentInboxService, agentRunSuspensionService } =
+ buildService();
+ const waitingThread = {
+ id: 'waiting-thread-id',
+ pendingQuestionMessageId: 'question-message-id',
+ };
agentInboxService.openThread.mockResolvedValueOnce({
- thread: {
- id: 'waiting-thread-id',
- pendingQuestionMessageId: 'question-message-id',
- },
+ thread: waitingThread,
isCreated: false,
});
+ agentRunSuspensionService.findConversationWait.mockResolvedValueOnce({
+ pendingQuestionMessageId: 'question-message-id',
+ suspendedRun: null,
+ hasPostedCall: false,
+ isWaiting: true,
+ });
await expect(
service.openConversation({
@@ -200,6 +211,12 @@ describe('AgentCallerConversationService', () => {
recipientWorkspaceMemberId: 'recipient-id',
}),
).resolves.toMatchObject({ threadId: 'thread-for-recipient-id' });
+ expect(
+ agentRunSuspensionService.findConversationWait,
+ ).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ thread: waitingThread,
+ });
});
it('starts its own conversation while the one its key names holds a suspended run', async () => {
@@ -211,10 +228,12 @@ describe('AgentCallerConversationService', () => {
isCreated: false,
});
agentRunSuspensionService.findConversationWait.mockImplementation(
- async ({ threadId }: { threadId: string }) => ({
+ async ({ thread }: { thread: { id: string } }) => ({
+ pendingQuestionMessageId: null,
suspendedRun:
- threadId === 'suspended-thread-id' ? { id: 'wake-up-id' } : null,
+ thread.id === 'suspended-thread-id' ? { id: 'wake-up-id' } : null,
hasPostedCall: false,
+ isWaiting: thread.id === 'suspended-thread-id',
}),
);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-suspension.service.find-conversation-wait.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-suspension.service.find-conversation-wait.spec.ts
new file mode 100644
index 00000000000..811dbce4ea8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run-suspension.service.find-conversation-wait.spec.ts
@@ -0,0 +1,99 @@
+import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+
+const THREAD_ID = 'thread-id';
+
+const buildService = ({
+ wakeUps = [],
+}: {
+ wakeUps?: { id: string; ownerType: string; ownerId: string }[];
+} = {}) =>
+ new AgentRunSuspensionService(
+ { find: jest.fn().mockResolvedValue(wakeUps) } as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ );
+
+const buildThread = (pendingQuestionMessageId: string | null = null) => ({
+ id: THREAD_ID,
+ pendingQuestionMessageId,
+});
+
+const SUSPENDED_RUN = {
+ id: 'run-wake-up-id',
+ ownerType: 'AGENT_RUN',
+ ownerId: THREAD_ID,
+};
+const POSTED_CALL = {
+ id: 'step-wake-up-id',
+ ownerType: 'WORKFLOW_STEP',
+ ownerId: 'workflow-run-id',
+};
+
+describe('AgentRunSuspensionService findConversationWait', () => {
+ it('reads a conversation with nothing pending as not waiting', async () => {
+ await expect(
+ buildService().findConversationWait({
+ workspaceId: 'workspace-id',
+ thread: buildThread(),
+ }),
+ ).resolves.toEqual({
+ pendingQuestionMessageId: null,
+ suspendedRun: null,
+ hasPostedCall: false,
+ isWaiting: false,
+ });
+ });
+
+ it('reads a pending question as waiting', async () => {
+ await expect(
+ buildService().findConversationWait({
+ workspaceId: 'workspace-id',
+ thread: buildThread('question-message-id'),
+ }),
+ ).resolves.toMatchObject({
+ pendingQuestionMessageId: 'question-message-id',
+ isWaiting: true,
+ });
+ });
+
+ it('reads a suspended run or a posted call as waiting', async () => {
+ await expect(
+ buildService({
+ wakeUps: [SUSPENDED_RUN, POSTED_CALL],
+ }).findConversationWait({
+ workspaceId: 'workspace-id',
+ thread: buildThread(),
+ }),
+ ).resolves.toMatchObject({
+ suspendedRun: { id: 'run-wake-up-id' },
+ hasPostedCall: true,
+ isWaiting: true,
+ });
+ });
+});
+
+describe('AgentRunSuspensionService assertConversationNotSuspended', () => {
+ it('refuses a run while a wake-up holds the conversation', async () => {
+ await expect(
+ buildService({ wakeUps: [POSTED_CALL] }).assertConversationNotSuspended({
+ workspaceId: 'workspace-id',
+ threadId: THREAD_ID,
+ }),
+ ).rejects.toMatchObject({ code: AiExceptionCode.THREAD_AWAITING_ANSWER });
+ });
+
+ it('lets a run in while no wake-up holds the conversation', async () => {
+ await expect(
+ buildService().assertConversationNotSuspended({
+ workspaceId: 'workspace-id',
+ threadId: THREAD_ID,
+ }),
+ ).resolves.toBeUndefined();
+ });
+});
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.ts
index ede6a0740c1..cb565916eff 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
@@ -124,16 +124,12 @@ export class AgentCallerConversationService {
const isKeyedConversationUnavailable =
!isDefined(keyedConversation) ||
isDefined(keyedConversation.thread.deletedAt) ||
- isDefined(keyedConversation.thread.pendingQuestionMessageId) ||
- (await this.agentRunSuspensionService
- .findConversationWait({
+ (
+ await this.agentRunSuspensionService.findConversationWait({
workspaceId,
- threadId: keyedConversation.thread.id,
+ thread: keyedConversation.thread,
})
- .then(
- ({ suspendedRun, hasPostedCall }) =>
- isDefined(suspendedRun) || hasPostedCall,
- ));
+ ).isWaiting;
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.ts
index 07e3b8ef685..124450cc9c9 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
@@ -17,6 +17,7 @@ import { DELIVER_AGENT_RUN_OUTCOME_JOB_NAME } from 'src/engine/metadata-modules/
import { AGENT_WAIT_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/agent-wait-tool-names.constant';
import { buildWaitOutcomeToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/build-wait-outcome-tool-output.util';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
+import { type AgentConversationWait } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-conversation-wait.type';
import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
import { type AgentRunCallerOutcome } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-outcome.type';
import { type AgentRunOutcomeDelivery } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-outcome-delivery.type';
@@ -39,6 +40,14 @@ import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scope
// one key for every run, so the owner's unique key leaves a conversation one suspended run
const SUSPENDED_RUN_WAKE_UP_KEY = 'RUN';
+type ConversationWakeUps = Pick<
+ AgentConversationWait,
+ 'suspendedRun' | 'hasPostedCall'
+>;
+
+const isHeldByWakeUp = ({ suspendedRun, hasPostedCall }: ConversationWakeUps) =>
+ isDefined(suspendedRun) || hasPostedCall;
+
const buildAnswerInThreadCondition = (threadId: string) =>
Raw((alias) => `${alias} @> :condition::jsonb`, {
condition: JSON.stringify({ type: 'ANSWER', threadId }),
@@ -92,32 +101,27 @@ export class AgentRunSuspensionService {
// a caller such as a workflow step posted there waits on its own answer
async findConversationWait({
workspaceId,
- threadId,
+ thread: { id: threadId, pendingQuestionMessageId },
}: {
workspaceId: string;
- threadId: string;
- }): 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'],
+ thread: Pick<
+ AgentChatThreadWorkspaceEntity,
+ 'id' | 'pendingQuestionMessageId'
+ >;
+ }): Promise<AgentConversationWait> {
+ const wakeUps = await this.findConversationWakeUps({
+ workspaceId,
+ threadId,
});
return {
- suspendedRun:
- wakeUps.find(
- ({ ownerType, ownerId }) =>
- ownerType === 'AGENT_RUN' && ownerId === threadId,
- ) ?? null,
- hasPostedCall: wakeUps.some(({ ownerType }) => ownerType !== 'AGENT_RUN'),
+ pendingQuestionMessageId,
+ ...wakeUps,
+ isWaiting: isDefined(pendingQuestionMessageId) || isHeldByWakeUp(wakeUps),
};
}
+ // a question the member was asked in chat does not hold the conversation from a run
async assertConversationNotSuspended({
workspaceId,
threadId,
@@ -125,12 +129,11 @@ export class AgentRunSuspensionService {
workspaceId: string;
threadId: string;
}): Promise<void> {
- const { suspendedRun, hasPostedCall } = await this.findConversationWait({
- workspaceId,
- threadId,
- });
-
- if (isDefined(suspendedRun) || hasPostedCall) {
+ if (
+ isHeldByWakeUp(
+ await this.findConversationWakeUps({ 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,
@@ -402,4 +405,29 @@ export class AgentRunSuspensionService {
turnStatus,
});
}
+
+ private async findConversationWakeUps({
+ workspaceId,
+ threadId,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ }): Promise<ConversationWakeUps> {
+ const wakeUps = await this.wakeUpRepository.find(workspaceId, {
+ where: [
+ { ownerType: 'AGENT_RUN', ownerId: threadId },
+ { condition: buildAnswerInThreadCondition(threadId) },
+ ],
+ select: ['id', 'ownerType', 'ownerId'],
+ });
+
+ return {
+ suspendedRun:
+ wakeUps.find(
+ ({ ownerType, ownerId }) =>
+ ownerType === 'AGENT_RUN' && ownerId === threadId,
+ ) ?? null,
+ hasPostedCall: wakeUps.some(({ ownerType }) => ownerType !== 'AGENT_RUN'),
+ };
+ }
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-conversation-wait.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-conversation-wait.type.ts
new file mode 100644
index 00000000000..b9666b0c944
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-conversation-wait.type.ts
@@ -0,0 +1,9 @@
+import { type PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';
+
+export type AgentConversationWait = {
+ pendingQuestionMessageId: string | null;
+ suspendedRun: Pick<PendingWakeUpEntity, 'id'> | null;
+ // a call a caller such as a workflow step posted, which waits on its own answer
+ hasPostedCall: boolean;
+ isWaiting: boolean;
+};
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 a57afbbf391..5cfa396b349 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
@@ -28,6 +28,7 @@ import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspac
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
import { AgentMessageStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-status.enum';
import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
+import { type AgentConversationWait } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-conversation-wait.type';
import { mapDBPartsToUIMessageParts } from 'src/engine/metadata-modules/ai/ai-history/utils/map-db-parts-to-ui-message-parts.util';
import { type BrowsingContextType } from 'src/engine/metadata-modules/ai/ai-agent/types/browsing-context.type';
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
@@ -110,19 +111,19 @@ export class AgentChatStreamingService {
const threadId = thread.id;
const workspaceId = workspace.id;
- const [{ suspendedRun, hasPostedCall }, hasQueuedBacklog] =
- await Promise.all([
- this.agentRunSuspensionService.findConversationWait({
- workspaceId,
- threadId,
- }),
- this.agentChatQueueService.hasQueuedMessages({ threadId, workspaceId }),
- ]);
+ const [conversationWait, hasQueuedBacklog] = await Promise.all([
+ this.agentRunSuspensionService.findConversationWait({
+ workspaceId,
+ thread,
+ }),
+ this.agentChatQueueService.hasQueuedMessages({ threadId, workspaceId }),
+ ]);
+ const { suspendedRun } = conversationWait;
await this.settlePendingToolCallsBeforeSending({
- thread,
+ threadId,
workspaceId,
- hasPostedCall,
+ conversationWait,
});
const started =
@@ -542,13 +543,14 @@ export class AgentChatStreamingService {
workspaceId: string;
}) {
const threadId = thread.id;
- const [queuedMessages, { suspendedRun }] = await Promise.all([
- this.agentChatQueueService.getQueuedMessages({ threadId, workspaceId }),
- this.agentRunSuspensionService.findConversationWait({
- workspaceId,
- threadId,
- }),
- ]);
+ const [queuedMessages, { suspendedRun, pendingQuestionMessageId }] =
+ await Promise.all([
+ this.agentChatQueueService.getQueuedMessages({ threadId, workspaceId }),
+ this.agentRunSuspensionService.findConversationWait({
+ workspaceId,
+ thread,
+ }),
+ ]);
// a run that went on to ask something reads what was sent meanwhile, as a message sent now would skip its question
if (isNonEmptyArray(queuedMessages) && isDefined(suspendedRun)) {
@@ -563,7 +565,7 @@ export class AgentChatStreamingService {
}
// queued messages wait behind a pending tool call: they follow the answer rather than replace it
- if (isDefined(thread.pendingQuestionMessageId)) {
+ if (isDefined(pendingQuestionMessageId)) {
return null;
}
@@ -622,19 +624,17 @@ export class AgentChatStreamingService {
// a message sent while an agent waits on a person closes its pending calls as skipped, so the model sees why.
// A call a caller such as a workflow step posted waits on its own answer, so it refuses the message
private async settlePendingToolCallsBeforeSending({
- thread,
+ threadId,
workspaceId,
- hasPostedCall,
+ conversationWait: { hasPostedCall, pendingQuestionMessageId: messageId },
}: {
- thread: Pick<
- AgentChatThreadWorkspaceEntity,
- 'id' | 'pendingQuestionMessageId'
- >;
+ threadId: string;
workspaceId: string;
- hasPostedCall: boolean;
+ conversationWait: Pick<
+ AgentConversationWait,
+ 'hasPostedCall' | 'pendingQuestionMessageId'
+ >;
}): Promise<void> {
- const messageId = thread.pendingQuestionMessageId;
-
if (hasPostedCall) {
throw new AiException(
'The conversation is waiting on an answer; answer it before sending a message',
@@ -649,7 +649,7 @@ export class AgentChatStreamingService {
// the member moved on from the question, which ends the turn that asked it
await this.threadLifecycleService.closePendingQuestion({
workspaceId,
- threadId: thread.id,
+ threadId,
messageId,
activeStreamId: null,
turnStatus: AgentTurnStatus.COMPLETED,