Skip to content

The open alternative to Salesforce, designed for AI.

feat(workflow): waits as a first-class step outcome, Wait for Event node, agent waits (#27247)

Félix Malfait33d034239a25
diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.ts
index 7d3ca8e2d6d..9a33ce6af16 100644
--- a/packages/twenty-front/src/generated/graphql.ts
+++ b/packages/twenty-front/src/generated/graphql.ts
@@ -1113,7 +1113,8 @@ export enum WorkflowActionType {
SEND_CHAT_MESSAGE = 'SEND_CHAT_MESSAGE',
SEND_EMAIL = 'SEND_EMAIL',
UPDATE_RECORD = 'UPDATE_RECORD',
- UPSERT_RECORD = 'UPSERT_RECORD'
+ UPSERT_RECORD = 'UPSERT_RECORD',
+ WAIT_FOR_EVENT = 'WAIT_FOR_EVENT'
}
export type WorkflowRun = {
diff --git a/packages/twenty-front/src/modules/workflow/types/Workflow.ts b/packages/twenty-front/src/modules/workflow/types/Workflow.ts
index 46107692eaa..5b6d774f084 100644
--- a/packages/twenty-front/src/modules/workflow/types/Workflow.ts
+++ b/packages/twenty-front/src/modules/workflow/types/Workflow.ts
@@ -10,6 +10,7 @@ import {
type workflowCronTriggerSchema,
type workflowDatabaseEventTriggerSchema,
type workflowDelayActionSchema,
+ type workflowWaitForEventActionSchema,
type workflowDeleteRecordActionSchema,
type workflowDraftEmailActionSchema,
type workflowEmptyActionSchema,
@@ -70,6 +71,9 @@ export type WorkflowPickRecordAction = z.infer<
typeof workflowPickRecordActionSchema
>;
export type WorkflowDelayAction = z.infer<typeof workflowDelayActionSchema>;
+export type WorkflowWaitForEventAction = z.infer<
+ typeof workflowWaitForEventActionSchema
+>;
export type WorkflowFilterAction = z.infer<typeof workflowFilterActionSchema>;
export type WorkflowFormAction = z.infer<typeof workflowFormActionSchema>;
export type WorkflowIfElseAction = z.infer<typeof workflowIfElseActionSchema>;
@@ -106,6 +110,7 @@ export type WorkflowAction =
| WorkflowClassifyAction
| WorkflowIteratorAction
| WorkflowDelayAction
+ | WorkflowWaitForEventAction
| WorkflowEmptyAction;
export type WorkflowActionType = WorkflowAction['type'];
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowRunStepNodeDetail.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowRunStepNodeDetail.tsx
index 0a524855449..3a7ae1e8709 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowRunStepNodeDetail.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowRunStepNodeDetail.tsx
@@ -16,6 +16,7 @@ import { WorkflowEditActionEmailBase } from '@/workflow/workflow-steps/workflow-
import { WorkflowEditActionUpdateRecord } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionUpdateRecord';
import { WorkflowEditActionUpsertRecord } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionUpsertRecord';
import { WorkflowEditActionDelay } from '@/workflow/workflow-steps/workflow-actions/delay-actions/components/WorkflowEditActionDelay';
+import { WorkflowEditActionWaitForEvent } from '@/workflow/workflow-steps/workflow-actions/wait-for-event-action/components/WorkflowEditActionWaitForEvent';
import { WorkflowEditActionFilter } from '@/workflow/workflow-steps/workflow-actions/filter-action/components/WorkflowEditActionFilter';
import { WorkflowEditActionFindRecords } from '@/workflow/workflow-steps/workflow-actions/find-records-action/components/WorkflowEditActionFindRecords';
import { WorkflowEditActionFormFiller } from '@/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormFiller';
@@ -338,6 +339,17 @@ export const WorkflowRunStepNodeDetail = ({
/>
);
}
+ case 'WAIT_FOR_EVENT': {
+ return (
+ <WorkflowEditActionWaitForEvent
+ key={stepId}
+ action={stepDefinition.definition}
+ actionOptions={{
+ readonly: true,
+ }}
+ />
+ );
+ }
}
}
}
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepDetail.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepDetail.tsx
index 5df68c17d7f..0713576d1c1 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepDetail.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepDetail.tsx
@@ -15,6 +15,7 @@ import { WorkflowEditActionEmailBase } from '@/workflow/workflow-steps/workflow-
import { WorkflowEditActionUpdateRecord } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionUpdateRecord';
import { WorkflowEditActionUpsertRecord } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionUpsertRecord';
import { WorkflowEditActionDelay } from '@/workflow/workflow-steps/workflow-actions/delay-actions/components/WorkflowEditActionDelay';
+import { WorkflowEditActionWaitForEvent } from '@/workflow/workflow-steps/workflow-actions/wait-for-event-action/components/WorkflowEditActionWaitForEvent';
import { WorkflowEditActionFilter } from '@/workflow/workflow-steps/workflow-actions/filter-action/components/WorkflowEditActionFilter';
import { WorkflowEditActionFindRecords } from '@/workflow/workflow-steps/workflow-actions/find-records-action/components/WorkflowEditActionFindRecords';
import { WorkflowEditActionFormBuilder } from '@/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormBuilder';
@@ -294,6 +295,15 @@ export const WorkflowStepDetail = ({
/>
);
}
+ case 'WAIT_FOR_EVENT': {
+ return (
+ <WorkflowEditActionWaitForEvent
+ key={stepId}
+ action={stepDefinition.definition}
+ actionOptions={props}
+ />
+ );
+ }
default:
return assertUnreachable(
stepDefinition.definition,
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/FlowActions.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/FlowActions.ts
index cee43794ceb..78a88293a33 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/FlowActions.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/FlowActions.ts
@@ -3,12 +3,19 @@ import { DELAY_ACTION } from '@/workflow/workflow-steps/workflow-actions/constan
import { FILTER_ACTION } from '@/workflow/workflow-steps/workflow-actions/constants/actions/FilterAction';
import { IF_ELSE_ACTION } from '@/workflow/workflow-steps/workflow-actions/constants/actions/IfElseAction';
import { ITERATOR_ACTION } from '@/workflow/workflow-steps/workflow-actions/constants/actions/IteratorAction';
+import { WAIT_FOR_EVENT_ACTION } from '@/workflow/workflow-steps/workflow-actions/constants/actions/WaitForEventAction';
export const FLOW_ACTIONS: Array<{
defaultLabel: string;
type: Extract<
WorkflowActionType,
- 'ITERATOR' | 'FILTER' | 'IF_ELSE' | 'DELAY'
+ 'ITERATOR' | 'FILTER' | 'IF_ELSE' | 'DELAY' | 'WAIT_FOR_EVENT'
>;
icon: string;
-}> = [ITERATOR_ACTION, FILTER_ACTION, IF_ELSE_ACTION, DELAY_ACTION];
+}> = [
+ ITERATOR_ACTION,
+ FILTER_ACTION,
+ IF_ELSE_ACTION,
+ DELAY_ACTION,
+ WAIT_FOR_EVENT_ACTION,
+];
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/WaitForEventAction.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/WaitForEventAction.ts
new file mode 100644
index 00000000000..b9480a5de0a
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/WaitForEventAction.ts
@@ -0,0 +1,11 @@
+import { type WorkflowActionType } from '@/workflow/types/Workflow';
+
+export const WAIT_FOR_EVENT_ACTION: {
+ defaultLabel: string;
+ type: Extract<WorkflowActionType, 'WAIT_FOR_EVENT'>;
+ icon: string;
+} = {
+ defaultLabel: 'Wait for Event',
+ type: 'WAIT_FOR_EVENT',
+ icon: 'IconHourglass',
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIcon.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIcon.ts
index eeb1bb6a88a..2f2e8e22b5d 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIcon.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIcon.ts
@@ -30,6 +30,7 @@ export const getActionIcon = (actionType: WorkflowActionType) => {
return HUMAN_INPUT_ACTIONS.find((item) => item.type === actionType)?.icon;
case 'ITERATOR':
case 'DELAY':
+ case 'WAIT_FOR_EVENT':
case 'FILTER':
case 'IF_ELSE':
return FLOW_ACTIONS.find((item) => item.type === actionType)?.icon;
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconColorOrThrow.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconColorOrThrow.ts
index fd570a5a6e5..5475bc4e28b 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconColorOrThrow.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconColorOrThrow.ts
@@ -28,6 +28,7 @@ export const getActionIconColorOrThrow = (
case 'FILTER':
case 'IF_ELSE':
case 'DELAY':
+ case 'WAIT_FOR_EVENT':
return themeCssVariables.color.green9;
case 'AI_AGENT':
case 'CLASSIFY':
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconStrokeOrThrow.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconStrokeOrThrow.ts
index 1d487e40342..673713e908f 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconStrokeOrThrow.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconStrokeOrThrow.ts
@@ -25,6 +25,7 @@ export const getActionIconStrokeOrThrow = (
case 'EMPTY':
case 'FILTER':
case 'DELAY':
+ case 'WAIT_FOR_EVENT':
case 'AI_AGENT':
case 'CLASSIFY':
return undefined;
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/wait-for-event-action/components/WorkflowEditActionWaitForEvent.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/wait-for-event-action/components/WorkflowEditActionWaitForEvent.tsx
new file mode 100644
index 00000000000..20799179098
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/wait-for-event-action/components/WorkflowEditActionWaitForEvent.tsx
@@ -0,0 +1,216 @@
+import { useFilteredObjectMetadataItems } from '@/object-metadata/hooks/useFilteredObjectMetadataItems';
+import { FormNumberFieldInput } from '@/object-record/record-field/ui/form-types/components/FormNumberFieldInput';
+import { FormSingleRecordPicker } from '@/object-record/record-field/ui/form-types/components/FormSingleRecordPicker';
+import { type FieldMultiSelectValue } from '@/object-record/record-field/ui/types/FieldMetadata';
+import { Select } from '@/ui/input/components/Select';
+import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';
+import { WorkflowFieldsMultiSelect } from '@/workflow/components/WorkflowEditUpdateEventFieldsMultiSelect';
+import { useWorkflowObjectSelectOptions } from '@/workflow/hooks/useWorkflowObjectSelectOptions';
+import { type WorkflowWaitForEventAction } from '@/workflow/types/Workflow';
+import { splitWorkflowTriggerEventName } from '@/workflow/utils/splitWorkflowTriggerEventName';
+import { WorkflowStepBody } from '@/workflow/workflow-steps/components/WorkflowStepBody';
+import { WorkflowStepFooter } from '@/workflow/workflow-steps/components/WorkflowStepFooter';
+import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
+import { useLingui } from '@lingui/react/macro';
+import { isNumber } from '@sniptt/guards';
+import { useState } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { type SelectOption } from 'twenty-ui/primitives/input';
+import { HorizontalSeparator } from 'twenty-ui/primitives/layout';
+
+type WaitForEventInput = WorkflowWaitForEventAction['settings']['input'];
+
+type WaitForEventTimeout = NonNullable<WaitForEventInput['timeout']>;
+
+type WaitForEventType = 'created' | 'updated' | 'deleted';
+
+type WorkflowEditActionWaitForEventProps = {
+ action: WorkflowWaitForEventAction;
+ actionOptions:
+ | {
+ readonly: true;
+ }
+ | {
+ readonly?: false;
+ onActionUpdate: (action: WorkflowWaitForEventAction) => void;
+ };
+};
+
+export const WorkflowEditActionWaitForEvent = ({
+ action,
+ actionOptions,
+}: WorkflowEditActionWaitForEventProps) => {
+ const { t } = useLingui();
+
+ const { objectMetadataItems } = useFilteredObjectMetadataItems();
+ const objectOptions = useWorkflowObjectSelectOptions();
+
+ const [timeoutDraft, setTimeoutDraft] = useState<WaitForEventTimeout>(
+ () => action.settings.input.timeout ?? {},
+ );
+
+ const { objectType, event } = splitWorkflowTriggerEventName(
+ action.settings.input.eventName,
+ );
+
+ const eventOptions: Array<SelectOption<WaitForEventType>> = [
+ { label: t`Record is created`, value: 'created' },
+ { label: t`Record is updated`, value: 'updated' },
+ { label: t`Record is deleted`, value: 'deleted' },
+ ];
+
+ const selectedEvent = eventOptions.find(
+ (eventOption) => eventOption.value === event,
+ )?.value;
+
+ const selectedObjectMetadataItem = objectMetadataItems.find(
+ (item) => item.isActive && item.nameSingular === objectType,
+ );
+
+ const updateInput = (input: Partial<WaitForEventInput>) => {
+ if (actionOptions.readonly) {
+ return;
+ }
+
+ actionOptions.onActionUpdate({
+ ...action,
+ settings: {
+ ...action.settings,
+ input: {
+ ...action.settings.input,
+ ...input,
+ },
+ },
+ });
+ };
+
+ // a record and fields only make sense for the object they were picked on
+ const handleObjectTypeChange = (newObjectType: string) => {
+ updateInput({
+ eventName: `${newObjectType}.${selectedEvent ?? 'updated'}`,
+ recordId: null,
+ updatedFields: null,
+ });
+ };
+
+ const handleEventChange = (newEvent: WaitForEventType) => {
+ updateInput({
+ eventName: `${objectType}.${newEvent}`,
+ ...(newEvent === 'updated' ? {} : { updatedFields: null }),
+ });
+ };
+
+ const handleUpdatedFieldsChange = (
+ fields: FieldMultiSelectValue | string,
+ ) => {
+ if (!isDefined(fields)) {
+ updateInput({ updatedFields: null });
+
+ return;
+ }
+
+ updateInput({ updatedFields: Array.isArray(fields) ? fields : [fields] });
+ };
+
+ const handleTimeoutDraftChange = (
+ unit: keyof WaitForEventTimeout,
+ value: number | string | null,
+ ) => {
+ // the step only accepts non-negative durations, so a negative one is not kept
+ if (isNumber(value) && value < 0) {
+ return;
+ }
+
+ setTimeoutDraft((previousTimeout) => ({
+ ...previousTimeout,
+ [unit]: value ?? undefined,
+ }));
+ };
+
+ const handleTimeoutCommit = () => {
+ updateInput({ timeout: timeoutDraft });
+ };
+
+ return (
+ <>
+ <WorkflowStepBody>
+ <Select
+ dropdownId="workflow-edit-action-wait-for-event-object"
+ label={t`Record Type`}
+ fullWidth
+ disabled={actionOptions.readonly}
+ value={objectType}
+ emptyOption={{ label: t`Select an option`, value: '' }}
+ options={objectOptions}
+ onChange={handleObjectTypeChange}
+ withSearchInput
+ dropdownSideOffset={4}
+ dropdownWidth={GenericDropdownContentWidth.ExtraLarge}
+ />
+ <Select
+ dropdownId="workflow-edit-action-wait-for-event-event"
+ label={t`Event`}
+ fullWidth
+ disabled={actionOptions.readonly}
+ value={selectedEvent}
+ options={eventOptions}
+ onChange={handleEventChange}
+ dropdownWidth={GenericDropdownContentWidth.Large}
+ />
+ {isDefined(selectedObjectMetadataItem) && (
+ <FormSingleRecordPicker
+ testId="workflow-wait-for-event-record-id"
+ label={t`Record (Optional)`}
+ onChange={(recordId) => updateInput({ recordId })}
+ objectNameSingulars={[selectedObjectMetadataItem.nameSingular]}
+ defaultValue={action.settings.input.recordId ?? undefined}
+ disabled={actionOptions.readonly}
+ VariablePicker={WorkflowVariablePicker}
+ />
+ )}
+ {isDefined(selectedObjectMetadataItem) && event === 'updated' && (
+ <WorkflowFieldsMultiSelect
+ key={objectType}
+ label={t`Fields (Optional)`}
+ placeholder={t`Select specific fields to wait for`}
+ objectMetadataItem={selectedObjectMetadataItem}
+ handleFieldsChange={handleUpdatedFieldsChange}
+ readonly={actionOptions.readonly ?? false}
+ defaultFields={action.settings.input.updatedFields}
+ actionType="DATABASE_EVENT"
+ />
+ )}
+ <HorizontalSeparator noMargin />
+ <FormNumberFieldInput
+ label={t`Timeout days (Optional)`}
+ defaultValue={timeoutDraft.days}
+ onChange={(value) => handleTimeoutDraftChange('days', value)}
+ onBlur={handleTimeoutCommit}
+ readonly={actionOptions.readonly}
+ VariablePicker={WorkflowVariablePicker}
+ placeholder={t`0`}
+ />
+ <FormNumberFieldInput
+ label={t`Timeout hours (Optional)`}
+ defaultValue={timeoutDraft.hours}
+ onChange={(value) => handleTimeoutDraftChange('hours', value)}
+ onBlur={handleTimeoutCommit}
+ readonly={actionOptions.readonly}
+ VariablePicker={WorkflowVariablePicker}
+ placeholder={t`0`}
+ />
+ <FormNumberFieldInput
+ label={t`Timeout minutes (Optional)`}
+ defaultValue={timeoutDraft.minutes}
+ onChange={(value) => handleTimeoutDraftChange('minutes', value)}
+ onBlur={handleTimeoutCommit}
+ readonly={actionOptions.readonly}
+ VariablePicker={WorkflowVariablePicker}
+ placeholder={t`0`}
+ />
+ </WorkflowStepBody>
+
+ {!actionOptions.readonly && <WorkflowStepFooter stepId={action.id} />}
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/types/StepOutputSchemaV2.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/types/StepOutputSchemaV2.ts
index 17c4b65045f..a9db989e3d6 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/types/StepOutputSchemaV2.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/types/StepOutputSchemaV2.ts
@@ -7,6 +7,7 @@ import { type FindRecordsOutputSchema } from '@/workflow/workflow-variables/type
import { type FormOutputSchema } from '@/workflow/workflow-variables/types/FormOutputSchema';
import { type IteratorOutputSchema } from '@/workflow/workflow-variables/types/IteratorOutputSchema';
import { type RecordOutputSchemaV2 } from '@/workflow/workflow-variables/types/RecordOutputSchemaV2';
+import { type WaitForEventOutputSchema } from '@/workflow/workflow-variables/types/WaitForEventOutputSchema';
import {
type BaseOutputSchemaV2,
type ManualTriggerOutputSchema,
@@ -19,7 +20,8 @@ export type OutputSchemaV2 =
| FormOutputSchema
| RecordOutputSchemaV2
| ManualTriggerOutputSchema
- | IteratorOutputSchema;
+ | IteratorOutputSchema
+ | WaitForEventOutputSchema;
export type StepOutputSchemaV2 = {
id: string;
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/types/WaitForEventOutputSchema.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/types/WaitForEventOutputSchema.ts
new file mode 100644
index 00000000000..c73d1dc7416
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/types/WaitForEventOutputSchema.ts
@@ -0,0 +1,10 @@
+import { type RecordNode } from '@/workflow/workflow-variables/types/RecordNode';
+import type { Leaf } from 'twenty-shared/workflow';
+
+export type WaitForEventOutputSchema = {
+ record: RecordNode;
+ recordId: Leaf;
+ before?: RecordNode;
+ updatedFields?: Leaf;
+ hasTimedOut: Leaf;
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/computeStepOutputSchema.test.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/computeStepOutputSchema.test.ts
index 8ba65751a93..70a03ab262e 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/computeStepOutputSchema.test.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/computeStepOutputSchema.test.ts
@@ -422,6 +422,55 @@ describe('computeStepOutputSchema', () => {
});
});
+ describe('WAIT_FOR_EVENT step', () => {
+ it('should expose the record of the event and whether the wait timed out', () => {
+ const result = computeStepOutputSchema({
+ step: {
+ type: 'WAIT_FOR_EVENT',
+ settings: { input: { eventName: 'company.updated' } },
+ } as any,
+ objectMetadataItems: [mockCompanyObjectMetadataItem],
+ });
+
+ expect(Object.keys(result ?? {})).toEqual([
+ 'record',
+ 'recordId',
+ 'hasTimedOut',
+ 'before',
+ 'updatedFields',
+ ]);
+ expect((result as any).record.label).toBe('Company');
+ });
+
+ it('should not expose update details for events that are not updates', () => {
+ const result = computeStepOutputSchema({
+ step: {
+ type: 'WAIT_FOR_EVENT',
+ settings: { input: { eventName: 'company.created' } },
+ } as any,
+ objectMetadataItems: [mockCompanyObjectMetadataItem],
+ });
+
+ expect(Object.keys(result ?? {})).toEqual([
+ 'record',
+ 'recordId',
+ 'hasTimedOut',
+ ]);
+ });
+
+ it('should return empty object when the event cannot be parsed', () => {
+ const result = computeStepOutputSchema({
+ step: {
+ type: 'WAIT_FOR_EVENT',
+ settings: { input: { eventName: 'company' } },
+ } as any,
+ objectMetadataItems: [mockCompanyObjectMetadataItem],
+ });
+
+ expect(result).toEqual({});
+ });
+ });
+
describe('FORM step', () => {
it('should return empty object when form fields are not defined', () => {
const result = computeStepOutputSchema({
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts
index d64aa03eea7..1c97b820207 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts
@@ -10,6 +10,7 @@ import { generateFindRecordsOutputSchema } from '@/workflow/workflow-variables/u
import { generateFormOutputSchema } from '@/workflow/workflow-variables/utils/generate/generateFormOutputSchema';
import { generateRecordEventOutputSchema } from '@/workflow/workflow-variables/utils/generate/generateRecordEventOutputSchema';
import { generateRecordOutputSchema } from '@/workflow/workflow-variables/utils/generate/generateRecordOutputSchema';
+import { generateWaitForEventOutputSchema } from '@/workflow/workflow-variables/utils/generate/generateWaitForEventOutputSchema';
import { FieldMetadataType } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import {
@@ -346,6 +347,30 @@ export const computeStepOutputSchema = ({
return generateClassifyOutputSchema(step.settings.input.questions);
}
+ case 'WAIT_FOR_EVENT': {
+ const parsedEventName = parseEventName(
+ step.settings?.input?.eventName ?? '',
+ );
+
+ if (!isDefined(parsedEventName)) {
+ return {};
+ }
+
+ const objectMetadataItem = findObjectMetadataItemByName(
+ objectMetadataItems,
+ parsedEventName.objectName,
+ );
+
+ if (!isDefined(objectMetadataItem)) {
+ return {};
+ }
+
+ return generateWaitForEventOutputSchema(
+ objectMetadataItem,
+ parsedEventName.action,
+ );
+ }
+
case 'FILTER':
case 'DELAY':
case 'EMPTY': {
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/generateWaitForEventOutputSchema.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/generateWaitForEventOutputSchema.ts
new file mode 100644
index 00000000000..df80eb32aef
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/generateWaitForEventOutputSchema.ts
@@ -0,0 +1,56 @@
+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
+import { type WaitForEventOutputSchema } from '@/workflow/workflow-variables/types/WaitForEventOutputSchema';
+import { generateRecordOutputSchema } from '@/workflow/workflow-variables/utils/generate/generateRecordOutputSchema';
+import { DatabaseEventAction } from '~/generated-metadata/graphql';
+
+export const generateWaitForEventOutputSchema = (
+ objectMetadataItem: EnrichedObjectMetadataItem,
+ action: DatabaseEventAction,
+): WaitForEventOutputSchema => {
+ const outputSchema: WaitForEventOutputSchema = {
+ record: {
+ isLeaf: false,
+ icon: objectMetadataItem.icon ?? undefined,
+ label: objectMetadataItem.labelSingular,
+ value: generateRecordOutputSchema(objectMetadataItem),
+ },
+ recordId: {
+ isLeaf: true,
+ icon: 'IconId',
+ type: 'string',
+ label: 'Record ID',
+ value: '',
+ },
+ hasTimedOut: {
+ isLeaf: true,
+ icon: 'IconClockX',
+ type: 'boolean',
+ label: 'Has Timed Out',
+ value: false,
+ },
+ };
+
+ if (
+ action !== DatabaseEventAction.UPDATED &&
+ action !== DatabaseEventAction.UPSERTED
+ ) {
+ return outputSchema;
+ }
+
+ return {
+ ...outputSchema,
+ before: {
+ isLeaf: false,
+ icon: 'IconHistory',
+ label: `${objectMetadataItem.labelSingular} Before Update`,
+ value: generateRecordOutputSchema(objectMetadataItem),
+ },
+ updatedFields: {
+ isLeaf: true,
+ icon: 'IconListDetails',
+ type: 'array',
+ label: 'Updated Fields',
+ value: [],
+ },
+ };
+};
diff --git a/packages/twenty-server/src/database/commands/cron-register-all.command.ts b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
index 5be371110a4..e37acdd5d65 100644
--- a/packages/twenty-server/src/database/commands/cron-register-all.command.ts
+++ b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
@@ -37,6 +37,7 @@ import { WorkflowCleanWorkflowRunsCronCommand } from 'src/modules/workflow/workf
import { WorkflowHandleStaledRunsCronCommand } from 'src/modules/workflow/workflow-runner/workflow-run-queue/cron/command/workflow-handle-staled-runs.cron.command';
import { WorkflowRunEnqueueCronCommand } from 'src/modules/workflow/workflow-runner/workflow-run-queue/cron/command/workflow-run-enqueue.cron.command';
import { WorkflowCronTriggerCronCommand } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/commands/workflow-cron-trigger.cron.command';
+import { WorkflowStepWaitSweepCronCommand } from 'src/modules/workflow/workflow-wait/crons/commands/workflow-step-wait-sweep.cron.command';
@Command({
name: 'cron:register:all',
@@ -66,6 +67,7 @@ export class CronRegisterAllCommand extends CommandRunner {
private readonly workflowHandleStaledRunsCronCommand: WorkflowHandleStaledRunsCronCommand,
private readonly workflowCleanWorkflowRunsCronCommand: WorkflowCleanWorkflowRunsCronCommand,
private readonly workflowCoreConsistencyCronCommand: WorkflowCoreConsistencyCronCommand,
+ private readonly workflowStepWaitSweepCronCommand: WorkflowStepWaitSweepCronCommand,
private readonly checkCustomDomainValidRecordsCronCommand: CheckCustomDomainValidRecordsCronCommand,
private readonly checkPublicDomainsValidRecordsCronCommand: CheckPublicDomainsValidRecordsCronCommand,
@@ -179,6 +181,10 @@ export class CronRegisterAllCommand extends CommandRunner {
name: 'WorkflowCoreConsistency',
command: this.workflowCoreConsistencyCronCommand,
},
+ {
+ name: 'WorkflowStepWaitSweep',
+ command: this.workflowStepWaitSweepCronCommand,
+ },
{
name: 'CronTrigger',
command: this.cronTriggerCronCommand,
diff --git a/packages/twenty-server/src/database/commands/database-command.module.ts b/packages/twenty-server/src/database/commands/database-command.module.ts
index 5754556c147..b06b6329f93 100644
--- a/packages/twenty-server/src/database/commands/database-command.module.ts
+++ b/packages/twenty-server/src/database/commands/database-command.module.ts
@@ -60,6 +60,7 @@ import { EmailingModule } from 'src/modules/emailing/emailing.module';
import { MessagingImportManagerModule } from 'src/modules/messaging/message-import-manager/messaging-import-manager.module';
import { WorkflowRunQueueModule } from 'src/modules/workflow/workflow-runner/workflow-run-queue/workflow-run-queue.module';
import { AutomatedTriggerModule } from 'src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.module';
+import { WorkflowWaitModule } from 'src/modules/workflow/workflow-wait/workflow-wait.module';
import { WorkflowCoreConsistencyModule } from 'src/modules/workflow/workflow-core-consistency/workflow-core-consistency.module';
@Module({
@@ -73,6 +74,7 @@ import { WorkflowCoreConsistencyModule } from 'src/modules/workflow/workflow-cor
WebhookSubscriptionModule,
EmailingModule,
AutomatedTriggerModule,
+ WorkflowWaitModule,
WorkflowCoreConsistencyModule,
FileModule,
WorkspaceModule,
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791148642493-create-workflow-step-wait-table.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791148642493-create-workflow-step-wait-table.ts
new file mode 100644
index 00000000000..0ddddb43152
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791148642493-create-workflow-step-wait-table.ts
@@ -0,0 +1,21 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.46.0', 1791148642493)
+export class CreateWorkflowStepWaitTableFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('CREATE TABLE "core"."workflowStepWait" ("workspaceId" uuid NOT NULL, "id" uuid NOT NULL DEFAULT uuid_generate_v4(), "workflowRunId" uuid NOT NULL, "stepId" character varying NOT NULL, "wait" jsonb NOT NULL, "eventName" character varying, "resumeAt" TIMESTAMP WITH TIME ZONE, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "UQ_WORKFLOW_STEP_WAIT_RUN_STEP" UNIQUE ("workflowRunId", "stepId"), CONSTRAINT "PK_f29518230d0ab83dbe09d23b462" PRIMARY KEY ("id"))');
+ await queryRunner.query('CREATE INDEX "IDX_WORKFLOW_STEP_WAIT_RESUME_AT" ON "core"."workflowStepWait" ("resumeAt") ');
+ await queryRunner.query('CREATE INDEX "IDX_WORKFLOW_STEP_WAIT_WORKSPACE_EVENT_NAME" ON "core"."workflowStepWait" ("workspaceId", "eventName") ');
+ await queryRunner.query('ALTER TABLE "core"."workflowStepWait" ADD CONSTRAINT "FK_d67ed7b2a1b9aa3ac664ac142c8" FOREIGN KEY ("workspaceId") REFERENCES "core"."workspace"("id") ON DELETE CASCADE ON UPDATE NO ACTION');
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('ALTER TABLE "core"."workflowStepWait" DROP CONSTRAINT "FK_d67ed7b2a1b9aa3ac664ac142c8"');
+ await queryRunner.query('DROP INDEX "core"."IDX_WORKFLOW_STEP_WAIT_WORKSPACE_EVENT_NAME"');
+ await queryRunner.query('DROP INDEX "core"."IDX_WORKFLOW_STEP_WAIT_RESUME_AT"');
+ await queryRunner.query('DROP TABLE "core"."workflowStepWait"');
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/create-workflow-step-wait-table-upgrade-command-name.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/create-workflow-step-wait-table-upgrade-command-name.constant.ts
new file mode 100644
index 00000000000..b533b13256a
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/create-workflow-step-wait-table-upgrade-command-name.constant.ts
@@ -0,0 +1,4 @@
+// Referenced by @WasIntroducedInUpgrade on WorkflowStepWaitEntity so upgrade
+// steps running below 2.46.0 don't query the table before this command creates it.
+export const CREATE_WORKFLOW_STEP_WAIT_TABLE_UPGRADE_COMMAND_NAME =
+ '2.46.0_CreateWorkflowStepWaitTableFastInstanceCommand_1791148642493';
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 1f9f53c2877..0f5ff82f0a9 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -220,6 +220,7 @@ import { AddChatWidgetTypeFastInstanceCommand } from 'src/database/commands/upgr
import { DropLegacyCampaignSendingCoreTablesFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-45/2-45-instance-command-fast-1790842027068-drop-legacy-campaign-sending-core-tables';
import { AddSharingReachToObjectMetadataFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-45/2-45-instance-command-fast-1790876699146-add-sharing-reach-to-object-metadata';
import { AddIsSystemToAgentAndWorkflowFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791130291063-add-is-system-to-agent-and-workflow';
+import { CreateWorkflowStepWaitTableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791148642493-create-workflow-step-wait-table';
import { DropCoreAgentHistoryTablesFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-47/2-47-instance-command-fast-1791094130961-drop-core-agent-history-tables';
export const INSTANCE_COMMANDS = [
@@ -443,5 +444,6 @@ export const INSTANCE_COMMANDS = [
AddApplicationWorkflowSideEffectsFastInstanceCommand,
AddSharingReachToObjectMetadataFastInstanceCommand,
AddIsSystemToAgentAndWorkflowFastInstanceCommand,
+ CreateWorkflowStepWaitTableFastInstanceCommand,
DropCoreAgentHistoryTablesFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
index 53d9531d158..17caf080790 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
@@ -112,6 +112,11 @@ const inputs = {
},
ITERATOR: { items: '{{trigger.items}}', initialLoopStepIds: [FIELD_ID] },
DELAY: { delayType: 'DURATION', duration: { seconds: 1 } },
+ WAIT_FOR_EVENT: {
+ eventName: 'company.updated',
+ recordId: '{{trigger.recordId}}',
+ timeout: { days: 1 },
+ },
EMPTY: {},
} satisfies Record<WorkflowStepManifest['type'], unknown>;
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow-step-wait.entity.ts b/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow-step-wait.entity.ts
new file mode 100644
index 00000000000..606f89ce1ec
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow-step-wait.entity.ts
@@ -0,0 +1,50 @@
+import {
+ Column,
+ CreateDateColumn,
+ Entity,
+ Index,
+ PrimaryGeneratedColumn,
+ Unique,
+} from 'typeorm';
+
+import { type WorkflowStepWait } from 'twenty-shared/workflow';
+
+import { CREATE_WORKFLOW_STEP_WAIT_TABLE_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-46/create-workflow-step-wait-table-upgrade-command-name.constant';
+import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
+import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity.type';
+
+// Waits a step resolves on its own, time or event, so they survive a lost queue job or a restart.
+// Deleting the row is how a resolution claims the step, so a wait resolves once.
+@Entity({ name: 'workflowStepWait', schema: 'core' })
+@WasIntroducedInUpgrade({
+ upgradeCommandName: CREATE_WORKFLOW_STEP_WAIT_TABLE_UPGRADE_COMMAND_NAME,
+})
+@Unique('UQ_WORKFLOW_STEP_WAIT_RUN_STEP', ['workflowRunId', 'stepId'])
+@Index('IDX_WORKFLOW_STEP_WAIT_WORKSPACE_EVENT_NAME', [
+ 'workspaceId',
+ 'eventName',
+])
+@Index('IDX_WORKFLOW_STEP_WAIT_RESUME_AT', ['resumeAt'])
+export class WorkflowStepWaitEntity extends WorkspaceRelatedEntity {
+ @PrimaryGeneratedColumn('uuid')
+ id: string;
+
+ @Column({ type: 'uuid' })
+ workflowRunId: string;
+
+ @Column({ type: 'varchar' })
+ stepId: string;
+
+ @Column({ type: 'jsonb' })
+ wait: Exclude<WorkflowStepWait, { type: 'ANSWER' }>;
+
+ @Column({ type: 'varchar', nullable: true })
+ eventName: string | null;
+
+ // When a time wait elapses or an event wait expires
+ @Column({ type: 'timestamptz', nullable: true })
+ resumeAt: Date | null;
+
+ @CreateDateColumn({ type: 'timestamptz' })
+ createdAt: Date;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts
index d4cc3ede1a2..6de6caa64e1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts
@@ -46,6 +46,15 @@ describe('endsOnPausingToolCall', () => {
).toBe(true);
});
+ it('pauses on an offered pausing tool resolved by something other than an answer', () => {
+ expect(
+ endsOnPausingToolCall({
+ steps: [stepWithResults(awaiting('wait_for_event'))],
+ offeredToolNames: ['wait_for_event'],
+ }),
+ ).toBe(true);
+ });
+
it('does not pause on a pausing call refused when it was made', () => {
expect(
endsOnPausingToolCall({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util.ts
index e582154c869..f08e1a3caa4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util.ts
@@ -1,9 +1,11 @@
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 { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util';
// not the SDK's hasToolCall, whose stop condition may be async: this is also read synchronously after the run
// a pausing call refused or failing when made has no awaiting result, so the model reads its error and goes on
+// an offered pausing tool may be resolved by something other than an answer, such as a workflow wait
export const endsOnPausingToolCall = ({
steps,
offeredToolNames,
@@ -13,8 +15,9 @@ export const endsOnPausingToolCall = ({
}[];
offeredToolNames?: string[];
}): boolean =>
- steps[steps.length - 1]?.toolResults.some(
- ({ toolName, output }) =>
- (offeredToolNames?.includes(toolName) ?? true) &&
- isDefined(findAwaitingPausingTool({ toolName, toolOutput: output })),
+ steps[steps.length - 1]?.toolResults.some(({ toolName, output }) =>
+ isDefined(offeredToolNames)
+ ? offeredToolNames.includes(toolName) &&
+ isAwaitingPausingToolOutput(output)
+ : isDefined(findAwaitingPausingTool({ toolName, toolOutput: output })),
) ?? false;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.workspace-service.ts
index da742c65ab5..a4059b27700 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.workspace-service.ts
@@ -1,4 +1,5 @@
import { computeAiAgentOutputSchema } from 'src/modules/workflow/workflow-builder/workflow-schema/utils/compute-ai-agent-output-schema.util';
+import { WAIT_FOR_EVENT_NAME_PATTERN } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/constants/wait-for-event-name-pattern.constant';
import { Injectable, Logger } from '@nestjs/common';
import { isString } from '@sniptt/guards';
@@ -120,6 +121,11 @@ export class WorkflowSchemaWorkspaceService {
formFieldMetadataItems: step.settings.input,
workspaceId,
});
+ case WorkflowActionType.WAIT_FOR_EVENT:
+ return this.computeWaitForEventOutputSchema({
+ eventName: step.settings.input?.eventName,
+ workspaceId,
+ });
case WorkflowActionType.ITERATOR: {
const items = step.settings.input.items;
@@ -384,6 +390,82 @@ export class WorkflowSchemaWorkspaceService {
return generateFakeObjectRecord({ objectMetadataInfo });
}
+ private async computeWaitForEventOutputSchema({
+ eventName,
+ workspaceId,
+ }: {
+ eventName: string | undefined;
+ workspaceId: string;
+ }): Promise<OutputSchema> {
+ // a step being configured has no output to describe yet, like on the front
+ if (!isDefined(eventName) || !WAIT_FOR_EVENT_NAME_PATTERN.test(eventName)) {
+ return {};
+ }
+
+ const [objectType, action] = eventName.split('.');
+
+ const objectMetadataInfo =
+ await this.workflowCommonWorkspaceService.getObjectMetadataInfo(
+ objectType,
+ workspaceId,
+ );
+
+ const recordLabel =
+ objectMetadataInfo.flatObjectMetadata.labelSingular ?? 'Record';
+
+ const record: Node = {
+ isLeaf: false,
+ label: recordLabel,
+ icon: 'IconAlpha',
+ type: 'object',
+ value: generateFakeObjectRecord({ objectMetadataInfo }),
+ };
+
+ const recordId: Leaf = {
+ isLeaf: true,
+ label: 'Record ID',
+ icon: 'IconId',
+ type: 'string',
+ value: generateFakeValue('string'),
+ };
+
+ const hasTimedOut: Leaf = {
+ isLeaf: true,
+ label: 'Has Timed Out',
+ icon: 'IconClockX',
+ type: 'boolean',
+ value: false,
+ };
+
+ if (action !== 'updated' && action !== 'upserted') {
+ return { record, recordId, hasTimedOut } satisfies OutputSchema;
+ }
+
+ const before: Node = {
+ isLeaf: false,
+ label: `${recordLabel} Before Update`,
+ icon: 'IconHistory',
+ type: 'object',
+ value: generateFakeObjectRecord({ objectMetadataInfo }),
+ };
+
+ const updatedFields: Leaf = {
+ isLeaf: true,
+ label: 'Updated Fields',
+ icon: 'IconListDetails',
+ type: 'array',
+ value: ['name'],
+ };
+
+ return {
+ record,
+ recordId,
+ before,
+ updatedFields,
+ hasTimedOut,
+ } satisfies OutputSchema;
+ }
+
private computeSendEmailActionOutputSchema(): OutputSchema {
return {
success: { isLeaf: true, type: 'boolean', value: true },
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
index ac86c8a7d55..1ce92cbbe1b 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
@@ -713,6 +713,26 @@ export class WorkflowVersionStepOperationsWorkspaceService {
},
};
}
+ case WorkflowActionType.WAIT_FOR_EVENT: {
+ const activeObjectMetadataItem =
+ await this.findFirstActiveObjectMetadata(workspaceId);
+
+ return {
+ builtStep: {
+ ...baseStep,
+ name: 'Wait for Event',
+ type: WorkflowActionType.WAIT_FOR_EVENT,
+ settings: {
+ ...BASE_STEP_DEFINITION,
+ input: {
+ eventName: `${activeObjectMetadataItem?.nameSingular ?? 'company'}.updated`,
+ recordId: null,
+ timeout: null,
+ },
+ },
+ },
+ };
+ }
case WorkflowActionType.EMPTY: {
return {
builtStep: {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/factories/workflow-action.factory.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/factories/workflow-action.factory.ts
index 152a44f5524..5cba2b98485 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/factories/workflow-action.factory.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/factories/workflow-action.factory.ts
@@ -26,6 +26,7 @@ import { DeleteRecordWorkflowAction } from 'src/modules/workflow/workflow-execut
import { FindRecordsWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/record-crud/find-records.workflow-action';
import { PickRecordWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/record-crud/pick-record.workflow-action';
import { UpdateRecordWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/record-crud/update-record.workflow-action';
+import { WaitForEventWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/wait-for-event.workflow-action';
import { UpsertRecordWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/record-crud/upsert-record.workflow-action';
import { WorkflowActionType } from 'twenty-shared/workflow';
@@ -53,6 +54,7 @@ export class WorkflowActionFactory {
private readonly classifyWorkflowAction: ClassifyWorkflowAction,
private readonly emptyWorkflowAction: EmptyWorkflowAction,
private readonly delayWorkflowAction: DelayWorkflowAction,
+ private readonly waitForEventWorkflowAction: WaitForEventWorkflowAction,
) {}
get(stepType: WorkflowActionType): WorkflowAction {
@@ -99,6 +101,8 @@ export class WorkflowActionFactory {
return this.emptyWorkflowAction;
case WorkflowActionType.DELAY:
return this.delayWorkflowAction;
+ case WorkflowActionType.WAIT_FOR_EVENT:
+ return this.waitForEventWorkflowAction;
default:
throw new WorkflowStepExecutorException(
`Workflow step executor not found for step type '${stepType}'`,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/interfaces/workflow-action.interface.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/interfaces/workflow-action.interface.ts
index f5aa422c817..92becd8fefc 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/interfaces/workflow-action.interface.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/interfaces/workflow-action.interface.ts
@@ -1,8 +1,15 @@
import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';
+import { type WorkflowWaitResolution } from 'src/modules/workflow/workflow-wait/types/workflow-wait-resolution.type';
+import { type WorkflowWaitResolutionInput } from 'src/modules/workflow/workflow-wait/types/workflow-wait-resolution-input.type';
export interface WorkflowAction {
execute(
workflowActionInput: WorkflowActionInput,
): Promise<WorkflowActionOutput>;
+
+ // Without it, a resolved time or event wait completes the step with the outcome as its result
+ resolveWait?(
+ workflowWaitResolutionInput: WorkflowWaitResolutionInput,
+ ): Promise<WorkflowWaitResolution>;
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-output.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-output.type.ts
index 7ac2b760639..8b8c9c7c433 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-output.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-output.type.ts
@@ -1,8 +1,11 @@
+import { type WorkflowStepWait } from 'twenty-shared/workflow';
+
export type WorkflowActionOutput = {
result?: object;
error?: string;
isUserError?: boolean;
- pendingEvent?: boolean;
+ // The step pauses as PENDING until what it waits on resolves it
+ wait?: WorkflowStepWait;
shouldEndWorkflowRun?: boolean;
shouldRemainRunning?: boolean;
shouldSkipStepExecution?: boolean;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
index e0a4d64a888..9eebff6f33b 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
@@ -30,6 +30,12 @@ import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor
import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';
import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';
import { APPLICATION_BOUND_AGENT_EXCLUDED_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant';
+import { WORKFLOW_AGENT_WAIT_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-prompt.constant';
+import { createWorkflowAgentWaitTools } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-workflow-agent-wait-tools.util';
+import { buildWaitOutcomeToolOutput } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-wait-outcome-tool-output.util';
+import { findAgentStepWait } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/find-agent-step-wait.util';
+import { type WorkflowWaitResolution } from 'src/modules/workflow/workflow-wait/types/workflow-wait-resolution.type';
+import { type WorkflowWaitResolutionInput } from 'src/modules/workflow/workflow-wait/types/workflow-wait-resolution-input.type';
import { WORKFLOW_AGENT_HUMAN_INPUT_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant';
import {
type RecordedConversation,
@@ -165,16 +171,19 @@ export class AiAgentWorkflowAction implements WorkflowAction {
}
: { messages: [{ role: 'user', content: resolvedPrompt }] }),
baseSystemPrompt: canAskForHumanInput
- ? `${WORKFLOW_BASE_SYSTEM_PROMPT}\n\n${WORKFLOW_AGENT_HUMAN_INPUT_PROMPT}\n\n${trimmedHumanInputInstructions}`
- : WORKFLOW_BASE_SYSTEM_PROMPT,
- pausingTools: canAskForHumanInput
- ? {
- [ASK_QUESTION_TOOL_NAME]: createAskQuestionTool({
- isWorkspaceSetupThread: false,
- }),
- [REQUEST_FORM_TOOL_NAME]: createRequestFormTool(),
- }
- : {},
+ ? `${WORKFLOW_BASE_SYSTEM_PROMPT}\n\n${WORKFLOW_AGENT_WAIT_PROMPT}\n\n${WORKFLOW_AGENT_HUMAN_INPUT_PROMPT}\n\n${trimmedHumanInputInstructions}`
+ : `${WORKFLOW_BASE_SYSTEM_PROMPT}\n\n${WORKFLOW_AGENT_WAIT_PROMPT}`,
+ pausingTools: {
+ ...createWorkflowAgentWaitTools(),
+ ...(canAskForHumanInput
+ ? {
+ [ASK_QUESTION_TOOL_NAME]: createAskQuestionTool({
+ isWorkspaceSetupThread: false,
+ }),
+ [REQUEST_FORM_TOOL_NAME]: createRequestFormTool(),
+ }
+ : {}),
+ },
canProposeToolCalls: canAskForHumanInput,
actorContext: executionContext.isActingOnBehalfOfUser
? executionContext.initiator
@@ -217,14 +226,22 @@ export class AiAgentWorkflowAction implements WorkflowAction {
}
if (executionResult.isPaused) {
- // Without the conversation nobody could answer, so the run would wait forever
- if (recordedConversation?.isAwaitingAnswer !== true) {
- return {
- error: 'Agent asked a question that could not be recorded.',
- };
+ if (recordedConversation?.isAwaitingAnswer) {
+ return { wait: { type: 'ANSWER' } };
}
- return { pendingEvent: true };
+ const wait = findAgentStepWait(executionResult.steps);
+
+ // Resuming continues the conversation, so without it the run would wait forever
+ if (isDefined(wait) && isDefined(recordedConversation)) {
+ return { wait };
+ }
+
+ return {
+ error: isDefined(wait)
+ ? 'Agent paused to wait but its conversation could not be recorded.'
+ : 'Agent asked a question that could not be recorded.',
+ };
}
return {
@@ -232,6 +249,29 @@ export class AiAgentWorkflowAction implements WorkflowAction {
};
}
+ async resolveWait({
+ stepInfo,
+ outcome,
+ runInfo,
+ }: WorkflowWaitResolutionInput): Promise<WorkflowWaitResolution> {
+ const threadId = stepInfo.threadId;
+
+ if (!isDefined(threadId)) {
+ throw new WorkflowStepExecutorException(
+ 'A waiting agent step has no conversation to continue',
+ WorkflowStepExecutorExceptionCode.INTERNAL_ERROR,
+ );
+ }
+
+ await this.workflowAgentConversationService.recordWaitOutcome({
+ workspaceId: runInfo.workspaceId,
+ threadId,
+ toolOutput: buildWaitOutcomeToolOutput(outcome),
+ });
+
+ return { resumedThreadId: threadId };
+ }
+
private async persistStepLog({
workflowRunId,
workspaceId,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-prompt.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-prompt.constant.ts
new file mode 100644
index 00000000000..357212fac02
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-prompt.constant.ts
@@ -0,0 +1 @@
+export const WORKFLOW_AGENT_WAIT_PROMPT = `When the task depends on something that has not happened yet, you can pause the workflow instead of finishing early: call wait_for_event to resume when a record is created, updated or deleted, or wait_for_duration to resume after some time. Call a wait tool alone and last; you continue in this conversation with its outcome. Only wait when the task requires it.`;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant.ts
new file mode 100644
index 00000000000..e7c5f5de9ca
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant.ts
@@ -0,0 +1,8 @@
+export const WAIT_FOR_EVENT_TOOL_NAME = 'wait_for_event';
+
+export const WAIT_FOR_DURATION_TOOL_NAME = 'wait_for_duration';
+
+export const WORKFLOW_AGENT_WAIT_TOOL_NAMES: string[] = [
+ WAIT_FOR_EVENT_TOOL_NAME,
+ WAIT_FOR_DURATION_TOOL_NAME,
+];
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
index bc0f8b1dfb7..33e8fde18ad 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
@@ -8,6 +8,10 @@ import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-histor
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 { type RecordableAgentExecution } from 'src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type';
+import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
+import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
+import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util';
+import { WORKFLOW_AGENT_WAIT_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
import { findLastMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util';
import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
@@ -17,6 +21,8 @@ import {
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
+const RECENT_MESSAGES_TO_SEARCH_FOR_WAIT = 50;
+
export type RecordedConversation = {
threadId: string;
isAwaitingAnswer: boolean;
@@ -33,6 +39,10 @@ export class WorkflowAgentConversationWorkspaceService {
constructor(
@InjectAgentHistoryRepository('agentChatThread')
private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
+ @InjectAgentHistoryRepository('agentMessage')
+ private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,
+ @InjectAgentHistoryRepository('agentMessagePart')
+ private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
private readonly conversationWriterService: AgentConversationWriterService,
private readonly threadService: AgentChatThreadService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
@@ -88,6 +98,47 @@ export class WorkflowAgentConversationWorkspaceService {
return { threadId, isAwaitingAnswer };
}
+ // The wait call stays pending in the conversation until its wait resolves, then carries the outcome
+ async recordWaitOutcome({
+ workspaceId,
+ threadId,
+ toolOutput,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ toolOutput: Record<string, unknown>;
+ }): Promise<void> {
+ // messages can follow the call while it waits, so the latest one may not carry it
+ const recentMessages = await this.messageRepository.find(workspaceId, {
+ where: { threadId },
+ order: { createdAt: 'DESC' },
+ take: RECENT_MESSAGES_TO_SEARCH_FOR_WAIT,
+ relations: ['parts'],
+ });
+
+ const waitPart = recentMessages
+ .flatMap((message) => message.parts ?? [])
+ .find(
+ (part) =>
+ isDefined(part.toolName) &&
+ WORKFLOW_AGENT_WAIT_TOOL_NAMES.includes(part.toolName) &&
+ isAwaitingPausingToolOutput(part.toolOutput),
+ );
+
+ if (!isDefined(waitPart)) {
+ throw new AiException(
+ 'The waiting call could not be found in the conversation',
+ AiExceptionCode.TOOL_CALL_NOT_FOUND,
+ );
+ }
+
+ await this.messagePartRepository.update(
+ workspaceId,
+ { id: waitPart.id },
+ { toolOutput },
+ );
+ }
+
// The answer is already the last message, so only the agent's reply is added
async recordContinuation({
workspaceId,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/__tests__/create-workflow-agent-wait-tools.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/__tests__/create-workflow-agent-wait-tools.util.spec.ts
new file mode 100644
index 00000000000..7fb2bfbe90c
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/__tests__/create-workflow-agent-wait-tools.util.spec.ts
@@ -0,0 +1,60 @@
+import { createWorkflowAgentWaitTools } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-workflow-agent-wait-tools.util';
+
+describe('createWorkflowAgentWaitTools', () => {
+ it('refuses a second wait of the same execution so only one is pending', async () => {
+ const tools = createWorkflowAgentWaitTools();
+
+ await expect(
+ tools.wait_for_event.execute({
+ objectName: 'company',
+ action: 'updated',
+ }),
+ ).resolves.toMatchObject({ result: { status: 'pending' } });
+
+ await expect(
+ tools.wait_for_duration.execute({ durationInMinutes: 60 }),
+ ).resolves.toMatchObject({ success: false });
+ });
+
+ it('only keeps a field filter on updates, where events report changed fields', async () => {
+ const createdEventWait =
+ await createWorkflowAgentWaitTools().wait_for_event.execute({
+ objectName: 'company',
+ action: 'created',
+ updatedFields: ['name'],
+ });
+ const updatedEventWait =
+ await createWorkflowAgentWaitTools().wait_for_event.execute({
+ objectName: 'company',
+ action: 'updated',
+ updatedFields: ['name'],
+ });
+
+ expect(createdEventWait).toMatchObject({
+ result: { wait: { type: 'EVENT', eventName: 'company.created' } },
+ });
+ expect(createdEventWait).not.toHaveProperty('result.wait.updatedFields');
+ expect(updatedEventWait).toMatchObject({
+ result: {
+ wait: {
+ type: 'EVENT',
+ eventName: 'company.updated',
+ updatedFields: ['name'],
+ },
+ },
+ });
+ });
+
+ it('gives each execution its own wait', async () => {
+ const firstExecutionTools = createWorkflowAgentWaitTools();
+ const secondExecutionTools = createWorkflowAgentWaitTools();
+
+ await firstExecutionTools.wait_for_duration.execute({
+ durationInMinutes: 5,
+ });
+
+ await expect(
+ secondExecutionTools.wait_for_duration.execute({ durationInMinutes: 5 }),
+ ).resolves.toMatchObject({ result: { status: 'pending' } });
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/build-second-wait-refusal-output.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/build-second-wait-refusal-output.util.ts
new file mode 100644
index 00000000000..f7587ec81b0
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/build-second-wait-refusal-output.util.ts
@@ -0,0 +1,6 @@
+// not pending, so the execution does not pause on it and the model reads why
+export const buildSecondWaitRefusalOutput = () => ({
+ success: false,
+ error:
+ 'Only one wait can be active at a time. Call a single wait tool and continue once it resolves.',
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/build-wait-pending-output.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/build-wait-pending-output.util.ts
new file mode 100644
index 00000000000..c1c21dec422
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/build-wait-pending-output.util.ts
@@ -0,0 +1,19 @@
+import { type WorkflowStepWait } from 'twenty-shared/workflow';
+
+export type WorkflowAgentWaitPendingOutput = {
+ success: true;
+ message: string;
+ result: { status: 'pending'; wait: WorkflowStepWait };
+};
+
+export const buildWaitPendingOutput = ({
+ message,
+ wait,
+}: {
+ message: string;
+ wait: WorkflowStepWait;
+}): WorkflowAgentWaitPendingOutput => ({
+ success: true,
+ message,
+ result: { status: 'pending', wait },
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-wait-for-duration.tool.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-wait-for-duration.tool.ts
new file mode 100644
index 00000000000..51a50d51346
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-wait-for-duration.tool.ts
@@ -0,0 +1,40 @@
+import { z } from 'zod';
+
+import { buildSecondWaitRefusalOutput } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/build-second-wait-refusal-output.util';
+import { buildWaitPendingOutput } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/build-wait-pending-output.util';
+import { type WorkflowAgentWaitSlot } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/workflow-agent-wait-slot.type';
+
+const MAX_DURATION_IN_MINUTES = 60 * 24 * 365;
+
+const waitForDurationInputSchema = z.object({
+ durationInMinutes: z
+ .number()
+ .int()
+ .positive()
+ .max(MAX_DURATION_IN_MINUTES)
+ .describe('How long to wait, in minutes (e.g. 1440 for one day).'),
+});
+
+export const createWaitForDurationTool = (waitSlot: WorkflowAgentWaitSlot) => ({
+ description:
+ 'Pause the workflow for a while, for example before following up. You continue once the time has passed.',
+ inputSchema: waitForDurationInputSchema,
+ execute: async ({
+ durationInMinutes,
+ }: z.infer<typeof waitForDurationInputSchema>) => {
+ if (waitSlot.isTaken) {
+ return buildSecondWaitRefusalOutput();
+ }
+
+ waitSlot.isTaken = true;
+
+ const resumeAt = new Date(
+ Date.now() + durationInMinutes * 60 * 1000,
+ ).toISOString();
+
+ return buildWaitPendingOutput({
+ message: `Waiting until ${resumeAt}.`,
+ wait: { type: 'TIME', resumeAt },
+ });
+ },
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-wait-for-event.tool.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-wait-for-event.tool.ts
new file mode 100644
index 00000000000..5d3d9011819
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-wait-for-event.tool.ts
@@ -0,0 +1,79 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+import { buildSecondWaitRefusalOutput } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/build-second-wait-refusal-output.util';
+import { buildWaitPendingOutput } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/build-wait-pending-output.util';
+import { type WorkflowAgentWaitSlot } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/workflow-agent-wait-slot.type';
+
+const MAX_TIMEOUT_IN_MINUTES = 60 * 24 * 365;
+
+const waitForEventInputSchema = z.object({
+ objectName: z
+ .string()
+ .regex(/^[a-z][a-zA-Z0-9]*$/)
+ .describe('Singular name of the object to watch, e.g. "company".'),
+ action: z
+ .enum(['created', 'updated', 'deleted'])
+ .describe('What must happen to a record of that object.'),
+ recordId: z
+ .uuid()
+ .optional()
+ .describe('Only resume for this record. Omit to resume on any record.'),
+ updatedFields: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'Only for the updated action: resume only when one of these fields changed.',
+ ),
+ timeoutInMinutes: z
+ .number()
+ .int()
+ .positive()
+ .max(MAX_TIMEOUT_IN_MINUTES)
+ .optional()
+ .describe(
+ 'Stop waiting after this many minutes. Omit to wait without limit.',
+ ),
+});
+
+export const createWaitForEventTool = (waitSlot: WorkflowAgentWaitSlot) => ({
+ description:
+ 'Pause the workflow until a record is created, updated or deleted. You then continue with the ' +
+ 'id of the record that changed, which you can read with your tools, or learn that the wait timed out.',
+ inputSchema: waitForEventInputSchema,
+ execute: async ({
+ objectName,
+ action,
+ recordId,
+ updatedFields,
+ timeoutInMinutes,
+ }: z.infer<typeof waitForEventInputSchema>) => {
+ if (waitSlot.isTaken) {
+ return buildSecondWaitRefusalOutput();
+ }
+
+ waitSlot.isTaken = true;
+
+ const eventName = `${objectName}.${action}`;
+
+ return buildWaitPendingOutput({
+ message: `Waiting for ${eventName}; the workflow resumes when it happens.`,
+ wait: {
+ type: 'EVENT',
+ eventName,
+ ...(isNonEmptyString(recordId) ? { recordId } : {}),
+ ...(action === 'updated' && isNonEmptyArray(updatedFields)
+ ? { updatedFields }
+ : {}),
+ ...(isDefined(timeoutInMinutes)
+ ? {
+ expiresAt: new Date(
+ Date.now() + timeoutInMinutes * 60 * 1000,
+ ).toISOString(),
+ }
+ : {}),
+ },
+ });
+ },
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-workflow-agent-wait-tools.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-workflow-agent-wait-tools.util.ts
new file mode 100644
index 00000000000..e6c0e76a9b2
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-workflow-agent-wait-tools.util.ts
@@ -0,0 +1,19 @@
+import { type ToolSet } from 'ai';
+
+import {
+ WAIT_FOR_DURATION_TOOL_NAME,
+ WAIT_FOR_EVENT_TOOL_NAME,
+} from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant';
+import { createWaitForDurationTool } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-wait-for-duration.tool';
+import { createWaitForEventTool } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-wait-for-event.tool';
+import { type WorkflowAgentWaitSlot } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/workflow-agent-wait-slot.type';
+
+// a step resumes on one wait, so a second wait call of the same execution is refused instead of left pending
+export const createWorkflowAgentWaitTools = () => {
+ const waitSlot: WorkflowAgentWaitSlot = { isTaken: false };
+
+ return {
+ [WAIT_FOR_EVENT_TOOL_NAME]: createWaitForEventTool(waitSlot),
+ [WAIT_FOR_DURATION_TOOL_NAME]: createWaitForDurationTool(waitSlot),
+ } satisfies ToolSet;
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/workflow-agent-wait-slot.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/workflow-agent-wait-slot.type.ts
new file mode 100644
index 00000000000..0303558b8ec
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/workflow-agent-wait-slot.type.ts
@@ -0,0 +1 @@
+export type WorkflowAgentWaitSlot = { isTaken: boolean };
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/find-agent-step-wait.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/find-agent-step-wait.util.spec.ts
new file mode 100644
index 00000000000..e7c9c110f92
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/find-agent-step-wait.util.spec.ts
@@ -0,0 +1,54 @@
+import { findAgentStepWait } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/find-agent-step-wait.util';
+
+const WAIT = { type: 'EVENT', eventName: 'company.updated' };
+
+const stepWithResults = (
+ ...toolResults: { toolName: string; output: unknown }[]
+) => ({ toolResults });
+
+describe('findAgentStepWait', () => {
+ it('finds the wait an execution ended on', () => {
+ expect(
+ findAgentStepWait([
+ stepWithResults({
+ toolName: 'wait_for_event',
+ output: { success: true, result: { status: 'pending', wait: WAIT } },
+ }),
+ ]),
+ ).toEqual(WAIT);
+ });
+
+ it('ignores a wait call made in an earlier step', () => {
+ expect(
+ findAgentStepWait([
+ stepWithResults({
+ toolName: 'wait_for_event',
+ output: { success: true, result: { status: 'pending', wait: WAIT } },
+ }),
+ stepWithResults({ toolName: 'search', output: {} }),
+ ]),
+ ).toBeUndefined();
+ });
+
+ it('ignores pending calls of tools that are not waits', () => {
+ expect(
+ findAgentStepWait([
+ stepWithResults({
+ toolName: 'ask_question',
+ output: { success: true, result: { status: 'pending', wait: WAIT } },
+ }),
+ ]),
+ ).toBeUndefined();
+ });
+
+ it('ignores a wait call whose wait cannot be read', () => {
+ expect(
+ findAgentStepWait([
+ stepWithResults({
+ toolName: 'wait_for_duration',
+ output: { success: true, result: { status: 'pending' } },
+ }),
+ ]),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-wait-outcome-tool-output.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-wait-outcome-tool-output.util.ts
new file mode 100644
index 00000000000..4732ad40f33
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-wait-outcome-tool-output.util.ts
@@ -0,0 +1,34 @@
+import { type WorkflowWaitOutcome } from 'src/modules/workflow/workflow-wait/types/workflow-wait-outcome.type';
+
+export const buildWaitOutcomeToolOutput = (
+ outcome: WorkflowWaitOutcome,
+): Record<string, unknown> => {
+ switch (outcome.type) {
+ case 'TIME_ELAPSED':
+ return {
+ success: true,
+ message: 'The wait is over.',
+ result: { status: 'completed' },
+ };
+ // the agent reads the record with its own tools, so its permissions decide what it sees
+ case 'EVENT_RECEIVED': {
+ const { eventName, recordId, updatedFields } = outcome.event;
+
+ return {
+ success: true,
+ message: `${eventName} happened on record ${recordId}.`,
+ result: {
+ status: 'completed',
+ event: { eventName, recordId, updatedFields },
+ },
+ };
+ }
+ case 'EXPIRED':
+ return {
+ success: true,
+ message:
+ 'Stopped waiting: the event did not happen before the timeout.',
+ result: { status: 'expired' },
+ };
+ }
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/find-agent-step-wait.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/find-agent-step-wait.util.ts
new file mode 100644
index 00000000000..2d2adc1a162
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/find-agent-step-wait.util.ts
@@ -0,0 +1,34 @@
+import { isPlainObject } from 'twenty-shared/utils';
+import {
+ type WorkflowStepWait,
+ workflowStepWaitSchema,
+} from 'twenty-shared/workflow';
+
+import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util';
+import { WORKFLOW_AGENT_WAIT_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant';
+
+// The wait an execution paused on, when it ended on a wait tool call
+export const findAgentStepWait = (
+ steps: { toolResults: { toolName: string; output: unknown }[] }[],
+): WorkflowStepWait | undefined => {
+ const lastStepToolResults = steps[steps.length - 1]?.toolResults ?? [];
+
+ for (const { toolName, output } of lastStepToolResults) {
+ if (
+ !WORKFLOW_AGENT_WAIT_TOOL_NAMES.includes(toolName) ||
+ !isAwaitingPausingToolOutput(output) ||
+ !isPlainObject(output) ||
+ !isPlainObject(output.result)
+ ) {
+ continue;
+ }
+
+ const parsedWait = workflowStepWaitSchema.safeParse(output.result.wait);
+
+ if (parsedWait.success) {
+ return parsedWait.data;
+ }
+ }
+
+ return undefined;
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/delay.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/delay.workflow-action.ts
index bbc5a6a54a1..8d7cc01cf54 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/delay.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/delay.workflow-action.ts
@@ -4,9 +4,6 @@ import { resolveInput } from 'twenty-shared/utils';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
-import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
-import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
-import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
@@ -14,23 +11,14 @@ import {
import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';
import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';
-import { RESUME_DELAYED_WORKFLOW_JOB_NAME } from 'src/modules/workflow/workflow-executor/workflow-actions/delay/contants/resume-delayed-workflow-job-name';
import { isWorkflowDelayAction } from 'src/modules/workflow/workflow-executor/workflow-actions/delay/guards/is-workflow-delay-action.guard';
-import { ResumeDelayedWorkflowJobData } from 'src/modules/workflow/workflow-executor/workflow-actions/delay/types/resume-delayed-workflow-job-data.type';
import { WorkflowDelayActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/delay/types/workflow-delay-action-input.type';
-import { buildRunWorkflowJobOptions } from 'src/modules/workflow/workflow-runner/utils/build-run-workflow-job-options.util';
@Injectable()
export class DelayWorkflowAction implements WorkflowAction {
- constructor(
- @InjectMessageQueue(MessageQueue.delayedJobsQueue)
- private readonly messageQueueService: MessageQueueService,
- ) {}
-
async execute({
currentStepId,
steps,
- runInfo,
context,
}: WorkflowActionInput): Promise<WorkflowActionOutput> {
const step = findStepOrThrow({
@@ -98,21 +86,11 @@ export class DelayWorkflowAction implements WorkflowAction {
);
}
- await this.messageQueueService.add<ResumeDelayedWorkflowJobData>(
- RESUME_DELAYED_WORKFLOW_JOB_NAME,
- {
- workspaceId: runInfo.workspaceId,
- workflowRunId: runInfo.workflowRunId,
- stepId: currentStepId,
- },
- {
- ...buildRunWorkflowJobOptions(runInfo.workflowRunId),
- delay: delayInMs,
- },
- );
-
return {
- pendingEvent: true,
+ wait: {
+ type: 'TIME',
+ resumeAt: new Date(Date.now() + delayInMs).toISOString(),
+ },
};
}
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/jobs/resume-delayed-workflow.job.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/jobs/resume-delayed-workflow.job.ts
index d7b8aeed68b..28404cd50c0 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/jobs/resume-delayed-workflow.job.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/delay/jobs/resume-delayed-workflow.job.ts
@@ -23,6 +23,7 @@ import { type RunWorkflowJobData } from 'src/modules/workflow/workflow-runner/ty
import { buildRunWorkflowJobOptions } from 'src/modules/workflow/workflow-runner/utils/build-run-workflow-job-options.util';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
+// Drains delays queued before delays became time waits; new ones resume through ResumeWaitingWorkflowStepJob
@Processor({
queueName: MessageQueue.delayedJobsQueue,
scope: Scope.REQUEST,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts
index 6c1ffb4fbd4..ac7427039f9 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts
@@ -29,6 +29,6 @@ export class FormWorkflowAction implements WorkflowAction {
);
}
- return { pendingEvent: true };
+ return { wait: { type: 'ANSWER' } };
}
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
index ad7ce6a3c52..db662206d55 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
@@ -162,7 +162,7 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {
workspaceId: runInfo.workspaceId,
});
- return { pendingEvent: true };
+ return { wait: { type: 'ANSWER' } };
}
return {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type.ts
index e7c3002ccfd..8a27cc8e975 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type.ts
@@ -3,6 +3,7 @@ import { type WorkflowAiAgentActionSettings } from 'src/modules/workflow/workflo
import { type WorkflowCodeActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/code/types/workflow-code-action-settings.type';
import { type WorkflowCreateCalendarEventActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/create-calendar-event/types/workflow-create-calendar-event-action-settings.type';
import { type WorkflowDelayActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/delay/types/workflow-delay-action-settings.type';
+import { type WorkflowWaitForEventActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-settings.type';
import { type WorkflowFilterActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/filter/types/workflow-filter-action-settings.type';
import { type WorkflowFormActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/form/types/workflow-form-action-settings.type';
import { type WorkflowHttpRequestActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/http-request/types/workflow-http-request-action-settings.type';
@@ -54,4 +55,5 @@ export type WorkflowActionSettings =
| WorkflowHttpRequestActionSettings
| WorkflowAiAgentActionSettings
| WorkflowDelayActionSettings
+ | WorkflowWaitForEventActionSettings
| WorkflowIteratorActionSettings;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type.ts
index 9e26c9722db..2df78c5fd19 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type.ts
@@ -5,6 +5,7 @@ import { type WorkflowClassifyActionSettings } from 'src/modules/workflow/workfl
import { type WorkflowCodeActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/code/types/workflow-code-action-settings.type';
import { type WorkflowCreateCalendarEventActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/create-calendar-event/types/workflow-create-calendar-event-action-settings.type';
import { type WorkflowDelayActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/delay/types/workflow-delay-action-settings.type';
+import { type WorkflowWaitForEventActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-settings.type';
import { type WorkflowFilterActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/filter/types/workflow-filter-action-settings.type';
import { type WorkflowFormActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/form/types/workflow-form-action-settings.type';
import { type WorkflowHttpRequestActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/http-request/types/workflow-http-request-action-settings.type';
@@ -140,6 +141,11 @@ export type WorkflowDelayAction = BaseWorkflowAction & {
settings: WorkflowDelayActionSettings;
};
+export type WorkflowWaitForEventAction = BaseWorkflowAction & {
+ type: WorkflowActionType.WAIT_FOR_EVENT;
+ settings: WorkflowWaitForEventActionSettings;
+};
+
export type WorkflowAction =
| WorkflowCodeAction
| WorkflowLogicFunctionAction
@@ -161,4 +167,5 @@ export type WorkflowAction =
| WorkflowClassifyAction
| WorkflowIteratorAction
| WorkflowEmptyAction
- | WorkflowDelayAction;
+ | WorkflowDelayAction
+ | WorkflowWaitForEventAction;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/__tests__/wait-for-event.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/__tests__/wait-for-event.workflow-action.spec.ts
new file mode 100644
index 00000000000..4188670dba7
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/__tests__/wait-for-event.workflow-action.spec.ts
@@ -0,0 +1,109 @@
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import { WaitForEventWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/wait-for-event.workflow-action';
+
+const NOW = new Date('2026-10-04T10:00:00.000Z');
+
+const executeWithInput = (input: Record<string, unknown>) =>
+ new WaitForEventWorkflowAction().execute({
+ currentStepId: 'step-id',
+ steps: [
+ {
+ id: 'step-id',
+ name: 'Wait for Event',
+ type: WorkflowActionType.WAIT_FOR_EVENT,
+ valid: true,
+ settings: {
+ input,
+ outputSchema: {},
+ errorHandlingOptions: {
+ continueOnFailure: { value: false },
+ retryOnFailure: { value: false },
+ },
+ },
+ },
+ ] as never,
+ context: { trigger: { object: { id: 'company-id' } } },
+ runInfo: { workflowRunId: 'run-id', workspaceId: 'workspace-id' },
+ });
+
+describe('WaitForEventWorkflowAction', () => {
+ beforeEach(() => {
+ jest.useFakeTimers().setSystemTime(NOW);
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('waits on the event for the record its variable resolves to', async () => {
+ await expect(
+ executeWithInput({
+ eventName: 'company.updated',
+ recordId: '{{trigger.object.id}}',
+ updatedFields: ['stage'],
+ }),
+ ).resolves.toEqual({
+ wait: {
+ type: 'EVENT',
+ eventName: 'company.updated',
+ recordId: 'company-id',
+ updatedFields: ['stage'],
+ },
+ });
+ });
+
+ it('expires the wait after its timeout', async () => {
+ await expect(
+ executeWithInput({
+ eventName: 'task.created',
+ timeout: { days: 1, hours: '2', minutes: '' },
+ }),
+ ).resolves.toEqual({
+ wait: {
+ type: 'EVENT',
+ eventName: 'task.created',
+ expiresAt: '2026-10-05T12:00:00.000Z',
+ },
+ });
+ });
+
+ it('refuses to widen the wait when its record resolves to nothing', async () => {
+ await expect(
+ executeWithInput({
+ eventName: 'company.updated',
+ recordId: '{{trigger.missing.id}}',
+ }),
+ ).rejects.toThrow('The record to wait for resolved to no record');
+ });
+
+ it('refuses a timeout it cannot read instead of dropping the deadline', async () => {
+ await expect(
+ executeWithInput({
+ eventName: 'company.updated',
+ timeout: { hours: 'soon' },
+ }),
+ ).rejects.toThrow('Wait timeout must be made of non-negative numbers');
+ });
+
+ it('refuses a timeout too long to schedule', async () => {
+ await expect(
+ executeWithInput({
+ eventName: 'company.updated',
+ timeout: { days: 100000000 },
+ }),
+ ).rejects.toThrow('Wait timeout cannot exceed one year');
+ });
+
+ it('refuses an event on an object name that cannot exist', async () => {
+ await expect(
+ executeWithInput({ eventName: 'my_object.created' }),
+ ).rejects.toThrow('Invalid event to wait for');
+ });
+
+ it('refuses an event it could never match', async () => {
+ await expect(executeWithInput({ eventName: 'company' })).rejects.toThrow(
+ 'Invalid event to wait for',
+ );
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/constants/wait-for-event-name-pattern.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/constants/wait-for-event-name-pattern.constant.ts
new file mode 100644
index 00000000000..241799854c7
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/constants/wait-for-event-name-pattern.constant.ts
@@ -0,0 +1,2 @@
+export const WAIT_FOR_EVENT_NAME_PATTERN =
+ /^[a-z][a-zA-Z0-9]*\.(created|updated|deleted|upserted)$/;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/guards/is-workflow-wait-for-event-action.guard.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/guards/is-workflow-wait-for-event-action.guard.ts
new file mode 100644
index 00000000000..e2dd7fc8ec6
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/guards/is-workflow-wait-for-event-action.guard.ts
@@ -0,0 +1,11 @@
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import {
+ type WorkflowAction,
+ type WorkflowWaitForEventAction,
+} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+export const isWorkflowWaitForEventAction = (
+ action: WorkflowAction,
+): action is WorkflowWaitForEventAction =>
+ action.type === WorkflowActionType.WAIT_FOR_EVENT;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-input.type.ts
new file mode 100644
index 00000000000..325d17900b0
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-input.type.ts
@@ -0,0 +1,10 @@
+export type WorkflowWaitForEventActionInput = {
+ eventName: string;
+ recordId?: string | null;
+ updatedFields?: string[] | null;
+ timeout?: {
+ days?: number | string;
+ hours?: number | string;
+ minutes?: number | string;
+ } | null;
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-settings.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-settings.type.ts
new file mode 100644
index 00000000000..5b71f733cee
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-settings.type.ts
@@ -0,0 +1,6 @@
+import { type WorkflowWaitForEventActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-input.type';
+import { type BaseWorkflowActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type';
+
+export type WorkflowWaitForEventActionSettings = BaseWorkflowActionSettings & {
+ input: WorkflowWaitForEventActionInput;
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/utils/compute-wait-timeout-in-ms.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/utils/compute-wait-timeout-in-ms.util.ts
new file mode 100644
index 00000000000..0a5f38d82d6
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/utils/compute-wait-timeout-in-ms.util.ts
@@ -0,0 +1,45 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ WorkflowStepExecutorException,
+ WorkflowStepExecutorExceptionCode,
+} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+import { type WorkflowWaitForEventActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-input.type';
+
+const MS_PER_MINUTE = 60 * 1000;
+
+const MAX_TIMEOUT_IN_MS = 365 * 24 * 60 * MS_PER_MINUTE;
+
+// Variables resolve timeout parts to strings, and an empty part means none of that unit
+export const computeWaitTimeoutInMs = (
+ timeout: WorkflowWaitForEventActionInput['timeout'],
+): number | null => {
+ if (!isDefined(timeout)) {
+ return null;
+ }
+
+ const days = Number(timeout.days || 0);
+ const hours = Number(timeout.hours || 0);
+ const minutes = Number(timeout.minutes || 0);
+
+ // a timeout that cannot be read must not turn into a wait without a deadline
+ if (
+ [days, hours, minutes].some((value) => !Number.isFinite(value) || value < 0)
+ ) {
+ throw new WorkflowStepExecutorException(
+ 'Wait timeout must be made of non-negative numbers',
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ );
+ }
+
+ const timeoutInMs = ((days * 24 + hours) * 60 + minutes) * MS_PER_MINUTE;
+
+ if (timeoutInMs > MAX_TIMEOUT_IN_MS) {
+ throw new WorkflowStepExecutorException(
+ 'Wait timeout cannot exceed one year',
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ );
+ }
+
+ return timeoutInMs > 0 ? timeoutInMs : null;
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/wait-for-event-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/wait-for-event-action.module.ts
new file mode 100644
index 00000000000..4174d2c879b
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/wait-for-event-action.module.ts
@@ -0,0 +1,9 @@
+import { Module } from '@nestjs/common';
+
+import { WaitForEventWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/wait-for-event.workflow-action';
+
+@Module({
+ providers: [WaitForEventWorkflowAction],
+ exports: [WaitForEventWorkflowAction],
+})
+export class WaitForEventActionModule {}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/wait-for-event.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/wait-for-event.workflow-action.ts
new file mode 100644
index 00000000000..c4720d0ebe8
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/wait-for-event.workflow-action.ts
@@ -0,0 +1,76 @@
+import { Injectable } from '@nestjs/common';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isNonEmptyArray, resolveInput } from 'twenty-shared/utils';
+
+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
+
+import {
+ WorkflowStepExecutorException,
+ WorkflowStepExecutorExceptionCode,
+} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
+import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';
+import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';
+import { WAIT_FOR_EVENT_NAME_PATTERN } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/constants/wait-for-event-name-pattern.constant';
+import { isWorkflowWaitForEventAction } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/guards/is-workflow-wait-for-event-action.guard';
+import { type WorkflowWaitForEventActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-input.type';
+import { computeWaitTimeoutInMs } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/utils/compute-wait-timeout-in-ms.util';
+
+@Injectable()
+export class WaitForEventWorkflowAction implements WorkflowAction {
+ async execute({
+ currentStepId,
+ steps,
+ context,
+ }: WorkflowActionInput): Promise<WorkflowActionOutput> {
+ const step = findStepOrThrow({
+ stepId: currentStepId,
+ steps,
+ });
+
+ if (!isWorkflowWaitForEventAction(step)) {
+ throw new WorkflowStepExecutorException(
+ 'Step is not a wait for event action',
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_TYPE,
+ );
+ }
+
+ const { eventName, recordId, updatedFields, timeout } = resolveInput(
+ step.settings.input,
+ context,
+ ) as WorkflowWaitForEventActionInput;
+
+ // a record set in the step that resolves to nothing would otherwise widen the wait to every record
+ if (
+ isNonEmptyString(step.settings.input.recordId) &&
+ !isNonEmptyString(recordId)
+ ) {
+ throw new WorkflowStepExecutorException(
+ 'The record to wait for resolved to no record',
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ );
+ }
+
+ if (!WAIT_FOR_EVENT_NAME_PATTERN.test(eventName)) {
+ throw new WorkflowStepExecutorException(
+ `Invalid event to wait for: "${eventName}"`,
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ );
+ }
+
+ const timeoutInMs = computeWaitTimeoutInMs(timeout);
+
+ return {
+ wait: {
+ type: 'EVENT',
+ eventName,
+ ...(isNonEmptyString(recordId) ? { recordId } : {}),
+ ...(isNonEmptyArray(updatedFields) ? { updatedFields } : {}),
+ ...(isDefined(timeoutInMs)
+ ? { expiresAt: new Date(Date.now() + timeoutInMs).toISOString() }
+ : {}),
+ },
+ };
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts
index b49d16ecc1d..8c32edf4e67 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts
@@ -23,9 +23,11 @@ import { IteratorActionModule } from 'src/modules/workflow/workflow-executor/wor
import { LogicFunctionActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function-action.module';
import { MailSenderActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/mail-sender-action.module';
import { SendChatMessageActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module';
+import { WaitForEventActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/wait-for-event-action.module';
import { RecordCRUDActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/record-crud/record-crud-action.module';
import { WorkflowExecutorWorkspaceService } from 'src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service';
import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
+import { WorkflowStepWaitStoreModule } from 'src/modules/workflow/workflow-wait/workflow-step-wait-store.module';
@Module({
imports: [
@@ -35,6 +37,7 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow
CodeActionModule,
LogicFunctionActionModule,
DelayActionModule,
+ WaitForEventActionModule,
RecordCRUDActionModule,
FormActionModule,
BillingModule,
@@ -53,8 +56,9 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow
MetricsModule,
UsageLimitModule,
UsageModule,
+ WorkflowStepWaitStoreModule,
],
providers: [WorkflowExecutorWorkspaceService, WorkflowActionFactory],
- exports: [WorkflowExecutorWorkspaceService],
+ exports: [WorkflowExecutorWorkspaceService, WorkflowActionFactory],
})
export class WorkflowExecutorModule {}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
index b0f367bcc70..a642e8c647f 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
@@ -59,6 +59,7 @@ import { RUN_WORKFLOW_JOB_NAME } from 'src/modules/workflow/workflow-runner/cons
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 { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
+import { WorkflowStepWaitWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service';
const MAX_EXECUTED_STEPS_COUNT = 20;
@@ -79,6 +80,7 @@ export class WorkflowExecutorWorkspaceService {
private readonly featureFlagService: FeatureFlagService,
private readonly exceptionHandlerService: ExceptionHandlerService,
private readonly metricsService: MetricsService,
+ private readonly workflowStepWaitWorkspaceService: WorkflowStepWaitWorkspaceService,
@InjectMessageQueue(MessageQueue.workflowQueue)
private readonly messageQueueService: MessageQueueService,
) {}
@@ -486,7 +488,7 @@ export class WorkflowExecutorWorkspaceService {
workflowRunId: string;
workspaceId: string;
}): Promise<{ shouldProcessNextSteps: boolean }> {
- const isPendingEvent = actionOutput.pendingEvent;
+ const wait = actionOutput.wait;
const isSuccess = isDefined(actionOutput.result);
const isStopped = actionOutput.shouldEndWorkflowRun ?? false;
const isNotFinished = actionOutput.shouldRemainRunning ?? false;
@@ -495,9 +497,10 @@ export class WorkflowExecutorWorkspaceService {
let stepInfo: WorkflowRunStepInfo;
- if (isPendingEvent) {
+ if (isDefined(wait)) {
stepInfo = {
status: StepStatus.PENDING,
+ wait,
};
} else if (isStopped) {
stepInfo = {
@@ -530,6 +533,16 @@ export class WorkflowExecutorWorkspaceService {
};
}
+ // armed before the step reads as pending, so an event in between is put off rather than lost
+ if (isDefined(wait)) {
+ await this.workflowStepWaitWorkspaceService.arm({
+ workspaceId,
+ workflowRunId,
+ stepId,
+ wait,
+ });
+ }
+
await this.workflowRunWorkspaceService.updateWorkflowRunStepInfo({
stepId,
stepInfo,
@@ -537,12 +550,45 @@ export class WorkflowExecutorWorkspaceService {
workspaceId,
});
+ if (isDefined(wait)) {
+ await this.cancelWaitIfRunEnded({ stepId, workflowRunId, workspaceId });
+ }
+
return {
shouldProcessNextSteps:
isSuccess || isStopped || isSkipped || isFailedSafely,
};
}
+ // a run that ended while its step was arming cancelled its waits before this one existed
+ private async cancelWaitIfRunEnded({
+ stepId,
+ workflowRunId,
+ workspaceId,
+ }: {
+ stepId: string;
+ workflowRunId: string;
+ workspaceId: string;
+ }): Promise<void> {
+ const { status } =
+ await this.workflowRunWorkspaceService.getWorkflowRunOrFail({
+ workflowRunId,
+ workspaceId,
+ });
+
+ if (
+ status === WorkflowRunStatus.COMPLETED ||
+ status === WorkflowRunStatus.FAILED ||
+ status === WorkflowRunStatus.STOPPED
+ ) {
+ await this.workflowStepWaitWorkspaceService.cancelStepWait({
+ workspaceId,
+ workflowRunId,
+ stepId,
+ });
+ }
+ }
+
private async executeStep({
step,
steps,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
index 4093d6131b0..7be0db5d193 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
@@ -54,6 +54,7 @@ describe('WorkflowRunWorkspaceService conversations', () => {
{} as never,
threadRepository as never,
messagePartRepository as never,
+ { cancelRunWaits: jest.fn().mockResolvedValue(undefined) } as never,
);
// The run lock serializes these methods with every other step write.
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
index aa9827b44c5..e2e3cb8b567 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
@@ -11,6 +11,7 @@ import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-commo
import { DeleteWorkflowRunsCommand } from 'src/modules/workflow/workflow-runner/workflow-run/command/delete-workflow-runs.command';
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 { WorkflowStepWaitStoreModule } from 'src/modules/workflow/workflow-wait/workflow-step-wait-store.module';
@Module({
imports: [
@@ -22,6 +23,7 @@ import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runne
FeatureFlagModule,
WorkflowRunRecordShareModule,
AgentHistoryModule,
+ WorkflowStepWaitStoreModule,
],
providers: [
WorkflowRunWorkspaceService,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
index 4073ce79a1b..cf4f71311b0 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
@@ -32,6 +32,7 @@ import { isWorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/
import { isWorkflowSendChatMessageAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/guards/is-workflow-send-chat-message-action.guard';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { type WorkflowTrigger } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
+import { WorkflowStepWaitWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service';
import {
WorkflowRunException,
WorkflowRunExceptionCode,
@@ -50,6 +51,7 @@ export class WorkflowRunWorkspaceService {
private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
@InjectAgentHistoryRepository('agentMessagePart')
private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
+ private readonly workflowStepWaitWorkspaceService: WorkflowStepWaitWorkspaceService,
) {}
async createCoreWorkflowRun({
@@ -210,6 +212,15 @@ export class WorkflowRunWorkspaceService {
await this.updateWorkflowRun({ workflowRunId, workspaceId, partialUpdate });
+ // the run is already over and its waits find nothing to resume, so a failure must not stop the cleanup below
+ await this.workflowStepWaitWorkspaceService
+ .cancelRunWaits({ workspaceId, workflowRunId })
+ .catch((error: unknown) => {
+ this.logger.error(
+ `Failed to cancel the waits of workflow run ${workflowRunId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ });
+
const stepThreadIds = Object.values(
workflowRunToUpdate.state?.stepInfos ?? {},
)
@@ -278,6 +289,7 @@ export class WorkflowRunWorkspaceService {
result: stepInfo?.result,
error: stepInfo?.error,
status: stepInfo.status,
+ wait: stepInfo?.wait,
},
},
},
@@ -464,7 +476,8 @@ export class WorkflowRunWorkspaceService {
...workflowRunToUpdate.state,
stepInfos: {
...workflowRunToUpdate.state?.stepInfos,
- [stepId]: { ...currentStepInfo, ...stepInfo },
+ // the step leaves PENDING, so it no longer waits
+ [stepId]: { ...currentStepInfo, wait: undefined, ...stepInfo },
},
},
},
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts
index b71285658e7..815298406e1 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts
@@ -1,7 +1,6 @@
import { buildCoreDispatchIds } from 'src/engine/core-modules/workflow/utils/build-core-dispatch-ids.util';
import { Injectable, Logger } from '@nestjs/common';
-import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
import {
ObjectRecordEvent,
type ObjectRecordCreateEvent,
@@ -17,23 +16,19 @@ import { In } from 'typeorm';
import { OnDatabaseBatchEvent } from 'src/engine/api/graphql/graphql-query-runner/decorators/on-database-batch-event.decorator';
import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';
-import { findActiveFlatApplicationByUniversalIdentifier } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-universal-identifier.util';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
-import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
import { buildFieldMapsFromFlatObjectMetadata } from 'src/engine/metadata-modules/flat-field-metadata/utils/build-field-maps-from-flat-object-metadata.util';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import { RecordAccessPolicyService } from 'src/engine/core-modules/record-share/services/record-access-policy.service';
import { omitInheritedReadabilityChildRecords } from 'src/engine/core-modules/record-share/utils/omit-inherited-readability-child-records.util';
-import { buildRoleRowAccessPolicySubject } from 'src/engine/core-modules/record-share/utils/build-role-row-access-policy-subject.util';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
-import { STANDARD_ROLE } from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-role.constant';
import { isCachedDatabaseEventTrigger } from 'src/engine/core-modules/workflow/utils/cached-workflow-automated-trigger.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';
@@ -44,6 +39,7 @@ import {
type BaseDatabaseEventTriggerSettings,
type UpdateEventTriggerSettings,
} from 'src/modules/workflow/workflow-trigger/automated-trigger/constants/automated-trigger-settings';
+import { resolveAutomationAdmittedRecordIds } from 'src/modules/workflow/workflow-trigger/automated-trigger/utils/resolve-automation-admitted-record-ids.util';
import { type CoreDispatchIds } from 'src/engine/core-modules/workflow/types/workflow-automated-trigger-maps.type';
import {
WorkflowTriggerJob,
@@ -414,47 +410,11 @@ export class WorkflowDatabaseEventTriggerListener {
private async resolveAdmittedRecordIds(
payload: WorkspaceEventBatch<ObjectRecordEvent>,
): Promise<Set<string>> {
- const {
- flatApplicationMaps,
- flatRoleMaps,
- rolesPermissions,
- roleIdsWithAllRecordsAccess,
- flatRowLevelPermissionPredicateMaps,
- flatRowLevelPermissionPredicateGroupMaps,
- flatFieldMetadataMaps,
- } = await this.workspaceCacheService.getOrRecompute(payload.workspaceId, [
- 'flatApplicationMaps',
- 'flatRoleMaps',
- 'rolesPermissions',
- 'roleIdsWithAllRecordsAccess',
- 'flatRowLevelPermissionPredicateMaps',
- 'flatRowLevelPermissionPredicateGroupMaps',
- 'flatFieldMetadataMaps',
- ]);
-
- const standardApplication = findActiveFlatApplicationByUniversalIdentifier(
- flatApplicationMaps,
- TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
- );
-
- return this.recordAccessPolicyService
- .buildEventRecordAccessGate(payload)
- .resolveAdmittedRecordIds(
- buildRoleRowAccessPolicySubject({
- roleId:
- standardApplication?.defaultRoleId ??
- findFlatEntityByUniversalIdentifier({
- flatEntityMaps: flatRoleMaps,
- universalIdentifier: STANDARD_ROLE.admin.universalIdentifier,
- })?.id,
- owningApplicationId: standardApplication?.id,
- rolesPermissions,
- roleIdsWithAllRecordsAccess,
- flatRowLevelPermissionPredicateMaps,
- flatRowLevelPermissionPredicateGroupMaps,
- flatFieldMetadataMaps,
- }),
- );
+ return resolveAutomationAdmittedRecordIds({
+ payload,
+ workspaceCacheService: this.workspaceCacheService,
+ recordAccessPolicyService: this.recordAccessPolicyService,
+ });
}
private shouldTriggerJob({
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/utils/resolve-automation-admitted-record-ids.util.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/utils/resolve-automation-admitted-record-ids.util.ts
new file mode 100644
index 00000000000..792a6abd658
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/utils/resolve-automation-admitted-record-ids.util.ts
@@ -0,0 +1,62 @@
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import { type ObjectRecordEvent } from 'twenty-shared/database-events';
+
+import { findActiveFlatApplicationByUniversalIdentifier } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-universal-identifier.util';
+import { type RecordAccessPolicyService } from 'src/engine/core-modules/record-share/services/record-access-policy.service';
+import { buildRoleRowAccessPolicySubject } from 'src/engine/core-modules/record-share/utils/build-role-row-access-policy-subject.util';
+import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';
+import { STANDARD_ROLE } from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-role.constant';
+
+export const resolveAutomationAdmittedRecordIds = async ({
+ payload,
+ workspaceCacheService,
+ recordAccessPolicyService,
+}: {
+ payload: WorkspaceEventBatch<ObjectRecordEvent>;
+ workspaceCacheService: WorkspaceCacheService;
+ recordAccessPolicyService: RecordAccessPolicyService;
+}): Promise<Set<string>> => {
+ const {
+ flatApplicationMaps,
+ flatRoleMaps,
+ rolesPermissions,
+ roleIdsWithAllRecordsAccess,
+ flatRowLevelPermissionPredicateMaps,
+ flatRowLevelPermissionPredicateGroupMaps,
+ flatFieldMetadataMaps,
+ } = await workspaceCacheService.getOrRecompute(payload.workspaceId, [
+ 'flatApplicationMaps',
+ 'flatRoleMaps',
+ 'rolesPermissions',
+ 'roleIdsWithAllRecordsAccess',
+ 'flatRowLevelPermissionPredicateMaps',
+ 'flatRowLevelPermissionPredicateGroupMaps',
+ 'flatFieldMetadataMaps',
+ ]);
+
+ const standardApplication = findActiveFlatApplicationByUniversalIdentifier(
+ flatApplicationMaps,
+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ );
+
+ return recordAccessPolicyService
+ .buildEventRecordAccessGate(payload)
+ .resolveAdmittedRecordIds(
+ buildRoleRowAccessPolicySubject({
+ roleId:
+ standardApplication?.defaultRoleId ??
+ findFlatEntityByUniversalIdentifier({
+ flatEntityMaps: flatRoleMaps,
+ universalIdentifier: STANDARD_ROLE.admin.universalIdentifier,
+ })?.id,
+ owningApplicationId: standardApplication?.id,
+ rolesPermissions,
+ roleIdsWithAllRecordsAccess,
+ flatRowLevelPermissionPredicateMaps,
+ flatRowLevelPermissionPredicateGroupMaps,
+ flatFieldMetadataMaps,
+ }),
+ );
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/assert-version-can-be-activated.util.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/assert-version-can-be-activated.util.ts
index 77c23e5b0ec..e9d62041d3a 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/assert-version-can-be-activated.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/assert-version-can-be-activated.util.ts
@@ -12,6 +12,7 @@ import {
WorkflowTriggerExceptionCode,
} from 'src/modules/workflow/workflow-trigger/exceptions/workflow-trigger.exception';
import { WorkflowTriggerType } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
+import { assertWaitForEventStepIsValid } from 'src/modules/workflow/workflow-trigger/utils/assert-wait-for-event-step-is-valid.util';
import { assertFormStepIsValid } from 'src/modules/workflow/workflow-trigger/utils/assert-form-step-is-valid.util';
export function assertVersionCanBeActivated(
@@ -275,6 +276,9 @@ function assertStepIsValid(step: WorkflowAction) {
case WorkflowActionType.FORM:
assertFormStepIsValid(step.settings);
break;
+ case WorkflowActionType.WAIT_FOR_EVENT:
+ assertWaitForEventStepIsValid(step.settings);
+ break;
default:
break;
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/assert-wait-for-event-step-is-valid.util.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/assert-wait-for-event-step-is-valid.util.ts
new file mode 100644
index 00000000000..d4be485f493
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/assert-wait-for-event-step-is-valid.util.ts
@@ -0,0 +1,26 @@
+import { msg } from '@lingui/core/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { WAIT_FOR_EVENT_NAME_PATTERN } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/constants/wait-for-event-name-pattern.constant';
+import { type WorkflowWaitForEventActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/wait-for-event/types/workflow-wait-for-event-action-settings.type';
+import {
+ WorkflowTriggerException,
+ WorkflowTriggerExceptionCode,
+} from 'src/modules/workflow/workflow-trigger/exceptions/workflow-trigger.exception';
+
+export const assertWaitForEventStepIsValid = (
+ settings: WorkflowWaitForEventActionSettings,
+) => {
+ if (
+ !isNonEmptyString(settings.input?.eventName) ||
+ !WAIT_FOR_EVENT_NAME_PATTERN.test(settings.input.eventName)
+ ) {
+ throw new WorkflowTriggerException(
+ 'Wait for event step must have a valid event',
+ WorkflowTriggerExceptionCode.INVALID_WORKFLOW_VERSION,
+ {
+ userFriendlyMessage: msg`Wait for event step must have a valid event`,
+ },
+ );
+ }
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/constants/resume-waiting-workflow-step-job-name.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/constants/resume-waiting-workflow-step-job-name.constant.ts
new file mode 100644
index 00000000000..a21a2bf7238
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/constants/resume-waiting-workflow-step-job-name.constant.ts
@@ -0,0 +1,2 @@
+export const RESUME_WAITING_WORKFLOW_STEP_JOB_NAME =
+ 'ResumeWaitingWorkflowStepJob';
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/crons/commands/workflow-step-wait-sweep.cron.command.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/crons/commands/workflow-step-wait-sweep.cron.command.ts
new file mode 100644
index 00000000000..8d3f455727d
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/crons/commands/workflow-step-wait-sweep.cron.command.ts
@@ -0,0 +1,34 @@
+import { Command, CommandRunner } from 'nest-commander';
+
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import {
+ WORKFLOW_STEP_WAIT_SWEEP_CRON_PATTERN,
+ WorkflowStepWaitSweepCronJob,
+} from 'src/modules/workflow/workflow-wait/crons/jobs/workflow-step-wait-sweep.cron.job';
+
+@Command({
+ name: 'cron:workflow:step-wait-sweep',
+ description: 'Reschedules workflow step waits whose resume time passed',
+})
+export class WorkflowStepWaitSweepCronCommand extends CommandRunner {
+ constructor(
+ @InjectMessageQueue(MessageQueue.cronQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {
+ super();
+ }
+
+ async run(): Promise<void> {
+ await this.messageQueueService.addCron({
+ jobName: WorkflowStepWaitSweepCronJob.name,
+ data: undefined,
+ options: {
+ repeat: {
+ pattern: WORKFLOW_STEP_WAIT_SWEEP_CRON_PATTERN,
+ },
+ },
+ });
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/crons/jobs/workflow-step-wait-sweep.cron.job.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/crons/jobs/workflow-step-wait-sweep.cron.job.ts
new file mode 100644
index 00000000000..67bb10d9cde
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/crons/jobs/workflow-step-wait-sweep.cron.job.ts
@@ -0,0 +1,60 @@
+import { Logger } from '@nestjs/common';
+import { InjectDataSource } from '@nestjs/typeorm';
+
+import { DataSource } from 'typeorm';
+
+import { SentryCronMonitor } from 'src/engine/core-modules/cron/sentry-cron-monitor.decorator';
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { WorkflowStepWaitWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service';
+
+export const WORKFLOW_STEP_WAIT_SWEEP_CRON_PATTERN = '*/5 * * * *';
+
+const OVERDUE_GRACE_INTERVAL = '5 minutes';
+const OVERDUE_WAITS_BATCH_SIZE = 1000;
+
+type OverdueWaitRow = {
+ id: string;
+ workspaceId: string;
+ workflowRunId: string;
+};
+
+// Resolutions are queued jobs, so a lost job would leave its wait forever; claiming makes a duplicate harmless
+@Processor(MessageQueue.cronQueue)
+export class WorkflowStepWaitSweepCronJob {
+ private readonly logger = new Logger(WorkflowStepWaitSweepCronJob.name);
+
+ constructor(
+ @InjectDataSource()
+ private readonly coreDataSource: DataSource,
+ private readonly workflowStepWaitWorkspaceService: WorkflowStepWaitWorkspaceService,
+ ) {}
+
+ @Process(WorkflowStepWaitSweepCronJob.name)
+ @SentryCronMonitor(
+ WorkflowStepWaitSweepCronJob.name,
+ WORKFLOW_STEP_WAIT_SWEEP_CRON_PATTERN,
+ )
+ async handle() {
+ const overdueWaits: OverdueWaitRow[] = await this.coreDataSource.query(
+ `SELECT "id", "workspaceId", "workflowRunId" FROM "core"."workflowStepWait"
+ WHERE "resumeAt" < now() - interval '${OVERDUE_GRACE_INTERVAL}'
+ ORDER BY "resumeAt" ASC
+ LIMIT $1`,
+ [OVERDUE_WAITS_BATCH_SIZE],
+ );
+
+ for (const { id, workspaceId, workflowRunId } of overdueWaits) {
+ await this.workflowStepWaitWorkspaceService.scheduleOverdueResolution({
+ workspaceId,
+ workflowRunId,
+ waitId: id,
+ });
+ }
+
+ if (overdueWaits.length > 0) {
+ this.logger.log(`Rescheduled ${overdueWaits.length} overdue step waits`);
+ }
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/jobs/resume-waiting-workflow-step.job.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/jobs/resume-waiting-workflow-step.job.ts
new file mode 100644
index 00000000000..7edd9b2e51f
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/jobs/resume-waiting-workflow-step.job.ts
@@ -0,0 +1,29 @@
+import { Scope } from '@nestjs/common';
+
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { RESUME_WAITING_WORKFLOW_STEP_JOB_NAME } from 'src/modules/workflow/workflow-wait/constants/resume-waiting-workflow-step-job-name.constant';
+import { WorkflowStepWaitResolverWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait-resolver.workspace-service';
+import { type ResumeWaitingWorkflowStepJobData } from 'src/modules/workflow/workflow-wait/types/resume-waiting-workflow-step-job-data.type';
+
+@Processor({
+ queueName: MessageQueue.delayedJobsQueue,
+ scope: Scope.REQUEST,
+})
+export class ResumeWaitingWorkflowStepJob {
+ constructor(
+ private readonly workflowStepWaitResolverWorkspaceService: WorkflowStepWaitResolverWorkspaceService,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ ) {}
+
+ @Process(RESUME_WAITING_WORKFLOW_STEP_JOB_NAME)
+ async handle(jobData: ResumeWaitingWorkflowStepJobData): Promise<void> {
+ await this.workspaceOrmManager.executeInWorkspaceContext(
+ () => this.workflowStepWaitResolverWorkspaceService.resolve(jobData),
+ buildSystemAuthContext(jobData.workspaceId),
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/listeners/workflow-step-wait-database-event.listener.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/listeners/workflow-step-wait-database-event.listener.ts
new file mode 100644
index 00000000000..aa8a2698058
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/listeners/workflow-step-wait-database-event.listener.ts
@@ -0,0 +1,107 @@
+import { Injectable } from '@nestjs/common';
+
+import { type ObjectRecordEvent } from 'twenty-shared/database-events';
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { OnDatabaseBatchEvent } from 'src/engine/api/graphql/graphql-query-runner/decorators/on-database-batch-event.decorator';
+import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';
+import { RecordAccessPolicyService } from 'src/engine/core-modules/record-share/services/record-access-policy.service';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';
+import { resolveAutomationAdmittedRecordIds } from 'src/modules/workflow/workflow-trigger/automated-trigger/utils/resolve-automation-admitted-record-ids.util';
+import { WorkflowStepWaitWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service';
+import { buildWorkflowWaitEvent } from 'src/modules/workflow/workflow-wait/utils/build-workflow-wait-event.util';
+import { doesEventMatchWait } from 'src/modules/workflow/workflow-wait/utils/does-event-match-wait.util';
+
+@Injectable()
+export class WorkflowStepWaitDatabaseEventListener {
+ constructor(
+ private readonly workflowStepWaitWorkspaceService: WorkflowStepWaitWorkspaceService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly recordAccessPolicyService: RecordAccessPolicyService,
+ ) {}
+
+ @OnDatabaseBatchEvent('*', DatabaseEventAction.CREATED)
+ async handleObjectRecordCreateEvent(
+ payload: WorkspaceEventBatch<ObjectRecordEvent>,
+ ) {
+ await this.resumeMatchingWaits(payload);
+ }
+
+ @OnDatabaseBatchEvent('*', DatabaseEventAction.UPDATED)
+ async handleObjectRecordUpdateEvent(
+ payload: WorkspaceEventBatch<ObjectRecordEvent>,
+ ) {
+ await this.resumeMatchingWaits(payload);
+ }
+
+ @OnDatabaseBatchEvent('*', DatabaseEventAction.DELETED)
+ async handleObjectRecordDeleteEvent(
+ payload: WorkspaceEventBatch<ObjectRecordEvent>,
+ ) {
+ await this.resumeMatchingWaits(payload);
+ }
+
+ @OnDatabaseBatchEvent('*', DatabaseEventAction.UPSERTED)
+ async handleObjectRecordUpsertEvent(
+ payload: WorkspaceEventBatch<ObjectRecordEvent>,
+ ) {
+ await this.resumeMatchingWaits(payload);
+ }
+
+ private async resumeMatchingWaits(
+ payload: WorkspaceEventBatch<ObjectRecordEvent>,
+ ): Promise<void> {
+ const { workspaceId, name: eventName } = payload;
+
+ if (!isNonEmptyString(workspaceId) || !isNonEmptyString(eventName)) {
+ return;
+ }
+
+ const eventWaits =
+ await this.workflowStepWaitWorkspaceService.findEventWaits({
+ workspaceId,
+ eventName,
+ });
+
+ if (eventWaits.length === 0) {
+ return;
+ }
+
+ const admittedRecordIds = await resolveAutomationAdmittedRecordIds({
+ payload,
+ workspaceCacheService: this.workspaceCacheService,
+ recordAccessPolicyService: this.recordAccessPolicyService,
+ });
+
+ const now = Date.now();
+
+ for (const eventWait of eventWaits) {
+ // an expired wait resolves as a timeout through its own job
+ if (
+ isDefined(eventWait.resumeAt) &&
+ eventWait.resumeAt.getTime() <= now
+ ) {
+ continue;
+ }
+
+ const matchingEvent = payload.events.find(
+ (event) =>
+ admittedRecordIds.has(event.recordId) &&
+ doesEventMatchWait({ wait: eventWait.wait, event }),
+ );
+
+ if (!isDefined(matchingEvent)) {
+ continue;
+ }
+
+ await this.workflowStepWaitWorkspaceService.scheduleResolution({
+ workspaceId,
+ workflowRunId: eventWait.workflowRunId,
+ waitId: eventWait.id,
+ event: buildWorkflowWaitEvent({ eventName, event: matchingEvent }),
+ });
+ }
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/services/__tests__/workflow-step-wait-resolver.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/services/__tests__/workflow-step-wait-resolver.workspace-service.spec.ts
new file mode 100644
index 00000000000..2c58e8601e2
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/services/__tests__/workflow-step-wait-resolver.workspace-service.spec.ts
@@ -0,0 +1,360 @@
+import { StepStatus } from 'twenty-shared/workflow';
+
+import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+import { RUN_WORKFLOW_JOB_NAME } from 'src/modules/workflow/workflow-runner/constants/run-workflow-job-name';
+import { WorkflowStepWaitResolverWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait-resolver.workspace-service';
+
+const WORKSPACE_ID = 'workspace-id';
+const WORKFLOW_RUN_ID = 'workflow-run-id';
+const STEP_ID = 'step-id';
+const WAIT_ID = 'wait-id';
+
+const EVENT = {
+ eventName: 'company.updated',
+ recordId: 'company-id',
+ record: { id: 'company-id', secret: 'hidden from the run' },
+};
+
+const READABLE_RECORD = { id: 'company-id', name: 'Acme' };
+
+const STORED_WAIT = {
+ id: WAIT_ID,
+ workflowRunId: WORKFLOW_RUN_ID,
+ stepId: STEP_ID,
+ wait: { type: 'EVENT', eventName: 'company.updated' },
+};
+
+const buildService = ({
+ storedWait = STORED_WAIT,
+ runStatus = WorkflowRunStatus.RUNNING,
+ stepStatus = StepStatus.PENDING,
+ stepType = 'WAIT_FOR_EVENT',
+ readableRecords = [READABLE_RECORD],
+ isRecordReadFailing = false,
+ resolveWait,
+}: {
+ storedWait?: object | null;
+ runStatus?: WorkflowRunStatus;
+ stepStatus?: StepStatus;
+ stepType?: string;
+ readableRecords?: object[];
+ isRecordReadFailing?: boolean;
+ resolveWait?: jest.Mock;
+} = {}) => {
+ const workflowStepWaitWorkspaceService = {
+ findWait: jest.fn().mockResolvedValue(storedWait),
+ claim: jest.fn().mockResolvedValue(storedWait),
+ scheduleResolution: jest.fn(),
+ };
+ const workflowRunWorkspaceService = {
+ getWorkflowRun: jest.fn().mockResolvedValue({
+ status: runStatus,
+ state: {
+ flow: { steps: [{ id: STEP_ID, type: stepType }] },
+ stepInfos: { [STEP_ID]: { status: stepStatus, threadId: 'thread-id' } },
+ },
+ }),
+ updateStepInfoIfPending: jest.fn().mockResolvedValue(true),
+ endWorkflowRun: jest.fn(),
+ };
+ const workflowActionFactory = {
+ get: jest.fn().mockReturnValue({ execute: jest.fn(), resolveWait }),
+ };
+ const workflowExecutionContextService = {
+ getExecutionContext: jest.fn().mockResolvedValue({
+ authContext: { type: 'system' },
+ rolePermissionConfig: { unionOf: ['role-id'] },
+ }),
+ };
+ const findRecordsService = {
+ execute: jest
+ .fn()
+ .mockResolvedValue(
+ isRecordReadFailing
+ ? { success: false, error: 'Connection terminated unexpectedly' }
+ : { success: true, result: { records: readableRecords } },
+ ),
+ };
+ const messageQueueService = { add: jest.fn() };
+
+ const service = new WorkflowStepWaitResolverWorkspaceService(
+ workflowStepWaitWorkspaceService as never,
+ workflowRunWorkspaceService as never,
+ workflowActionFactory as never,
+ workflowExecutionContextService as never,
+ findRecordsService as never,
+ messageQueueService as never,
+ );
+
+ return {
+ service,
+ workflowStepWaitWorkspaceService,
+ workflowRunWorkspaceService,
+ findRecordsService,
+ messageQueueService,
+ };
+};
+
+describe('WorkflowStepWaitResolverWorkspaceService', () => {
+ it('does nothing when the wait was already resolved or cancelled', async () => {
+ const { service, workflowRunWorkspaceService, messageQueueService } =
+ buildService({ storedWait: null });
+
+ await service.resolve({ workspaceId: WORKSPACE_ID, waitId: WAIT_ID });
+
+ expect(workflowRunWorkspaceService.getWorkflowRun).not.toHaveBeenCalled();
+ 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();
+
+ await service.resolve({
+ workspaceId: WORKSPACE_ID,
+ waitId: WAIT_ID,
+ 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,
+ },
+ expect.anything(),
+ );
+ });
+
+ it('keeps waiting when the run cannot read the record of the event', async () => {
+ const {
+ service,
+ workflowStepWaitWorkspaceService,
+ workflowRunWorkspaceService,
+ } = buildService({ readableRecords: [] });
+
+ await service.resolve({
+ workspaceId: WORKSPACE_ID,
+ waitId: WAIT_ID,
+ event: EVENT,
+ });
+
+ expect(workflowStepWaitWorkspaceService.claim).not.toHaveBeenCalled();
+ expect(
+ workflowRunWorkspaceService.updateStepInfoIfPending,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('keeps the event and tries again when reading its record fails', async () => {
+ const { service, workflowStepWaitWorkspaceService } = buildService({
+ isRecordReadFailing: true,
+ });
+
+ await service.resolve({
+ workspaceId: WORKSPACE_ID,
+ waitId: WAIT_ID,
+ event: EVENT,
+ });
+
+ expect(workflowStepWaitWorkspaceService.claim).not.toHaveBeenCalled();
+ expect(
+ workflowStepWaitWorkspaceService.scheduleResolution,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({ event: EVENT, recordReadAttempt: 1 }),
+ );
+ });
+
+ it('keeps waiting for another event once reading the record kept failing', async () => {
+ const {
+ service,
+ workflowStepWaitWorkspaceService,
+ workflowRunWorkspaceService,
+ } = buildService({ isRecordReadFailing: true });
+
+ await service.resolve({
+ workspaceId: WORKSPACE_ID,
+ waitId: WAIT_ID,
+ event: EVENT,
+ recordReadAttempt: 8,
+ });
+
+ expect(workflowStepWaitWorkspaceService.claim).not.toHaveBeenCalled();
+ expect(
+ workflowStepWaitWorkspaceService.scheduleResolution,
+ ).not.toHaveBeenCalled();
+ expect(workflowRunWorkspaceService.endWorkflowRun).not.toHaveBeenCalled();
+ });
+
+ it('keeps fields the run cannot read out of the previous snapshot', async () => {
+ const { service, workflowRunWorkspaceService } = buildService();
+
+ await service.resolve({
+ workspaceId: WORKSPACE_ID,
+ waitId: WAIT_ID,
+ event: {
+ ...EVENT,
+ before: { id: 'company-id', name: 'Old', secret: 'old secret' },
+ updatedFields: ['name', 'secret'],
+ },
+ });
+
+ const [{ stepInfo }] =
+ workflowRunWorkspaceService.updateStepInfoIfPending.mock.calls[0];
+
+ expect(stepInfo.result.before).toEqual({ id: 'company-id', name: 'Old' });
+ expect(stepInfo.result.updatedFields).toEqual(['name']);
+ });
+
+ it('reads deleted records when the event is a deletion', async () => {
+ const { service, findRecordsService } = buildService();
+
+ await service.resolve({
+ workspaceId: WORKSPACE_ID,
+ waitId: WAIT_ID,
+ event: { ...EVENT, eventName: 'company.deleted' },
+ });
+
+ expect(findRecordsService.execute).toHaveBeenCalledWith(
+ expect.objectContaining({
+ objectName: 'company',
+ filter: { id: { eq: 'company-id' }, deletedAt: { is: 'NOT_NULL' } },
+ }),
+ );
+ });
+
+ it('puts the resolution off while the step is still pausing', async () => {
+ const { service, workflowStepWaitWorkspaceService } = buildService({
+ stepStatus: StepStatus.RUNNING,
+ });
+
+ await service.resolve({
+ workspaceId: WORKSPACE_ID,
+ waitId: WAIT_ID,
+ event: EVENT,
+ });
+
+ expect(workflowStepWaitWorkspaceService.claim).not.toHaveBeenCalled();
+ expect(
+ workflowStepWaitWorkspaceService.scheduleResolution,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({ waitId: WAIT_ID, event: EVENT, attempt: 1 }),
+ );
+ });
+
+ it('keeps putting the resolution off, at most a minute apart, while the step is pausing', async () => {
+ const { service, workflowStepWaitWorkspaceService } = buildService({
+ stepStatus: StepStatus.RUNNING,
+ });
+
+ await service.resolve({
+ workspaceId: WORKSPACE_ID,
+ waitId: WAIT_ID,
+ event: EVENT,
+ attempt: 20,
+ });
+
+ expect(workflowStepWaitWorkspaceService.claim).not.toHaveBeenCalled();
+ expect(
+ workflowStepWaitWorkspaceService.scheduleResolution,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({ event: EVENT, attempt: 21, delayMs: 60_000 }),
+ );
+ });
+
+ it('reports a timeout when an event wait expires', async () => {
+ const { service, workflowRunWorkspaceService } = buildService();
+
+ await service.resolve({ workspaceId: WORKSPACE_ID, waitId: WAIT_ID });
+
+ expect(
+ workflowRunWorkspaceService.updateStepInfoIfPending,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({
+ stepInfo: { status: StepStatus.SUCCESS, result: { hasTimedOut: true } },
+ }),
+ );
+ });
+
+ it('runs a step again on its conversation when the step resolves the wait itself', async () => {
+ const resolveWait = jest
+ .fn()
+ .mockResolvedValue({ resumedThreadId: 'thread-id' });
+ const { service, workflowRunWorkspaceService, messageQueueService } =
+ buildService({ stepType: 'AI_AGENT', resolveWait });
+
+ await service.resolve({
+ workspaceId: WORKSPACE_ID,
+ waitId: WAIT_ID,
+ event: EVENT,
+ });
+
+ expect(resolveWait).toHaveBeenCalledWith(
+ expect.objectContaining({
+ outcome: {
+ type: 'EVENT_RECEIVED',
+ event: { ...EVENT, record: READABLE_RECORD },
+ },
+ }),
+ );
+ expect(
+ workflowRunWorkspaceService.updateStepInfoIfPending,
+ ).not.toHaveBeenCalled();
+ expect(messageQueueService.add).toHaveBeenCalledWith(
+ RUN_WORKFLOW_JOB_NAME,
+ {
+ workspaceId: WORKSPACE_ID,
+ workflowRunId: WORKFLOW_RUN_ID,
+ stepToResume: { stepId: STEP_ID, threadId: 'thread-id' },
+ },
+ expect.anything(),
+ );
+ });
+
+ it('removes the wait of a run that is no longer running without resuming it', async () => {
+ const {
+ service,
+ workflowStepWaitWorkspaceService,
+ workflowRunWorkspaceService,
+ messageQueueService,
+ } = buildService({ runStatus: WorkflowRunStatus.STOPPED });
+
+ await service.resolve({ workspaceId: WORKSPACE_ID, waitId: WAIT_ID });
+
+ expect(workflowStepWaitWorkspaceService.claim).toHaveBeenCalled();
+ expect(
+ workflowRunWorkspaceService.updateStepInfoIfPending,
+ ).not.toHaveBeenCalled();
+ expect(messageQueueService.add).not.toHaveBeenCalled();
+ });
+
+ it('fails the run when the step cannot resume, since its wait is gone', async () => {
+ const resolveWait = jest.fn().mockRejectedValue(new Error('boom'));
+ const { service, workflowRunWorkspaceService } = buildService({
+ stepType: 'AI_AGENT',
+ resolveWait,
+ });
+
+ await expect(
+ service.resolve({ workspaceId: WORKSPACE_ID, waitId: WAIT_ID }),
+ ).rejects.toThrow('boom');
+
+ expect(workflowRunWorkspaceService.endWorkflowRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workflowRunId: WORKFLOW_RUN_ID,
+ status: WorkflowRunStatus.FAILED,
+ }),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-wait-resolver.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-wait-resolver.workspace-service.ts
new file mode 100644
index 00000000000..1249a0e09c2
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-wait-resolver.workspace-service.ts
@@ -0,0 +1,280 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+import { StepStatus } from 'twenty-shared/workflow';
+
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import { FindRecordsService } from 'src/engine/core-modules/record-crud/services/find-records.service';
+import { type WorkflowStepWaitEntity } from 'src/engine/core-modules/workflow/entities/workflow-step-wait.entity';
+import {
+ WorkflowRunStatus,
+ type WorkflowRunWorkspaceEntity,
+} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+import { WorkflowActionFactory } from 'src/modules/workflow/workflow-executor/factories/workflow-action.factory';
+import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
+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 { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
+import { WorkflowStepWaitWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service';
+import { type ResumeWaitingWorkflowStepJobData } from 'src/modules/workflow/workflow-wait/types/resume-waiting-workflow-step-job-data.type';
+import { type WorkflowWaitEvent } from 'src/modules/workflow/workflow-wait/types/workflow-wait-event.type';
+import { buildDefaultWaitResult } from 'src/modules/workflow/workflow-wait/utils/build-default-wait-result.util';
+import { buildWaitOutcome } from 'src/modules/workflow/workflow-wait/utils/build-wait-outcome.util';
+import { restrictWaitEventToReadableRecord } from 'src/modules/workflow/workflow-wait/utils/restrict-wait-event-to-readable-record.util';
+
+const RETRY_BASE_DELAY_MS = 2_000;
+const RETRY_MAX_DELAY_MS = 60_000;
+const RECORD_READ_MAX_ATTEMPTS = 8;
+
+const computeRetryDelayMs = (attempt: number) =>
+ Math.min(RETRY_BASE_DELAY_MS * 2 ** attempt, RETRY_MAX_DELAY_MS);
+
+type RunRecordRead =
+ | { status: 'READABLE'; record: Record<string, unknown> }
+ | { status: 'UNREADABLE' }
+ | { status: 'FAILED'; error?: string };
+
+@Injectable()
+export class WorkflowStepWaitResolverWorkspaceService {
+ private readonly logger = new Logger(
+ WorkflowStepWaitResolverWorkspaceService.name,
+ );
+
+ constructor(
+ private readonly workflowStepWaitWorkspaceService: WorkflowStepWaitWorkspaceService,
+ private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
+ private readonly workflowActionFactory: WorkflowActionFactory,
+ private readonly workflowExecutionContextService: WorkflowExecutionContextService,
+ private readonly findRecordsService: FindRecordsService,
+ @InjectMessageQueue(MessageQueue.workflowQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {}
+
+ async resolve({
+ workspaceId,
+ waitId,
+ event,
+ attempt = 0,
+ recordReadAttempt = 0,
+ }: ResumeWaitingWorkflowStepJobData): Promise<void> {
+ const pendingWait = await this.workflowStepWaitWorkspaceService.findWait({
+ workspaceId,
+ waitId,
+ });
+
+ if (!isDefined(pendingWait)) {
+ return;
+ }
+
+ const { workflowRunId, stepId } = pendingWait;
+
+ const workflowRun = await this.workflowRunWorkspaceService.getWorkflowRun({
+ workflowRunId,
+ workspaceId,
+ });
+ const stepStatus = workflowRun?.state?.stepInfos?.[stepId]?.status;
+ const isRunRunning = workflowRun?.status === WorkflowRunStatus.RUNNING;
+
+ // the wait is armed before its step reads as pending, so the event is held until it does or the run ends
+ if (isRunRunning && stepStatus === StepStatus.RUNNING) {
+ await this.workflowStepWaitWorkspaceService.scheduleResolution({
+ workspaceId,
+ workflowRunId,
+ waitId,
+ event,
+ attempt: attempt + 1,
+ delayMs: computeRetryDelayMs(attempt),
+ });
+
+ return;
+ }
+
+ let readableEvent = event;
+
+ // a record the run cannot read must not resume it, so the wait goes on for another event
+ if (isRunRunning && stepStatus === StepStatus.PENDING && isDefined(event)) {
+ const recordRead = await this.readRecordAsRun({
+ workspaceId,
+ workflowRunId,
+ event,
+ });
+
+ // a failed read cannot tell a transient error from an object the run cannot read, so it is retried a few times
+ if (recordRead.status === 'FAILED') {
+ if (recordReadAttempt < RECORD_READ_MAX_ATTEMPTS) {
+ await this.workflowStepWaitWorkspaceService.scheduleResolution({
+ workspaceId,
+ workflowRunId,
+ waitId,
+ event,
+ recordReadAttempt: recordReadAttempt + 1,
+ delayMs: computeRetryDelayMs(recordReadAttempt),
+ });
+ } else {
+ this.logger.warn(
+ `Wait ${waitId} of workflow run ${workflowRunId} kept waiting after its ${event.eventName} record could not be read: ${recordRead.error}`,
+ );
+ }
+
+ return;
+ }
+
+ if (recordRead.status === 'UNREADABLE') {
+ return;
+ }
+
+ readableEvent = restrictWaitEventToReadableRecord({
+ event,
+ readableRecord: recordRead.record,
+ });
+ }
+
+ const claimedWait = await this.workflowStepWaitWorkspaceService.claim({
+ workspaceId,
+ waitId,
+ });
+
+ if (!isDefined(claimedWait) || !isDefined(workflowRun)) {
+ return;
+ }
+
+ // the claimed wait is gone, so a step that cannot resume would wait forever
+ try {
+ await this.resolveClaimedWait({
+ claimedWait,
+ workflowRun,
+ workspaceId,
+ event: readableEvent,
+ });
+ } catch (error) {
+ await this.workflowRunWorkspaceService.endWorkflowRun({
+ workflowRunId,
+ workspaceId,
+ status: WorkflowRunStatus.FAILED,
+ error: `A waiting step could not resume: ${error instanceof Error ? error.message : String(error)}`,
+ isSystemError: true,
+ });
+
+ throw error;
+ }
+ }
+
+ private async resolveClaimedWait({
+ claimedWait,
+ workflowRun,
+ workspaceId,
+ event,
+ }: {
+ claimedWait: WorkflowStepWaitEntity;
+ workflowRun: WorkflowRunWorkspaceEntity;
+ workspaceId: string;
+ event?: WorkflowWaitEvent;
+ }): Promise<void> {
+ const { workflowRunId, stepId } = claimedWait;
+
+ const step = workflowRun.state?.flow?.steps?.find(
+ (candidate) => candidate.id === stepId,
+ );
+ const stepInfo = workflowRun.state?.stepInfos?.[stepId];
+
+ if (
+ workflowRun.status !== WorkflowRunStatus.RUNNING ||
+ !isDefined(step) ||
+ stepInfo?.status !== StepStatus.PENDING
+ ) {
+ return;
+ }
+
+ const outcome = buildWaitOutcome({ wait: claimedWait.wait, event });
+ const workflowAction = this.workflowActionFactory.get(step.type);
+
+ const resolution = isDefined(workflowAction.resolveWait)
+ ? await workflowAction.resolveWait({
+ step,
+ stepInfo,
+ outcome,
+ runInfo: { workflowRunId, workspaceId },
+ })
+ : { result: buildDefaultWaitResult(outcome) };
+
+ if ('resumedThreadId' in resolution) {
+ await this.enqueueRunWorkflowJob({
+ workspaceId,
+ workflowRunId,
+ stepToResume: { stepId, threadId: resolution.resumedThreadId },
+ });
+
+ return;
+ }
+
+ const hasCompletedStep =
+ await this.workflowRunWorkspaceService.updateStepInfoIfPending({
+ stepId,
+ stepInfo: { status: StepStatus.SUCCESS, result: resolution.result },
+ workflowRunId,
+ workspaceId,
+ });
+
+ if (hasCompletedStep) {
+ await this.enqueueRunWorkflowJob({
+ workspaceId,
+ workflowRunId,
+ lastExecutedStepId: stepId,
+ });
+ }
+ }
+
+ private async readRecordAsRun({
+ workspaceId,
+ workflowRunId,
+ event,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ event: WorkflowWaitEvent;
+ }): Promise<RunRecordRead> {
+ const [objectName, action] = event.eventName.split('.');
+
+ const { authContext, rolePermissionConfig } =
+ await this.workflowExecutionContextService.getExecutionContext({
+ workflowRunId,
+ workspaceId,
+ });
+
+ const { success, result, error } = await this.findRecordsService.execute({
+ objectName,
+ // a deleted record only reads when the filter asks for deleted records
+ filter:
+ action === 'deleted'
+ ? { id: { eq: event.recordId }, deletedAt: { is: 'NOT_NULL' } }
+ : { id: { eq: event.recordId } },
+ limit: 1,
+ authContext,
+ rolePermissionConfig,
+ shouldBuildEffectiveSelectFields: false,
+ });
+
+ if (!success) {
+ return { status: 'FAILED', error };
+ }
+
+ const record = result?.records[0];
+
+ return isPlainObject(record)
+ ? { status: 'READABLE', record }
+ : { status: 'UNREADABLE' };
+ }
+
+ private async enqueueRunWorkflowJob(
+ jobData: RunWorkflowJobData,
+ ): Promise<void> {
+ await this.messageQueueService.add<RunWorkflowJobData>(
+ RUN_WORKFLOW_JOB_NAME,
+ jobData,
+ buildRunWorkflowJobOptions(jobData.workflowRunId),
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service.ts
new file mode 100644
index 00000000000..034d01b6a95
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service.ts
@@ -0,0 +1,187 @@
+import { Injectable } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+import { type WorkflowStepWait } from 'twenty-shared/workflow';
+import { v4 } from 'uuid';
+
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import { WorkflowStepWaitEntity } from 'src/engine/core-modules/workflow/entities/workflow-step-wait.entity';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { buildRunWorkflowJobOptions } from 'src/modules/workflow/workflow-runner/utils/build-run-workflow-job-options.util';
+import { RESUME_WAITING_WORKFLOW_STEP_JOB_NAME } from 'src/modules/workflow/workflow-wait/constants/resume-waiting-workflow-step-job-name.constant';
+import { type ResumeWaitingWorkflowStepJobData } from 'src/modules/workflow/workflow-wait/types/resume-waiting-workflow-step-job-data.type';
+
+@Injectable()
+export class WorkflowStepWaitWorkspaceService {
+ constructor(
+ @InjectWorkspaceScopedRepository(WorkflowStepWaitEntity)
+ private readonly workflowStepWaitRepository: WorkspaceScopedRepository<WorkflowStepWaitEntity>,
+ @InjectMessageQueue(MessageQueue.delayedJobsQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {}
+
+ // An answer wait is resolved through the step's conversation, so it is not stored
+ async arm({
+ workspaceId,
+ workflowRunId,
+ stepId,
+ wait,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ stepId: string;
+ wait: WorkflowStepWait;
+ }): Promise<void> {
+ if (wait.type === 'ANSWER') {
+ return;
+ }
+
+ const resumeAt =
+ wait.type === 'TIME'
+ ? new Date(wait.resumeAt)
+ : isDefined(wait.expiresAt)
+ ? new Date(wait.expiresAt)
+ : null;
+
+ // A step waiting again, in a loop or a retry, replaces its previous wait in one statement.
+ // The fresh id leaves stale jobs of the previous wait nothing to claim
+ const waitId = v4();
+
+ await this.workflowStepWaitRepository.upsert(
+ workspaceId,
+ {
+ id: waitId,
+ workflowRunId,
+ stepId,
+ wait,
+ eventName: wait.type === 'EVENT' ? wait.eventName : null,
+ resumeAt,
+ },
+ ['workflowRunId', 'stepId'],
+ );
+
+ if (!isDefined(resumeAt)) {
+ return;
+ }
+
+ await this.scheduleResolution({
+ workspaceId,
+ workflowRunId,
+ waitId,
+ delayMs: resumeAt.getTime() - Date.now(),
+ });
+ }
+
+ async scheduleResolution({
+ workspaceId,
+ workflowRunId,
+ waitId,
+ event,
+ attempt,
+ recordReadAttempt,
+ delayMs = 0,
+ }: Omit<ResumeWaitingWorkflowStepJobData, 'workspaceId' | 'waitId'> & {
+ workspaceId: string;
+ workflowRunId: string;
+ waitId: string;
+ delayMs?: number;
+ }): Promise<void> {
+ await this.messageQueueService.add<ResumeWaitingWorkflowStepJobData>(
+ RESUME_WAITING_WORKFLOW_STEP_JOB_NAME,
+ { workspaceId, waitId, event, attempt, recordReadAttempt },
+ {
+ ...buildRunWorkflowJobOptions(workflowRunId),
+ delay: Math.max(delayMs, 0),
+ },
+ );
+ }
+
+ // A wait stays overdue until its job claims it, so each sweep would queue it again
+ async scheduleOverdueResolution({
+ workspaceId,
+ workflowRunId,
+ waitId,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ waitId: string;
+ }): Promise<void> {
+ await this.messageQueueService.add<ResumeWaitingWorkflowStepJobData>(
+ RESUME_WAITING_WORKFLOW_STEP_JOB_NAME,
+ { workspaceId, waitId },
+ {
+ ...buildRunWorkflowJobOptions(workflowRunId),
+ deduplication: { id: `overdue-workflow-step-wait-${waitId}` },
+ },
+ );
+ }
+
+ async findWait({
+ workspaceId,
+ waitId,
+ }: {
+ workspaceId: string;
+ waitId: string;
+ }): Promise<WorkflowStepWaitEntity | null> {
+ return this.workflowStepWaitRepository.findOne(workspaceId, {
+ where: { id: waitId },
+ });
+ }
+
+ async claim({
+ workspaceId,
+ waitId,
+ }: {
+ workspaceId: string;
+ waitId: string;
+ }): Promise<WorkflowStepWaitEntity | null> {
+ const [claimedWait] = await this.workflowStepWaitRepository.deleteAndReturn(
+ workspaceId,
+ { id: waitId },
+ );
+
+ return claimedWait ?? null;
+ }
+
+ async findEventWaits({
+ workspaceId,
+ eventName,
+ }: {
+ workspaceId: string;
+ eventName: string;
+ }): Promise<WorkflowStepWaitEntity[]> {
+ return this.workflowStepWaitRepository.find(workspaceId, {
+ where: { eventName },
+ });
+ }
+
+ async cancelStepWait({
+ workspaceId,
+ workflowRunId,
+ stepId,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ stepId: string;
+ }): Promise<void> {
+ await this.workflowStepWaitRepository.delete(workspaceId, {
+ workflowRunId,
+ stepId,
+ });
+ }
+
+ async cancelRunWaits({
+ workspaceId,
+ workflowRunId,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ }): Promise<void> {
+ await this.workflowStepWaitRepository.delete(workspaceId, {
+ workflowRunId,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/types/resume-waiting-workflow-step-job-data.type.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/types/resume-waiting-workflow-step-job-data.type.ts
new file mode 100644
index 00000000000..caf8c56d8c3
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/types/resume-waiting-workflow-step-job-data.type.ts
@@ -0,0 +1,12 @@
+import { type WorkflowWaitEvent } from 'src/modules/workflow/workflow-wait/types/workflow-wait-event.type';
+
+export type ResumeWaitingWorkflowStepJobData = {
+ workspaceId: string;
+ waitId: string;
+ // Absent when the wait's time came: a time wait elapsed or an event wait expired
+ event?: WorkflowWaitEvent;
+ // How many times the resolution was put off because the step was still pausing
+ attempt?: number;
+ // How many times reading the event's record as the run failed
+ recordReadAttempt?: number;
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-event.type.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-event.type.ts
new file mode 100644
index 00000000000..658ac4f1d19
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-event.type.ts
@@ -0,0 +1,8 @@
+export type WorkflowWaitEvent = {
+ eventName: string;
+ recordId: string;
+ // The record after the event, or before it when it was deleted
+ record: Record<string, unknown>;
+ before?: Record<string, unknown>;
+ updatedFields?: string[];
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-outcome.type.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-outcome.type.ts
new file mode 100644
index 00000000000..b0bf234d529
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-outcome.type.ts
@@ -0,0 +1,6 @@
+import { type WorkflowWaitEvent } from 'src/modules/workflow/workflow-wait/types/workflow-wait-event.type';
+
+export type WorkflowWaitOutcome =
+ | { type: 'TIME_ELAPSED' }
+ | { type: 'EVENT_RECEIVED'; event: WorkflowWaitEvent }
+ | { type: 'EXPIRED' };
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-resolution-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-resolution-input.type.ts
new file mode 100644
index 00000000000..f88a23d35e2
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-resolution-input.type.ts
@@ -0,0 +1,12 @@
+import { type WorkflowRunStepInfo } from 'twenty-shared/workflow';
+
+import { type WorkflowRunInfo } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+import { type WorkflowWaitOutcome } from 'src/modules/workflow/workflow-wait/types/workflow-wait-outcome.type';
+
+export type WorkflowWaitResolutionInput = {
+ step: WorkflowAction;
+ stepInfo: WorkflowRunStepInfo;
+ outcome: WorkflowWaitOutcome;
+ runInfo: WorkflowRunInfo;
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-resolution.type.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-resolution.type.ts
new file mode 100644
index 00000000000..66a157bac9c
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/types/workflow-wait-resolution.type.ts
@@ -0,0 +1,4 @@
+export type WorkflowWaitResolution =
+ | { result: object }
+ // The step runs again on its conversation, where it recorded the outcome
+ | { resumedThreadId: string };
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/utils/__tests__/build-wait-outcome.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/__tests__/build-wait-outcome.util.spec.ts
new file mode 100644
index 00000000000..adc70aec149
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/__tests__/build-wait-outcome.util.spec.ts
@@ -0,0 +1,55 @@
+import { buildDefaultWaitResult } from 'src/modules/workflow/workflow-wait/utils/build-default-wait-result.util';
+import { buildWaitOutcome } from 'src/modules/workflow/workflow-wait/utils/build-wait-outcome.util';
+
+const EVENT = {
+ eventName: 'company.updated',
+ recordId: 'company-id',
+ record: { id: 'company-id', name: 'Acme' },
+};
+
+describe('buildWaitOutcome', () => {
+ it('reports an event when one resolved the wait', () => {
+ expect(
+ buildWaitOutcome({
+ wait: { type: 'EVENT', eventName: 'company.updated' },
+ event: EVENT,
+ }),
+ ).toEqual({ type: 'EVENT_RECEIVED', event: EVENT });
+ });
+
+ it('reports elapsed time for a time wait', () => {
+ expect(
+ buildWaitOutcome({
+ wait: { type: 'TIME', resumeAt: new Date().toISOString() },
+ }),
+ ).toEqual({ type: 'TIME_ELAPSED' });
+ });
+
+ it('reports an expiry for an event wait whose time came', () => {
+ expect(
+ buildWaitOutcome({
+ wait: { type: 'EVENT', eventName: 'company.updated' },
+ }),
+ ).toEqual({ type: 'EXPIRED' });
+ });
+});
+
+describe('buildDefaultWaitResult', () => {
+ it('keeps the delay result for elapsed time', () => {
+ expect(buildDefaultWaitResult({ type: 'TIME_ELAPSED' })).toEqual({
+ success: true,
+ });
+ });
+
+ it('exposes the event and that it did not time out', () => {
+ expect(
+ buildDefaultWaitResult({ type: 'EVENT_RECEIVED', event: EVENT }),
+ ).toEqual({ hasTimedOut: false, ...EVENT });
+ });
+
+ it('reports a timeout when the wait expired', () => {
+ expect(buildDefaultWaitResult({ type: 'EXPIRED' })).toEqual({
+ hasTimedOut: true,
+ });
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/utils/__tests__/does-event-match-wait.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/__tests__/does-event-match-wait.util.spec.ts
new file mode 100644
index 00000000000..efdd4464ece
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/__tests__/does-event-match-wait.util.spec.ts
@@ -0,0 +1,90 @@
+import { type ObjectRecordEvent } from 'twenty-shared/database-events';
+
+import { doesEventMatchWait } from 'src/modules/workflow/workflow-wait/utils/does-event-match-wait.util';
+
+const buildUpdateEvent = ({
+ recordId,
+ updatedFields,
+}: {
+ recordId: string;
+ updatedFields: string[];
+}) =>
+ ({
+ recordId,
+ properties: { before: {}, after: {}, updatedFields, diff: {} },
+ }) as unknown as ObjectRecordEvent;
+
+describe('doesEventMatchWait', () => {
+ it('matches any record when the wait names none', () => {
+ expect(
+ doesEventMatchWait({
+ wait: { type: 'EVENT', eventName: 'company.updated' },
+ event: buildUpdateEvent({ recordId: 'a', updatedFields: ['name'] }),
+ }),
+ ).toBe(true);
+ });
+
+ it('only matches the record the wait names', () => {
+ const wait = {
+ type: 'EVENT' as const,
+ eventName: 'company.updated',
+ recordId: 'a',
+ };
+
+ expect(
+ doesEventMatchWait({
+ wait,
+ event: buildUpdateEvent({ recordId: 'a', updatedFields: ['name'] }),
+ }),
+ ).toBe(true);
+ expect(
+ doesEventMatchWait({
+ wait,
+ event: buildUpdateEvent({ recordId: 'b', updatedFields: ['name'] }),
+ }),
+ ).toBe(false);
+ });
+
+ it('only matches updates that changed one of the watched fields', () => {
+ const wait = {
+ type: 'EVENT' as const,
+ eventName: 'company.updated',
+ updatedFields: ['stage'],
+ };
+
+ expect(
+ doesEventMatchWait({
+ wait,
+ event: buildUpdateEvent({ recordId: 'a', updatedFields: ['stage'] }),
+ }),
+ ).toBe(true);
+ expect(
+ doesEventMatchWait({
+ wait,
+ event: buildUpdateEvent({ recordId: 'a', updatedFields: ['name'] }),
+ }),
+ ).toBe(false);
+ });
+
+ it('does not match a field-filtered wait on an event that reports no changed fields', () => {
+ expect(
+ doesEventMatchWait({
+ wait: {
+ type: 'EVENT',
+ eventName: 'company.updated',
+ updatedFields: ['stage'],
+ },
+ event: buildUpdateEvent({ recordId: 'a', updatedFields: [] }),
+ }),
+ ).toBe(false);
+ });
+
+ it('never matches a wait that is not on an event', () => {
+ expect(
+ doesEventMatchWait({
+ wait: { type: 'TIME', resumeAt: new Date().toISOString() },
+ event: buildUpdateEvent({ recordId: 'a', updatedFields: [] }),
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/utils/__tests__/restrict-wait-event-to-readable-record.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/__tests__/restrict-wait-event-to-readable-record.util.spec.ts
new file mode 100644
index 00000000000..04bac807c76
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/__tests__/restrict-wait-event-to-readable-record.util.spec.ts
@@ -0,0 +1,43 @@
+import { restrictWaitEventToReadableRecord } from 'src/modules/workflow/workflow-wait/utils/restrict-wait-event-to-readable-record.util';
+
+describe('restrictWaitEventToReadableRecord', () => {
+ it('drops the fields the run cannot read from every part of the event', () => {
+ expect(
+ restrictWaitEventToReadableRecord({
+ event: {
+ eventName: 'company.updated',
+ recordId: 'company-id',
+ record: { id: 'company-id', name: 'Acme', secret: 'new' },
+ before: { id: 'company-id', name: 'Old Acme', secret: 'old' },
+ updatedFields: ['name', 'secret'],
+ },
+ readableRecord: { id: 'company-id', name: 'Acme' },
+ }),
+ ).toEqual({
+ eventName: 'company.updated',
+ recordId: 'company-id',
+ record: { id: 'company-id', name: 'Acme' },
+ before: { id: 'company-id', name: 'Old Acme' },
+ updatedFields: ['name'],
+ });
+ });
+
+ it('leaves an event without a previous snapshot without one', () => {
+ expect(
+ restrictWaitEventToReadableRecord({
+ event: {
+ eventName: 'company.created',
+ recordId: 'company-id',
+ record: { id: 'company-id', secret: 'new' },
+ },
+ readableRecord: { id: 'company-id' },
+ }),
+ ).toEqual({
+ eventName: 'company.created',
+ recordId: 'company-id',
+ record: { id: 'company-id' },
+ before: undefined,
+ updatedFields: undefined,
+ });
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/utils/build-default-wait-result.util.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/build-default-wait-result.util.ts
new file mode 100644
index 00000000000..802e4daf091
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/build-default-wait-result.util.ts
@@ -0,0 +1,14 @@
+import { type WorkflowWaitOutcome } from 'src/modules/workflow/workflow-wait/types/workflow-wait-outcome.type';
+
+export const buildDefaultWaitResult = (
+ outcome: WorkflowWaitOutcome,
+): object => {
+ switch (outcome.type) {
+ case 'TIME_ELAPSED':
+ return { success: true };
+ case 'EVENT_RECEIVED':
+ return { hasTimedOut: false, ...outcome.event };
+ case 'EXPIRED':
+ return { hasTimedOut: true };
+ }
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/utils/build-wait-outcome.util.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/build-wait-outcome.util.ts
new file mode 100644
index 00000000000..e8937ab6c38
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/build-wait-outcome.util.ts
@@ -0,0 +1,19 @@
+import { isDefined } from 'twenty-shared/utils';
+import { type WorkflowStepWait } from 'twenty-shared/workflow';
+
+import { type WorkflowWaitEvent } from 'src/modules/workflow/workflow-wait/types/workflow-wait-event.type';
+import { type WorkflowWaitOutcome } from 'src/modules/workflow/workflow-wait/types/workflow-wait-outcome.type';
+
+export const buildWaitOutcome = ({
+ wait,
+ event,
+}: {
+ wait: WorkflowStepWait;
+ event?: WorkflowWaitEvent;
+}): WorkflowWaitOutcome => {
+ if (isDefined(event)) {
+ return { type: 'EVENT_RECEIVED', event };
+ }
+
+ return wait.type === 'TIME' ? { type: 'TIME_ELAPSED' } : { type: 'EXPIRED' };
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/utils/build-workflow-wait-event.util.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/build-workflow-wait-event.util.ts
new file mode 100644
index 00000000000..3b4b7c5407d
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/build-workflow-wait-event.util.ts
@@ -0,0 +1,29 @@
+import { type ObjectRecordEvent } from 'twenty-shared/database-events';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type WorkflowWaitEvent } from 'src/modules/workflow/workflow-wait/types/workflow-wait-event.type';
+
+export const buildWorkflowWaitEvent = ({
+ eventName,
+ event,
+}: {
+ eventName: string;
+ event: ObjectRecordEvent;
+}): WorkflowWaitEvent => {
+ // every event shape carries a subset of these
+ const { before, after, updatedFields } = event.properties as {
+ before?: object;
+ after?: object;
+ updatedFields?: string[];
+ };
+
+ return {
+ eventName,
+ recordId: event.recordId,
+ record: (after ?? before ?? {}) as Record<string, unknown>,
+ ...(isDefined(after) && isDefined(before)
+ ? { before: before as Record<string, unknown> }
+ : {}),
+ ...(isDefined(updatedFields) ? { updatedFields } : {}),
+ };
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/utils/does-event-match-wait.util.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/does-event-match-wait.util.ts
new file mode 100644
index 00000000000..fde1601be9a
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/does-event-match-wait.util.ts
@@ -0,0 +1,32 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type ObjectRecordEvent } from 'twenty-shared/database-events';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { type WorkflowStepWait } from 'twenty-shared/workflow';
+
+export const doesEventMatchWait = ({
+ wait,
+ event,
+}: {
+ wait: WorkflowStepWait;
+ event: ObjectRecordEvent;
+}): boolean => {
+ if (wait.type !== 'EVENT') {
+ return false;
+ }
+
+ if (isNonEmptyString(wait.recordId) && wait.recordId !== event.recordId) {
+ return false;
+ }
+
+ if (!isNonEmptyArray(wait.updatedFields)) {
+ return true;
+ }
+
+ // like database event triggers, a field filter only matches events that report which fields changed
+ const eventUpdatedFields =
+ 'updatedFields' in event.properties
+ ? (event.properties.updatedFields ?? [])
+ : [];
+
+ return wait.updatedFields.some((field) => eventUpdatedFields.includes(field));
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/utils/restrict-wait-event-to-readable-record.util.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/restrict-wait-event-to-readable-record.util.ts
new file mode 100644
index 00000000000..74337e37a42
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/utils/restrict-wait-event-to-readable-record.util.ts
@@ -0,0 +1,29 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type WorkflowWaitEvent } from 'src/modules/workflow/workflow-wait/types/workflow-wait-event.type';
+
+// The record read under the run's permissions only holds the fields the run can read
+export const restrictWaitEventToReadableRecord = ({
+ event,
+ readableRecord,
+}: {
+ event: WorkflowWaitEvent;
+ readableRecord: Record<string, unknown>;
+}): WorkflowWaitEvent => {
+ const readableFieldNames = new Set(Object.keys(readableRecord));
+ const isReadableField = (fieldName: string) =>
+ readableFieldNames.has(fieldName);
+
+ return {
+ ...event,
+ record: readableRecord,
+ before: isDefined(event.before)
+ ? Object.fromEntries(
+ Object.entries(event.before).filter(([fieldName]) =>
+ isReadableField(fieldName),
+ ),
+ )
+ : undefined,
+ updatedFields: event.updatedFields?.filter(isReadableField),
+ };
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/workflow-step-wait-store.module.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/workflow-step-wait-store.module.ts
new file mode 100644
index 00000000000..bb6234b0a80
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/workflow-step-wait-store.module.ts
@@ -0,0 +1,16 @@
+import { Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
+
+import { WorkflowStepWaitEntity } from 'src/engine/core-modules/workflow/entities/workflow-step-wait.entity';
+import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
+import { WorkflowStepWaitWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service';
+
+@Module({
+ imports: [TypeOrmModule.forFeature([WorkflowStepWaitEntity])],
+ providers: [
+ WorkflowStepWaitWorkspaceService,
+ provideWorkspaceScopedRepository(WorkflowStepWaitEntity),
+ ],
+ exports: [WorkflowStepWaitWorkspaceService],
+})
+export class WorkflowStepWaitStoreModule {}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-wait/workflow-wait.module.ts b/packages/twenty-server/src/modules/workflow/workflow-wait/workflow-wait.module.ts
new file mode 100644
index 00000000000..bc2c9a7213c
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-wait/workflow-wait.module.ts
@@ -0,0 +1,35 @@
+import { Module } from '@nestjs/common';
+
+import { RecordCrudModule } from 'src/engine/core-modules/record-crud/record-crud.module';
+import { RecordShareModule } from 'src/engine/core-modules/record-share/record-share.module';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+import { WorkflowExecutionContextModule } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.module';
+import { WorkflowExecutorModule } from 'src/modules/workflow/workflow-executor/workflow-executor.module';
+import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
+import { WorkflowStepWaitSweepCronCommand } from 'src/modules/workflow/workflow-wait/crons/commands/workflow-step-wait-sweep.cron.command';
+import { WorkflowStepWaitSweepCronJob } from 'src/modules/workflow/workflow-wait/crons/jobs/workflow-step-wait-sweep.cron.job';
+import { ResumeWaitingWorkflowStepJob } from 'src/modules/workflow/workflow-wait/jobs/resume-waiting-workflow-step.job';
+import { WorkflowStepWaitDatabaseEventListener } from 'src/modules/workflow/workflow-wait/listeners/workflow-step-wait-database-event.listener';
+import { WorkflowStepWaitResolverWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait-resolver.workspace-service';
+import { WorkflowStepWaitStoreModule } from 'src/modules/workflow/workflow-wait/workflow-step-wait-store.module';
+
+@Module({
+ imports: [
+ WorkflowStepWaitStoreModule,
+ WorkflowExecutorModule,
+ WorkflowRunModule,
+ RecordShareModule,
+ WorkspaceCacheModule,
+ WorkflowExecutionContextModule,
+ RecordCrudModule,
+ ],
+ providers: [
+ WorkflowStepWaitResolverWorkspaceService,
+ ResumeWaitingWorkflowStepJob,
+ WorkflowStepWaitDatabaseEventListener,
+ WorkflowStepWaitSweepCronJob,
+ WorkflowStepWaitSweepCronCommand,
+ ],
+ exports: [WorkflowStepWaitSweepCronCommand],
+})
+export class WorkflowWaitModule {}
diff --git a/packages/twenty-server/src/modules/workflow/workflow.module.ts b/packages/twenty-server/src/modules/workflow/workflow.module.ts
index 1cc76b601e5..54238b36ad9 100644
--- a/packages/twenty-server/src/modules/workflow/workflow.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow.module.ts
@@ -3,12 +3,14 @@ import { Module } from '@nestjs/common';
import { WorkflowCoreSyncModule } from 'src/modules/workflow/workflow-core-sync/workflow-core-sync.module';
import { WorkflowStatusModule } from 'src/modules/workflow/workflow-status/workflow-status.module';
import { WorkflowTriggerModule } from 'src/modules/workflow/workflow-trigger/workflow-trigger.module';
+import { WorkflowWaitModule } from 'src/modules/workflow/workflow-wait/workflow-wait.module';
@Module({
imports: [
WorkflowTriggerModule,
WorkflowStatusModule,
WorkflowCoreSyncModule,
+ WorkflowWaitModule,
],
})
export class WorkflowModule {}
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
new file mode 100644
index 00000000000..af9520ecba3
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/wait-for-event-workflow.integration-spec.ts
@@ -0,0 +1,448 @@
+import request from 'supertest';
+import {
+ destroyWorkflowRun,
+ 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 { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { v4 } from 'uuid';
+
+import { type WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { type WorkflowCommonWorkspaceService } from 'src/modules/workflow/common/workspace-services/workflow-common.workspace-service';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import {
+ type WorkflowAction,
+ type WorkflowWaitForEventAction,
+} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+import { type WorkflowStepWaitDatabaseEventListener } from 'src/modules/workflow/workflow-wait/listeners/workflow-step-wait-database-event.listener';
+import { type WorkflowStepWaitResolverWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait-resolver.workspace-service';
+import { type WorkflowStepWaitWorkspaceService } from 'src/modules/workflow/workflow-wait/services/workflow-step-wait.workspace-service';
+
+const client = request(`http://localhost:${APP_PORT}`);
+
+const schema = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+const MIRROR_POLL_ATTEMPTS = 20;
+const MIRROR_POLL_INTERVAL_MS = 250;
+
+const graphql = (query: string, variables?: object) =>
+ client
+ .post('/graphql')
+ .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
+ .send({ query, variables });
+
+const buildCompanyUpdatedBatch = async (companyId: string) => ({
+ name: 'company.updated',
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ objectMetadata: (
+ await getAppProviderByClassName<WorkflowCommonWorkspaceService>(
+ 'WorkflowCommonWorkspaceService',
+ ).getObjectMetadataInfo('company', SEED_APPLE_WORKSPACE_ID)
+ ).flatObjectMetadata,
+ events: [
+ {
+ recordId: companyId,
+ properties: {
+ before: { id: companyId, name: 'Before' },
+ after: { id: companyId, name: 'After' },
+ updatedFields: ['name'],
+ diff: { name: { before: 'Before', after: 'After' } },
+ },
+ },
+ ],
+});
+
+describe('Wait for event workflow (e2e)', () => {
+ let createdWorkflowId: string | null = null;
+ let createdWorkflowVersionId: string | null = null;
+ let createdWorkflowRunId: string | null = null;
+ let waitStepId: string | null = null;
+ let watchedCompanyId: string | null = null;
+ let otherCompanyId: string | null = null;
+
+ const getSteps = async (): Promise<WorkflowAction[]> => {
+ const response = await graphql(
+ `
+ query GetWorkflowVersion($id: UUID!) {
+ workflowVersion(filter: { id: { eq: $id } }) {
+ steps
+ }
+ }
+ `,
+ { id: createdWorkflowVersionId },
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.workflowVersion.steps;
+ };
+
+ // the core mirror of a workflow and its version is linked asynchronously
+ const waitForCoreWorkflowMirror = async (): Promise<{
+ trigger: unknown;
+ coreWorkflowVersionId: string;
+ coreWorkflowId: string;
+ }> => {
+ for (let attempt = 0; attempt < MIRROR_POLL_ATTEMPTS; attempt++) {
+ const [version] = await global.testDataSource.query(
+ `SELECT trigger, "coreWorkflowVersionId" FROM "${schema}"."workflowVersion" WHERE id = $1`,
+ [createdWorkflowVersionId],
+ );
+ const [workflow] = await global.testDataSource.query(
+ `SELECT "coreWorkflowId" FROM "${schema}".workflow WHERE id = $1`,
+ [createdWorkflowId],
+ );
+
+ if (version?.coreWorkflowVersionId && workflow?.coreWorkflowId) {
+ return {
+ trigger: version.trigger,
+ coreWorkflowVersionId: version.coreWorkflowVersionId,
+ coreWorkflowId: workflow.coreWorkflowId,
+ };
+ }
+
+ await new Promise((resolve) =>
+ setTimeout(resolve, MIRROR_POLL_INTERVAL_MS),
+ );
+ }
+
+ throw new Error('The workflow core mirror was never linked');
+ };
+
+ const createCompany = async (name: string): Promise<string> => {
+ const response = await graphql(
+ `
+ mutation CreateCompany($data: CompanyCreateInput!) {
+ createCompany(data: $data) {
+ id
+ }
+ }
+ `,
+ { data: { name } },
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.createCompany.id;
+ };
+
+ beforeAll(async () => {
+ watchedCompanyId = await createCompany('Wait For Event Watched Co');
+ otherCompanyId = await createCompany('Wait For Event Other Co');
+
+ const createWorkflowResponse = await graphql(`
+ mutation CreateWorkflow {
+ createWorkflow(data: { name: "Wait For Event Workflow" }) {
+ id
+ }
+ }
+ `);
+
+ expect(createWorkflowResponse.body.errors).toBeUndefined();
+ createdWorkflowId = createWorkflowResponse.body.data.createWorkflow.id;
+
+ const getWorkflowResponse = await graphql(
+ `
+ query GetWorkflow($id: UUID!) {
+ workflow(filter: { id: { eq: $id } }) {
+ versions {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ }
+ `,
+ { id: createdWorkflowId },
+ );
+
+ expect(getWorkflowResponse.body.errors).toBeUndefined();
+ createdWorkflowVersionId =
+ getWorkflowResponse.body.data.workflow.versions.edges[0].node.id;
+
+ const updateTriggerResponse = await updateWorkflowVersionTrigger({
+ workflowVersionId: createdWorkflowVersionId!,
+ trigger: {
+ name: 'Manual Trigger',
+ type: 'MANUAL',
+ settings: { outputSchema: {} },
+ nextStepIds: [],
+ position: { x: 0, y: 0 },
+ },
+ });
+
+ expect(updateTriggerResponse.body.errors).toBeUndefined();
+
+ const createStepResponse = await graphql(
+ `
+ mutation CreateWorkflowVersionStep(
+ $input: CreateWorkflowVersionStepInput!
+ ) {
+ createWorkflowVersionStep(input: $input) {
+ stepsDiff
+ }
+ }
+ `,
+ {
+ input: {
+ workflowVersionId: createdWorkflowVersionId,
+ stepType: 'WAIT_FOR_EVENT',
+ parentStepId: 'trigger',
+ position: { x: 200, y: 0 },
+ },
+ },
+ );
+
+ expect(createStepResponse.body.errors).toBeUndefined();
+
+ const waitStep = (await getSteps()).find(
+ (step): step is WorkflowWaitForEventAction =>
+ step.type === 'WAIT_FOR_EVENT',
+ );
+
+ expect(waitStep).toBeDefined();
+ waitStepId = waitStep!.id;
+
+ const updateStepResponse = await graphql(
+ `
+ mutation UpdateWorkflowVersionStep(
+ $input: UpdateWorkflowVersionStepInput!
+ ) {
+ updateWorkflowVersionStep(input: $input) {
+ id
+ }
+ }
+ `,
+ {
+ input: {
+ workflowVersionId: createdWorkflowVersionId,
+ step: {
+ ...waitStep!,
+ settings: {
+ ...waitStep!.settings,
+ input: {
+ eventName: 'company.updated',
+ recordId: watchedCompanyId,
+ timeout: null,
+ },
+ },
+ },
+ },
+ },
+ );
+
+ expect(updateStepResponse.body.errors).toBeUndefined();
+
+ const activateResponse = await graphql(
+ `
+ mutation ActivateWorkflowVersion($workflowVersionId: UUID!) {
+ activateWorkflowVersion(workflowVersionId: $workflowVersionId)
+ }
+ `,
+ { workflowVersionId: createdWorkflowVersionId },
+ );
+
+ expect(activateResponse.body.errors).toBeUndefined();
+ });
+
+ afterAll(async () => {
+ if (createdWorkflowRunId) {
+ await destroyWorkflowRun(createdWorkflowRunId);
+ }
+
+ if (createdWorkflowId) {
+ await graphql(
+ `
+ mutation DestroyWorkflow($id: ID!) {
+ destroyWorkflow(id: $id) {
+ id
+ }
+ }
+ `,
+ { id: createdWorkflowId },
+ );
+ }
+
+ for (const companyId of [watchedCompanyId, otherCompanyId]) {
+ if (companyId) {
+ await graphql(
+ `
+ mutation DestroyCompany($id: UUID!) {
+ destroyCompany(id: $id) {
+ id
+ }
+ }
+ `,
+ { id: companyId },
+ );
+ }
+ }
+ });
+
+ it('pauses on the event and resumes with the record once it happens', async () => {
+ const steps = await getSteps();
+ const { trigger, coreWorkflowVersionId, coreWorkflowId } =
+ await waitForCoreWorkflowMirror();
+
+ createdWorkflowRunId = v4();
+
+ const state = {
+ flow: { trigger, steps },
+ stepInfos: {
+ trigger: { status: 'NOT_STARTED', result: {} },
+ ...Object.fromEntries(
+ steps.map((step) => [step.id, { status: 'NOT_STARTED' }]),
+ ),
+ },
+ };
+
+ // Inserted directly so no start job is enqueued and the test drives the run
+ await global.testDataSource.query(
+ `INSERT INTO "${schema}"."workflowRun" (id, name, "workflowId", "workflowVersionId", "coreWorkflowId", "coreWorkflowVersionId", status, state, position, "enqueuedAt")
+ VALUES ($1, 'Wait for event run', $2, $3, $4, $5, 'ENQUEUED', $6, 0, now())`,
+ [
+ createdWorkflowRunId,
+ createdWorkflowId,
+ createdWorkflowVersionId,
+ coreWorkflowId,
+ coreWorkflowVersionId,
+ JSON.stringify(state),
+ ],
+ );
+ await getAppProviderByClassName<WorkflowRunRecordShareService>(
+ 'WorkflowRunRecordShareService',
+ ).syncRuns({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workflowRunIds: [createdWorkflowRunId],
+ });
+
+ await (
+ await global.workflowTestServices.runJob()
+ ).handle({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workflowRunId: createdWorkflowRunId,
+ });
+
+ const pendingRun = await getWorkflowRun(createdWorkflowRunId);
+
+ expect(pendingRun?.status).toBe('RUNNING');
+ expect(pendingRun?.state?.stepInfos?.[waitStepId!]).toMatchObject({
+ status: 'PENDING',
+ wait: {
+ type: 'EVENT',
+ eventName: 'company.updated',
+ recordId: watchedCompanyId,
+ },
+ });
+
+ const storedWaits = await global.testDataSource.query(
+ `SELECT id, "eventName" FROM core."workflowStepWait" WHERE "workflowRunId" = $1`,
+ [createdWorkflowRunId],
+ );
+
+ expect(storedWaits).toEqual([
+ { id: expect.any(String), eventName: 'company.updated' },
+ ]);
+
+ const listener =
+ getAppProviderByClassName<WorkflowStepWaitDatabaseEventListener>(
+ 'WorkflowStepWaitDatabaseEventListener',
+ );
+ const scheduleSpy = jest
+ .spyOn(
+ getAppProviderByClassName<WorkflowStepWaitWorkspaceService>(
+ 'WorkflowStepWaitWorkspaceService',
+ ),
+ 'scheduleResolution',
+ )
+ .mockResolvedValue(undefined);
+
+ await listener.handleObjectRecordUpdateEvent(
+ (await buildCompanyUpdatedBatch(otherCompanyId!)) as never,
+ );
+
+ expect(scheduleSpy).not.toHaveBeenCalled();
+
+ await listener.handleObjectRecordUpdateEvent(
+ (await buildCompanyUpdatedBatch(watchedCompanyId!)) as never,
+ );
+
+ expect(scheduleSpy).toHaveBeenCalledTimes(1);
+
+ const [{ waitId, event }] = scheduleSpy.mock.calls[0];
+
+ scheduleSpy.mockRestore();
+
+ await getAppProviderByClassName<WorkflowStepWaitResolverWorkspaceService>(
+ 'WorkflowStepWaitResolverWorkspaceService',
+ ).resolve({ workspaceId: SEED_APPLE_WORKSPACE_ID, waitId, event });
+
+ await (
+ await global.workflowTestServices.runJob()
+ ).handle({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workflowRunId: createdWorkflowRunId,
+ lastExecutedStepId: waitStepId!,
+ });
+
+ const completedRun = await getWorkflowRun(createdWorkflowRunId);
+
+ expect(completedRun?.status).toBe('COMPLETED');
+ expect(completedRun?.state?.stepInfos?.[waitStepId!]).toMatchObject({
+ status: 'SUCCESS',
+ result: {
+ hasTimedOut: false,
+ eventName: 'company.updated',
+ recordId: watchedCompanyId,
+ record: { id: watchedCompanyId, name: 'Wait For Event Watched Co' },
+ updatedFields: ['name'],
+ },
+ });
+
+ const remainingWaits = await global.testDataSource.query(
+ `SELECT id FROM core."workflowStepWait" WHERE "workflowRunId" = $1`,
+ [createdWorkflowRunId],
+ );
+
+ expect(remainingWaits).toEqual([]);
+ }, 60000);
+
+ it('replaces the wait of a step that waits again with one of a new id', async () => {
+ const workflowStepWaitWorkspaceService =
+ getAppProviderByClassName<WorkflowStepWaitWorkspaceService>(
+ 'WorkflowStepWaitWorkspaceService',
+ );
+ const workflowRunId = v4();
+ const arm = () =>
+ workflowStepWaitWorkspaceService.arm({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workflowRunId,
+ stepId: 'step-waiting-again',
+ wait: { type: 'EVENT', eventName: 'company.updated' },
+ });
+ const findWaits = (): Promise<{ id: string }[]> =>
+ global.testDataSource.query(
+ `SELECT id FROM core."workflowStepWait" WHERE "workflowRunId" = $1`,
+ [workflowRunId],
+ );
+
+ try {
+ await arm();
+ const [firstWait] = await findWaits();
+
+ await arm();
+ const waits = await findWaits();
+
+ expect(waits).toHaveLength(1);
+ expect(waits[0].id).not.toBe(firstWait.id);
+ } finally {
+ await workflowStepWaitWorkspaceService.cancelRunWaits({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workflowRunId,
+ });
+ }
+ });
+});
diff --git a/packages/twenty-shared/src/application/workflowStepManifestType.ts b/packages/twenty-shared/src/application/workflowStepManifestType.ts
index 6bc48fbcc0f..35dab052411 100644
--- a/packages/twenty-shared/src/application/workflowStepManifestType.ts
+++ b/packages/twenty-shared/src/application/workflowStepManifestType.ts
@@ -6,6 +6,7 @@ import { workflowHttpRequestActionSettingsSchema } from '@/workflow/schemas/http
import { workflowClassifyActionSettingsSchema } from '@/workflow/schemas/classify-action-settings-schema';
import { workflowIteratorActionSettingsSchema } from '@/workflow/schemas/iterator-action-settings-schema';
import { workflowDelayActionSettingsSchema } from '@/workflow/schemas/workflow-delay-action-settings-schema';
+import { workflowWaitForEventActionSettingsSchema } from '@/workflow/schemas/wait-for-event-action-settings-schema';
import { workflowEmptyActionSettingsSchema } from '@/workflow/schemas/empty-action-settings-schema';
import { baseWorkflowActionSettingsSchema } from '@/workflow/schemas/base-workflow-action-settings-schema';
import { workflowCreateRecordActionSettingsSchema } from '@/workflow/schemas/create-record-action-settings-schema';
@@ -61,6 +62,10 @@ export const workflowStepManifestSchema = z.discriminatedUnion('type', [
stepSchema('CLASSIFY', workflowClassifyActionSettingsSchema.shape.input),
stepSchema('ITERATOR', workflowIteratorActionSettingsSchema.shape.input),
stepSchema('DELAY', workflowDelayActionSettingsSchema.shape.input),
+ stepSchema(
+ 'WAIT_FOR_EVENT',
+ workflowWaitForEventActionSettingsSchema.shape.input,
+ ),
stepSchema('EMPTY', workflowEmptyActionSettingsSchema.shape.input),
stepSchema(
'CREATE_RECORD',
diff --git a/packages/twenty-shared/src/workflow/index.ts b/packages/twenty-shared/src/workflow/index.ts
index 42508445be0..11fda006408 100644
--- a/packages/twenty-shared/src/workflow/index.ts
+++ b/packages/twenty-shared/src/workflow/index.ts
@@ -99,6 +99,8 @@ export { workflowUpdateRecordActionSchema } from './schemas/update-record-action
export { workflowUpdateRecordActionSettingsSchema } from './schemas/update-record-action-settings-schema';
export { workflowUpsertRecordActionSchema } from './schemas/upsert-record-action-schema';
export { workflowUpsertRecordActionSettingsSchema } from './schemas/upsert-record-action-settings-schema';
+export { workflowWaitForEventActionSchema } from './schemas/wait-for-event-action-schema';
+export { workflowWaitForEventActionSettingsSchema } from './schemas/wait-for-event-action-settings-schema';
export { workflowWebhookTriggerSchema } from './schemas/webhook-trigger-schema';
export { workflowActionSchema } from './schemas/workflow-action-schema';
export { workflowDelayActionSchema } from './schemas/workflow-delay-action-schema';
@@ -114,6 +116,7 @@ export {
workflowRunStepLogsSchema,
} from './schemas/workflow-run-step-log-schema';
export { workflowRunStepStatusSchema } from './schemas/workflow-run-step-status-schema';
+export { workflowStepWaitSchema } from './schemas/workflow-step-wait-schema';
export { workflowTriggerSchema } from './schemas/workflow-trigger-schema';
export { workflowVariableReferenceSchema } from './schemas/workflow-variable-reference-schema';
export type { EmailRecipients } from './types/EmailRecipients';
@@ -143,6 +146,7 @@ export type {
AiAgentStepLogDetails,
AiToolCallLog,
} from './types/WorkflowRunStepLog';
+export type { WorkflowStepWait } from './types/WorkflowStepWait';
export { canObjectBeManagedByAutomation } from './utils/canObjectBeManagedByAutomation';
export { extractRawVariableNamePart } from './utils/extractRawVariableNameParts';
export { getFunctionInputFromInputSchema } from './utils/getFunctionInputFromInputSchema';
diff --git a/packages/twenty-shared/src/workflow/schemas/wait-for-event-action-schema.ts b/packages/twenty-shared/src/workflow/schemas/wait-for-event-action-schema.ts
new file mode 100644
index 00000000000..2210f5b2e15
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/schemas/wait-for-event-action-schema.ts
@@ -0,0 +1,10 @@
+import { z } from 'zod';
+import { baseWorkflowActionSchema } from './base-workflow-action-schema';
+import { workflowWaitForEventActionSettingsSchema } from './wait-for-event-action-settings-schema';
+
+export const workflowWaitForEventActionSchema = baseWorkflowActionSchema.extend(
+ {
+ type: z.literal('WAIT_FOR_EVENT'),
+ settings: workflowWaitForEventActionSettingsSchema,
+ },
+);
diff --git a/packages/twenty-shared/src/workflow/schemas/wait-for-event-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/wait-for-event-action-settings-schema.ts
new file mode 100644
index 00000000000..c40e0d0bdfe
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/schemas/wait-for-event-action-settings-schema.ts
@@ -0,0 +1,38 @@
+import { z } from 'zod';
+import { baseWorkflowActionSettingsSchema } from './base-workflow-action-settings-schema';
+
+export const workflowWaitForEventActionSettingsSchema =
+ baseWorkflowActionSettingsSchema.extend({
+ input: z.object({
+ eventName: z
+ .string()
+ .describe(
+ 'Event to wait for, in format objectName.action (e.g., "company.updated", "task.created", "person.deleted").',
+ ),
+ recordId: z
+ .string()
+ .nullable()
+ .optional()
+ .describe(
+ 'Only resume for this record. Usually a variable such as {{trigger.object.id}}. Leave empty to resume on any record.',
+ ),
+ updatedFields: z
+ .array(z.string())
+ .nullable()
+ .optional()
+ .describe(
+ 'For update events, only resume when one of these fields changed.',
+ ),
+ timeout: z
+ .object({
+ days: z.union([z.number().min(0), z.string()]).optional(),
+ hours: z.union([z.number().min(0), z.string()]).optional(),
+ minutes: z.union([z.number().min(0), z.string()]).optional(),
+ })
+ .nullable()
+ .optional()
+ .describe(
+ 'Stop waiting after this duration. The step then succeeds with hasTimedOut set to true.',
+ ),
+ }),
+ });
diff --git a/packages/twenty-shared/src/workflow/schemas/workflow-action-schema.ts b/packages/twenty-shared/src/workflow/schemas/workflow-action-schema.ts
index b89c5efc55f..7732a4816ff 100644
--- a/packages/twenty-shared/src/workflow/schemas/workflow-action-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/workflow-action-schema.ts
@@ -20,6 +20,7 @@ import { workflowSendEmailActionSchema } from './send-email-action-schema';
import { workflowUpdateRecordActionSchema } from './update-record-action-schema';
import { workflowUpsertRecordActionSchema } from './upsert-record-action-schema';
import { workflowDelayActionSchema } from './workflow-delay-action-schema';
+import { workflowWaitForEventActionSchema } from './wait-for-event-action-schema';
export const workflowActionSchema = z.discriminatedUnion('type', [
workflowCodeActionSchema,
@@ -42,5 +43,6 @@ export const workflowActionSchema = z.discriminatedUnion('type', [
workflowIfElseActionSchema,
workflowIteratorActionSchema,
workflowDelayActionSchema,
+ workflowWaitForEventActionSchema,
workflowEmptyActionSchema,
]);
diff --git a/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts b/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts
index 602a7c3c9f6..e801229823f 100644
--- a/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
import { workflowRunStepStatusSchema } from './workflow-run-step-status-schema';
+import { workflowStepWaitSchema } from './workflow-step-wait-schema';
export const workflowRunStateStepInfoSchema = z.object({
result: z.any().optional(),
@@ -8,6 +9,8 @@ export const workflowRunStateStepInfoSchema = z.object({
retryAttempt: z.number().optional(),
// The agent step's conversation, kept per history entry so each loop iteration's one stays reachable.
threadId: z.string().optional(),
+ // What a PENDING step waits on
+ wait: workflowStepWaitSchema.optional(),
get history() {
return z
.array(
diff --git a/packages/twenty-shared/src/workflow/schemas/workflow-step-wait-schema.ts b/packages/twenty-shared/src/workflow/schemas/workflow-step-wait-schema.ts
new file mode 100644
index 00000000000..2feffcc9499
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/schemas/workflow-step-wait-schema.ts
@@ -0,0 +1,14 @@
+import { z } from 'zod';
+
+export const workflowStepWaitSchema = z.discriminatedUnion('type', [
+ // resolved when someone answers the step's conversation
+ z.object({ type: z.literal('ANSWER') }),
+ z.object({ type: z.literal('TIME'), resumeAt: z.string() }),
+ z.object({
+ type: z.literal('EVENT'),
+ eventName: z.string(),
+ recordId: z.string().optional(),
+ updatedFields: z.array(z.string()).optional(),
+ expiresAt: z.string().optional(),
+ }),
+]);
diff --git a/packages/twenty-shared/src/workflow/types/WorkflowActionType.ts b/packages/twenty-shared/src/workflow/types/WorkflowActionType.ts
index b53b177bc60..e252c4bb68c 100644
--- a/packages/twenty-shared/src/workflow/types/WorkflowActionType.ts
+++ b/packages/twenty-shared/src/workflow/types/WorkflowActionType.ts
@@ -20,4 +20,5 @@ export enum WorkflowActionType {
ITERATOR = 'ITERATOR',
EMPTY = 'EMPTY',
DELAY = 'DELAY',
+ WAIT_FOR_EVENT = 'WAIT_FOR_EVENT',
}
diff --git a/packages/twenty-shared/src/workflow/types/WorkflowStepWait.ts b/packages/twenty-shared/src/workflow/types/WorkflowStepWait.ts
new file mode 100644
index 00000000000..e310433cfac
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/types/WorkflowStepWait.ts
@@ -0,0 +1,4 @@
+import { type workflowStepWaitSchema } from '@/workflow/schemas/workflow-step-wait-schema';
+import type z from 'zod';
+
+export type WorkflowStepWait = z.infer<typeof workflowStepWaitSchema>;