Skip to content

The open alternative to Salesforce, designed for AI.

Keep a wake-up until what it resumes is handed off (#27704)

Félix Malfait407463a1b078
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
index ad705e6af1e..d6b729ee4b8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
@@ -119,10 +119,11 @@ const buildService = (execution = buildExecution()) => {
};
const pendingWakeUpService = {
- claim: jest.fn().mockResolvedValue({
+ find: jest.fn().mockResolvedValue({
condition: { type: 'ANSWER', threadId: 'thread-id' },
payload: SUSPENSION,
}),
+ claim: jest.fn().mockResolvedValue(null),
cancel: jest.fn().mockResolvedValue([]),
};
@@ -326,7 +327,7 @@ describe('AgentRunnerService', () => {
agentRunConversationService.closeTurn.mockResolvedValue({
isAwaitingAnswer: true,
});
- pendingWakeUpService.claim.mockResolvedValue({
+ pendingWakeUpService.find.mockResolvedValue({
condition: { type: 'ANSWER', threadId: 'thread-id' },
payload: { ...SUSPENSION, continuationCount: 49 },
});
@@ -367,17 +368,58 @@ describe('AgentRunnerService', () => {
expect(agentAsyncExecutorService.executeAgent).not.toHaveBeenCalled();
});
- it('continues a pause once, as a second continuation finds its wake-up claimed', async () => {
+ it('continues a pause once, as a second continuation finds its wake-up removed', async () => {
const { service, pendingWakeUpService, agentAsyncExecutorService } =
buildService();
- pendingWakeUpService.claim.mockResolvedValue(null);
+ pendingWakeUpService.find.mockResolvedValue(null);
await service.continue(CONTINUATION);
expect(agentAsyncExecutorService.executeAgent).not.toHaveBeenCalled();
});
+ it('continues a run again when the worker running it died, as its wake-up is still there', async () => {
+ const {
+ service,
+ pendingWakeUpService,
+ agentAsyncExecutorService,
+ agentRunSuspensionService,
+ } = buildService();
+
+ agentAsyncExecutorService.executeAgent.mockReturnValueOnce(
+ new Promise(() => {}),
+ );
+
+ void service.continue(CONTINUATION);
+
+ while (agentAsyncExecutorService.executeAgent.mock.calls.length === 0) {
+ await Promise.resolve();
+ }
+
+ expect(pendingWakeUpService.claim).not.toHaveBeenCalled();
+
+ await service.continue(CONTINUATION);
+
+ expect(agentAsyncExecutorService.executeAgent).toHaveBeenCalledTimes(2);
+ expect(agentRunSuspensionService.settle).toHaveBeenCalledTimes(1);
+ expect(pendingWakeUpService.claim).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ wakeUpId: 'wake-up-id',
+ });
+ });
+
+ it('keeps the wake-up of a run whose caller could not be handed the outcome', async () => {
+ const { service, pendingWakeUpService, agentRunSuspensionService } =
+ buildService();
+
+ agentRunSuspensionService.settle.mockRejectedValue(new Error('db down'));
+
+ await expect(service.continue(CONTINUATION)).rejects.toThrow('db down');
+
+ expect(pendingWakeUpService.claim).not.toHaveBeenCalled();
+ });
+
it('fails the run when its answer could not be delivered', async () => {
const { service, agentRunSuspensionService, agentAsyncExecutorService } =
buildService();
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts
index ee153432dc8..a43a444ced6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-pending-wake-up-handler.service.ts
@@ -56,7 +56,7 @@ export class AgentRunPendingWakeUpHandlerService
.buildExecutionContext({ workspaceId, caller });
}
- // the run claims its wake-up once it holds its conversation, so the conversation waits until it goes on
+ // the run removes its wake-up once it went on, so the conversation waits until then
async resolve({
wakeUp,
outcome,
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 28d2f106449..1ceb3c7c2c3 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
@@ -115,10 +115,12 @@ export class AgentRunSuspensionService {
}
}
+ // the wake-up stays while its run goes on, so another resolution of it is let go rather than queued behind it
async scheduleContinuation(jobData: ContinueAgentRunJobData): Promise<void> {
await this.messageQueueService.add<ContinueAgentRunJobData>(
CONTINUE_AGENT_RUN_JOB_NAME,
jobData,
+ { deduplication: { id: `continue-agent-run-${jobData.wakeUpId}` } },
);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
index c0dab820307..ebf064e89cb 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
@@ -5,6 +5,7 @@ import { type AgentRunSummary } from 'twenty-shared/ai';
import { type PendingWakeUpCondition } from 'twenty-shared/pending-wake-up';
import { isDefined } from 'twenty-shared/utils';
+import { type PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';
import { PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up.service';
import { AGENT_WAIT_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/agent-wait-prompt.constant';
import { createAgentWaitTools } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/wait-tools/create-agent-wait-tools.util';
@@ -67,8 +68,10 @@ export class AgentRunnerService {
});
}
- // Picks a suspended run up where it paused once its wake-up resolved. The run claims the wake-up
- // under its conversation's lock, so each pause goes on once and the conversation waits until it does
+ // Picks a suspended run up where it paused once its wake-up resolved, under its conversation's lock.
+ // The wake-up is removed only once the run went on and its caller has the outcome, so a job that
+ // died or failed midway finds it again, and a pause the run made again replaced it with another
+ // id, so each pause goes on once
continue({
workspaceId,
threadId,
@@ -79,7 +82,7 @@ export class AgentRunnerService {
workspaceId,
threadId,
work: async () => {
- const wakeUp = await this.pendingWakeUpService.claim({
+ const wakeUp = await this.pendingWakeUpService.find({
workspaceId,
wakeUpId,
});
@@ -88,95 +91,108 @@ export class AgentRunnerService {
return;
}
- const suspension = wakeUp.payload as AgentRunSuspension;
- const isAwaitingAnswer = wakeUp.condition.type === 'ANSWER';
- const { caller, runSpec } = suspension;
- const handler = this.callerHandlerRegistry.getHandlerOrThrow(
- caller.type,
- );
+ await this.continueSuspendedRun({
+ workspaceId,
+ threadId,
+ wakeUp,
+ outcome,
+ });
- let result: AgentRunnerResult;
+ await this.pendingWakeUpService.claim({ workspaceId, wakeUpId });
+ },
+ });
+ }
- // the wake-up is claimed, so a run that cannot go on is settled rather than left paused
- try {
- if (
- (await handler.getWaitingState({ workspaceId, caller })) === 'GONE'
- ) {
- await this.agentRunSuspensionService.closeAwaitedCalls({
- workspaceId,
- threadId,
- isAwaitingAnswer,
- });
+ private async continueSuspendedRun({
+ workspaceId,
+ threadId,
+ wakeUp,
+ outcome,
+ }: Omit<ContinueAgentRunJobData, 'wakeUpId'> & {
+ wakeUp: Pick<PendingWakeUpEntity, 'payload' | 'condition'>;
+ }): Promise<void> {
+ const suspension = wakeUp.payload as AgentRunSuspension;
+ const isAwaitingAnswer = wakeUp.condition.type === 'ANSWER';
+ const { caller, runSpec } = suspension;
+ const handler = this.callerHandlerRegistry.getHandlerOrThrow(caller.type);
- return;
- }
+ let result: AgentRunnerResult;
- if (outcome.type === 'ANSWERED' && 'error' in outcome.answer) {
- throw new Error(outcome.answer.error);
- }
+ // a run that cannot go on is settled rather than left paused
+ try {
+ if ((await handler.getWaitingState({ workspaceId, caller })) === 'GONE') {
+ await this.agentRunSuspensionService.closeAwaitedCalls({
+ workspaceId,
+ threadId,
+ isAwaitingAnswer,
+ });
- // a wait the run called alongside a question is over once the question is answered
- await this.agentRunSuspensionService.recordWaitOutcome({
- workspaceId,
- threadId,
- outcome:
- outcome.type === 'ANSWERED' ? { type: 'CANCELLED' } : outcome,
- });
+ return;
+ }
- const agent = isDefined(runSpec.agentId)
- ? await this.agentRepository.findOne(workspaceId, {
- where: { id: runSpec.agentId },
- })
- : null;
-
- if (isDefined(runSpec.agentId) && !isDefined(agent)) {
- throw new AiException(
- `Agent with id ${runSpec.agentId} not found`,
- AiExceptionCode.AGENT_NOT_FOUND,
- );
- }
+ if (outcome.type === 'ANSWERED' && 'error' in outcome.answer) {
+ throw new Error(outcome.answer.error);
+ }
- result = await this.runTurn({
- input: {
- workspaceId,
- conversation: { threadId, isCreated: false },
- caller,
- spec: runSpec,
- agent,
- prompt: null,
- executionContext: await handler.buildExecutionContext({
- workspaceId,
- caller,
- }),
- },
- suspension,
- });
- } catch (error) {
- await this.agentRunSuspensionService.settle({
- workspaceId,
- threadId,
- suspension,
- outcome: {
- status: 'FAILED',
- error: error instanceof Error ? error.message : String(error),
- },
- isAwaitingAnswer,
- });
+ // a wait the run called alongside a question is over once the question is answered
+ await this.agentRunSuspensionService.recordWaitOutcome({
+ workspaceId,
+ threadId,
+ outcome: outcome.type === 'ANSWERED' ? { type: 'CANCELLED' } : outcome,
+ });
- return;
- }
+ const agent = isDefined(runSpec.agentId)
+ ? await this.agentRepository.findOne(workspaceId, {
+ where: { id: runSpec.agentId },
+ })
+ : null;
- if (result.outcome.status !== 'SUSPENDED') {
- await this.agentRunSuspensionService.settle({
+ if (isDefined(runSpec.agentId) && !isDefined(agent)) {
+ throw new AiException(
+ `Agent with id ${runSpec.agentId} not found`,
+ AiExceptionCode.AGENT_NOT_FOUND,
+ );
+ }
+
+ result = await this.runTurn({
+ input: {
+ workspaceId,
+ conversation: { threadId, isCreated: false },
+ caller,
+ spec: runSpec,
+ agent,
+ prompt: null,
+ executionContext: await handler.buildExecutionContext({
workspaceId,
- threadId,
- suspension,
- outcome: result.outcome,
- summary: result.summary,
- });
- }
- },
- });
+ caller,
+ }),
+ },
+ suspension,
+ });
+ } catch (error) {
+ await this.agentRunSuspensionService.settle({
+ workspaceId,
+ threadId,
+ suspension,
+ outcome: {
+ status: 'FAILED',
+ error: error instanceof Error ? error.message : String(error),
+ },
+ isAwaitingAnswer,
+ });
+
+ return;
+ }
+
+ if (result.outcome.status !== 'SUSPENDED') {
+ await this.agentRunSuspensionService.settle({
+ workspaceId,
+ threadId,
+ suspension,
+ outcome: result.outcome,
+ summary: result.summary,
+ });
+ }
}
private async runTurn({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/continue-agent-run-job-data.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/continue-agent-run-job-data.type.ts
index 37a167aa9a7..0936ec9a0ee 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/continue-agent-run-job-data.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/continue-agent-run-job-data.type.ts
@@ -3,7 +3,7 @@ import { type PendingWakeUpOutcome } from 'src/engine/core-modules/pending-wake-
export type ContinueAgentRunJobData = {
workspaceId: string;
threadId: string;
- // the run's wake-up, which the continuation claims, and what resolved it
+ // the run's wake-up, which the continuation removes once the run went on, and what resolved it
wakeUpId: string;
outcome: PendingWakeUpOutcome;
};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-waiting-step.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-waiting-step.workspace-service.spec.ts
index aa7c15ad0f2..d709cf9531e 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-waiting-step.workspace-service.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-waiting-step.workspace-service.spec.ts
@@ -57,12 +57,6 @@ const buildService = ({
stepInfos: { [STEP_ID]: { status: stepStatus, error: stepError } },
},
}),
- updateStepInfoIfPending: jest
- .fn()
- .mockResolvedValue(
- runStatus === WorkflowRunStatus.RUNNING &&
- stepStatus === StepStatus.PENDING,
- ),
endWorkflowRun: jest.fn(),
};
const workflowExecutionContextService = {
@@ -121,9 +115,8 @@ describe('WorkflowWaitingStepWorkspaceService as a wake-up owner', () => {
expect(messageQueueService.add).not.toHaveBeenCalled();
});
- it('completes the step with the record as the run reads it and resumes the run', async () => {
- const { service, workflowRunWorkspaceService, messageQueueService } =
- buildService();
+ it('ends the step with the record as the run reads it through the run job', async () => {
+ const { service, messageQueueService } = buildService();
await service.resolve({
workspaceId: WORKSPACE_ID,
@@ -131,40 +124,44 @@ describe('WorkflowWaitingStepWorkspaceService as a wake-up owner', () => {
event: EVENT,
});
- expect(
- workflowRunWorkspaceService.updateStepInfoIfPending,
- ).toHaveBeenCalledWith(
- expect.objectContaining({
- stepId: STEP_ID,
- stepInfo: {
- status: StepStatus.SUCCESS,
- result: { hasTimedOut: false, ...EVENT, record: READABLE_RECORD },
- },
- }),
- );
expect(messageQueueService.add).toHaveBeenCalledWith(
RUN_WORKFLOW_JOB_NAME,
{
workspaceId: WORKSPACE_ID,
workflowRunId: WORKFLOW_RUN_ID,
- lastExecutedStepId: STEP_ID,
+ awaitedStepOutput: {
+ stepId: STEP_ID,
+ actionOutput: {
+ result: { hasTimedOut: false, ...EVENT, record: READABLE_RECORD },
+ },
+ },
},
expect.anything(),
);
});
+ it('resumes the step once when its wait is resolved twice', async () => {
+ const { service, pendingWakeUpService, messageQueueService } =
+ buildService();
+
+ pendingWakeUpService.claim.mockResolvedValue(null);
+
+ await service.resolve({ workspaceId: WORKSPACE_ID, wakeUpId: WAIT_ID });
+
+ expect(messageQueueService.add).not.toHaveBeenCalled();
+ });
+
it('ends the step with the answer to the call it posted through the run job', async () => {
- const { service, workflowRunWorkspaceService, messageQueueService } =
- buildService({
- storedWait: {
- ...STORED_WAIT,
- condition: {
- type: 'ANSWER',
- threadId: 'thread-id',
- toolCallId: 'call-id',
- },
+ const { service, messageQueueService } = buildService({
+ storedWait: {
+ ...STORED_WAIT,
+ condition: {
+ type: 'ANSWER',
+ threadId: 'thread-id',
+ toolCallId: 'call-id',
},
- });
+ },
+ });
await service.resolve({
workspaceId: WORKSPACE_ID,
@@ -172,9 +169,6 @@ describe('WorkflowWaitingStepWorkspaceService as a wake-up owner', () => {
answer: { result: { threadId: 'thread-id', outcome: 'executed' } },
});
- expect(
- workflowRunWorkspaceService.updateStepInfoIfPending,
- ).not.toHaveBeenCalled();
expect(messageQueueService.add).toHaveBeenCalledWith(
RUN_WORKFLOW_JOB_NAME,
{
@@ -210,8 +204,9 @@ describe('WorkflowWaitingStepWorkspaceService as a wake-up owner', () => {
});
it('keeps waiting when the run cannot read the record of the event', async () => {
- const { service, pendingWakeUpService, workflowRunWorkspaceService } =
- buildService({ readableRecords: [] });
+ const { service, pendingWakeUpService, messageQueueService } = buildService(
+ { readableRecords: [] },
+ );
await service.resolve({
workspaceId: WORKSPACE_ID,
@@ -220,9 +215,7 @@ describe('WorkflowWaitingStepWorkspaceService as a wake-up owner', () => {
});
expect(pendingWakeUpService.claim).not.toHaveBeenCalled();
- expect(
- workflowRunWorkspaceService.updateStepInfoIfPending,
- ).not.toHaveBeenCalled();
+ expect(messageQueueService.add).not.toHaveBeenCalled();
});
it('keeps the event and tries again when reading its record fails', async () => {
@@ -259,7 +252,7 @@ describe('WorkflowWaitingStepWorkspaceService as a wake-up owner', () => {
});
it('keeps fields the run cannot read out of the previous snapshot', async () => {
- const { service, workflowRunWorkspaceService } = buildService();
+ const { service, messageQueueService } = buildService();
await service.resolve({
workspaceId: WORKSPACE_ID,
@@ -271,11 +264,15 @@ describe('WorkflowWaitingStepWorkspaceService as a wake-up owner', () => {
},
});
- const [{ stepInfo }] =
- workflowRunWorkspaceService.updateStepInfoIfPending.mock.calls[0];
+ const [, { awaitedStepOutput }] = messageQueueService.add.mock.calls[0];
- expect(stepInfo.result.before).toEqual({ id: 'company-id', name: 'Old' });
- expect(stepInfo.result.updatedFields).toEqual(['name']);
+ expect(awaitedStepOutput.actionOutput.result.before).toEqual({
+ id: 'company-id',
+ name: 'Old',
+ });
+ expect(awaitedStepOutput.actionOutput.result.updatedFields).toEqual([
+ 'name',
+ ]);
});
it('reads deleted records when the event is a deletion', async () => {
@@ -335,16 +332,19 @@ describe('WorkflowWaitingStepWorkspaceService as a wake-up owner', () => {
});
it('reports a timeout when an event wait expires', async () => {
- const { service, workflowRunWorkspaceService } = buildService();
+ const { service, messageQueueService } = buildService();
await service.resolve({ workspaceId: WORKSPACE_ID, wakeUpId: WAIT_ID });
- expect(
- workflowRunWorkspaceService.updateStepInfoIfPending,
- ).toHaveBeenCalledWith(
+ expect(messageQueueService.add).toHaveBeenCalledWith(
+ RUN_WORKFLOW_JOB_NAME,
expect.objectContaining({
- stepInfo: { status: StepStatus.SUCCESS, result: { hasTimedOut: true } },
+ awaitedStepOutput: {
+ stepId: STEP_ID,
+ actionOutput: { result: { hasTimedOut: true } },
+ },
}),
+ expect.anything(),
);
});
@@ -360,19 +360,13 @@ describe('WorkflowWaitingStepWorkspaceService as a wake-up owner', () => {
});
it('removes the wait of a step that now waits on a retry without resuming it', async () => {
- const {
- service,
- pendingWakeUpService,
- workflowRunWorkspaceService,
- messageQueueService,
- } = buildService({ stepError: 'Step failed' });
+ const { service, pendingWakeUpService, messageQueueService } = buildService(
+ { stepError: 'Step failed' },
+ );
await service.resolve({ workspaceId: WORKSPACE_ID, wakeUpId: WAIT_ID });
expect(pendingWakeUpService.claim).toHaveBeenCalled();
- expect(
- workflowRunWorkspaceService.updateStepInfoIfPending,
- ).not.toHaveBeenCalled();
expect(messageQueueService.add).not.toHaveBeenCalled();
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-waiting-step.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-waiting-step.workspace-service.ts
index 17d0e377a0b..14c79ccc636 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-waiting-step.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-waiting-step.workspace-service.ts
@@ -27,7 +27,6 @@ import { buildWorkflowAgentRunExecutionContext } from 'src/modules/workflow/work
import { RUN_WORKFLOW_JOB_NAME } from 'src/modules/workflow/workflow-runner/constants/run-workflow-job-name';
import { type RunWorkflowJobData } from 'src/modules/workflow/workflow-runner/types/run-workflow-job-data.type';
import { buildRunWorkflowJobOptions } from 'src/modules/workflow/workflow-runner/utils/build-run-workflow-job-options.util';
-import { isWorkflowRunNotFoundError } from 'src/modules/workflow/workflow-runner/utils/is-workflow-run-not-found-error.util';
import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
import { buildDefaultWaitResult } from 'src/modules/workflow/workflow-wait/utils/build-default-wait-result.util';
@@ -198,6 +197,8 @@ export class WorkflowWaitingStepWorkspaceService
}): Promise<void> {
const { workspaceId, ownerId: workflowRunId, ownerKey: stepId } = wakeUp;
+ // claiming is what resumes each wait once: the run job knows only the step, so a second delivery
+ // could otherwise resume the step's next wait, in a loop, with this one's outcome
if (
!isDefined(
await this.pendingWakeUpService.claim({
@@ -212,45 +213,24 @@ export class WorkflowWaitingStepWorkspaceService
// the claimed wait is gone, so a step that cannot resume would wait forever
try {
- // an answered call ends the step through the executor's usual path, so a failure is retried
- // or continues on failure like any failed step
- if (outcome.type === 'ANSWERED') {
- await this.messageQueueService.add<RunWorkflowJobData>(
- RUN_WORKFLOW_JOB_NAME,
- {
- workspaceId,
- workflowRunId,
- awaitedStepOutput: { stepId, actionOutput: outcome.answer },
- },
- buildRunWorkflowJobOptions(workflowRunId),
- );
-
- return;
- }
-
- const hasCompletedStep =
- await this.workflowRunWorkspaceService.updateStepInfoIfPending({
- stepId,
- stepInfo: {
- status: StepStatus.SUCCESS,
- result: buildDefaultWaitResult(outcome),
- },
- workflowRunId,
+ // the step ends through the executor's usual path, so a failure is retried or continues on
+ // failure like any failed step
+ await this.messageQueueService.add<RunWorkflowJobData>(
+ RUN_WORKFLOW_JOB_NAME,
+ {
workspaceId,
- });
-
- if (hasCompletedStep) {
- await this.messageQueueService.add<RunWorkflowJobData>(
- RUN_WORKFLOW_JOB_NAME,
- { workspaceId, workflowRunId, lastExecutedStepId: stepId },
- buildRunWorkflowJobOptions(workflowRunId),
- );
- }
+ workflowRunId,
+ awaitedStepOutput: {
+ stepId,
+ actionOutput:
+ outcome.type === 'ANSWERED'
+ ? outcome.answer
+ : { result: buildDefaultWaitResult(outcome) },
+ },
+ },
+ buildRunWorkflowJobOptions(workflowRunId),
+ );
} catch (error) {
- if (isWorkflowRunNotFoundError(error)) {
- return;
- }
-
await this.workflowRunWorkspaceService.endWorkflowRun({
workflowRunId,
workspaceId,
diff --git a/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts
index 20e34205d8d..e189a21596f 100644
--- a/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts
+++ b/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts
@@ -206,14 +206,15 @@ describe('agent runs that wait (integration)', () => {
Object.keys(executeAgent.mock.calls[0][0].pausingTools ?? {}),
).toEqual(['wait_for_event', 'wait_for_duration']);
+ // the wake-up goes once the run went on, just after its turn closes
await expectEventually(async () => {
expect(await findTurnStatuses(suspension.threadId)).toEqual([
'completed',
'completed',
]);
+ expect(await findSuspensions('AGENT_TRIGGER', agentId)).toEqual([]);
});
- expect(await findSuspensions('AGENT_TRIGGER', agentId)).toEqual([]);
expect(executeAgent).toHaveBeenCalledTimes(2);
expect(executeAgent.mock.calls[1][0].messages).toEqual([]);
expect(
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/wait-for-event-workflow.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/wait-for-event-workflow.integration-spec.ts
index 3909b7f5425..ec60b006dde 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/wait-for-event-workflow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/wait-for-event-workflow.integration-spec.ts
@@ -4,6 +4,7 @@ import {
getWorkflowRun,
} from 'test/integration/graphql/suites/workflow/utils/workflow-run-test.util';
import { updateWorkflowVersionTrigger } from 'test/integration/graphql/suites/workflow/utils/update-workflow-version-trigger.util';
+import { expectEventually } from 'test/integration/utils/expect-eventually.util';
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { v4 } from 'uuid';
@@ -383,17 +384,15 @@ describe('Wait for event workflow (e2e)', () => {
event,
});
- await (
- await global.workflowTestServices.runJob()
- ).handle({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workflowRunId: createdWorkflowRunId,
- lastExecutedStepId: waitStepId!,
+ // the step resumes through the run job its wake-up queued
+ await expectEventually(async () => {
+ expect((await getWorkflowRun(createdWorkflowRunId!))?.status).toBe(
+ 'COMPLETED',
+ );
});
const completedRun = await getWorkflowRun(createdWorkflowRunId);
- expect(completedRun?.status).toBe('COMPLETED');
expect(completedRun?.state?.stepInfos?.[waitStepId!]).toMatchObject({
status: 'SUCCESS',
result: {