Skip to content

The open alternative to Salesforce, designed for AI.

Expose defineWorkflow in twenty-sdk (#27377)

Thomas Trompette90fb7fdd6a51
diff --git a/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.ts b/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.ts
index c573c23ffff..2539619d33c 100644
--- a/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.ts
+++ b/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.ts
@@ -343,6 +343,57 @@ export { compileApplicationTranslations } from './cli/utilities/translations/com
});
}, 60000);
+ it('matches a workflow definition and its validation errors', async () => {
+ const appPath = await copyFixture('minimal-app');
+ const writeWorkflow = (stepType: string) =>
+ writeFile(
+ join(appPath, 'my.workflow.ts'),
+ `import { defineWorkflow } from 'twenty-sdk/define';
+
+export default defineWorkflow({
+ universalIdentifier: 'e1e2e3e4-e5e6-4000-8000-000000000060',
+ name: 'My workflow',
+ version: {
+ trigger: {
+ universalIdentifier: 'e1e2e3e4-e5e6-4000-8000-000000000061',
+ type: 'MANUAL',
+ nextStepIds: ['e1e2e3e4-e5e6-4000-8000-000000000062'],
+ },
+ steps: [
+ {
+ universalIdentifier: 'e1e2e3e4-e5e6-4000-8000-000000000062',
+ name: 'Run my function',
+ type: '${stepType}',
+ logicFunctionUniversalIdentifier: 'e1e2e3e4-e5e6-4000-8000-000000000010',
+ input: {},
+ nextStepIds: [],
+ },
+ ],
+ },
+});
+`,
+ );
+
+ await writeWorkflow('LOGIC_FUNCTION');
+ const result = await compareManifest(appPath);
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.manifest.workflows).toHaveLength(1);
+ expect(result.filePaths.workflows).toEqual(['my.workflow.ts']);
+ }
+
+ await writeWorkflow('CODE');
+ const invalidResult = await compareManifest(appPath);
+
+ expect(invalidResult.success).toBe(false);
+ if (!invalidResult.success) {
+ expect(invalidResult.errors.join('\n')).toContain(
+ 'Unsupported step type',
+ );
+ }
+ }, 60000);
+
it('keeps evaluated source output and workspace credentials outside the manifest result', async () => {
const appPath = await copyFixture('minimal-app');
const applicationFiles = (await buildManifest(appPath)).filePaths
diff --git a/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts b/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
index 0f5645f2ef5..4ca6743fef3 100644
--- a/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
+++ b/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
@@ -399,6 +399,47 @@ describe('manifestValidate', () => {
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
+
+ it('should not read universalIdentifier keys inside workflow step payloads', () => {
+ const stepId = '550e8400-e29b-41d4-a716-446655440062';
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [validField],
+ workflows: [
+ {
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440060',
+ name: 'Workflow',
+ version: {
+ trigger: {
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440061',
+ type: 'MANUAL',
+ nextStepIds: [stepId],
+ },
+ steps: [
+ {
+ universalIdentifier: stepId,
+ name: 'Step',
+ type: 'LOGIC_FUNCTION',
+ logicFunctionUniversalIdentifier:
+ '550e8400-e29b-41d4-a716-446655440063',
+ input: {
+ universalIdentifier: 'customer-123',
+ field: {
+ universalIdentifier: validField.universalIdentifier,
+ },
+ },
+ nextStepIds: [],
+ },
+ ],
+ },
+ },
+ ],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
});
describe('relation field validation', () => {
diff --git a/packages/twenty-cli/src/app/manifest/manifest-build.ts b/packages/twenty-cli/src/app/manifest/manifest-build.ts
index 2be60ad7131..fae70113660 100644
--- a/packages/twenty-cli/src/app/manifest/manifest-build.ts
+++ b/packages/twenty-cli/src/app/manifest/manifest-build.ts
@@ -60,6 +60,7 @@ import {
type SettingsMenuItemManifest,
type TimelineActivityTypeManifest,
type ViewManifest,
+ type WorkflowManifest,
} from 'twenty-shared/application';
import { assertUnreachable, isDefined } from 'twenty-shared/utils';
@@ -109,6 +110,7 @@ export const buildManifest = async (
const roles: RoleManifest[] = [];
const skills: SkillManifest[] = [];
const agents: AgentManifest[] = [];
+ const workflows: WorkflowManifest[] = [];
const connectionProviders: ConnectionProviderManifest[] = [];
const logicFunctions: LogicFunctionManifest[] = [];
const frontComponents: FrontComponentManifest[] = [];
@@ -140,6 +142,7 @@ export const buildManifest = async (
const rolesFilePaths: string[] = [];
const skillsFilePaths: string[] = [];
const agentsFilePaths: string[] = [];
+ const workflowsFilePaths: string[] = [];
const connectionProvidersFilePaths: string[] = [];
const logicFunctionsFilePaths: string[] = [];
const frontComponentsFilePaths: string[] = [];
@@ -259,6 +262,17 @@ export const buildManifest = async (
agentsFilePaths.push(relativePath);
break;
}
+ case 'workflows': {
+ const extract = await extractManifestFromFile<WorkflowManifest>({
+ appPath,
+ filePath,
+ });
+ workflows.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ workflowsFilePaths.push(relativePath);
+ break;
+ }
case 'connectionProviders': {
const extract =
await extractManifestFromFile<ConnectionProviderManifest>({
@@ -689,6 +703,7 @@ export const buildManifest = async (
roles: roles.sort(byId),
skills: skills.sort(byId),
agents: agents.sort(byId),
+ workflows: workflows.sort(byId),
connectionProviders: connectionProviders.sort(byId),
logicFunctions: logicFunctions.sort(byId),
frontComponents: frontComponents.sort(byId),
@@ -713,6 +728,7 @@ export const buildManifest = async (
roles: rolesFilePaths,
skills: skillsFilePaths,
agents: agentsFilePaths,
+ workflows: workflowsFilePaths,
connectionProviders: connectionProvidersFilePaths,
logicFunctions: logicFunctionsFilePaths,
frontComponents: frontComponentsFilePaths,
diff --git a/packages/twenty-cli/src/app/manifest/manifest-validate.ts b/packages/twenty-cli/src/app/manifest/manifest-validate.ts
index 648921c5da5..3bd170019f0 100644
--- a/packages/twenty-cli/src/app/manifest/manifest-validate.ts
+++ b/packages/twenty-cli/src/app/manifest/manifest-validate.ts
@@ -69,7 +69,11 @@ const findUniversalIdentifiers = (obj: object): string[] => {
key === 'identifyAccountLogicFunction' ||
key === 'onConnectLogicFunction' ||
key === 'onDisconnectLogicFunction' ||
- key === 'settingsFrontComponent'
+ key === 'settingsFrontComponent' ||
+ key === 'input' ||
+ key === 'expectedBody' ||
+ key === 'outputSchema' ||
+ key === 'expectedOutputSchema'
) {
continue;
}
diff --git a/packages/twenty-cli/src/app/source/extract-define-entity.ts b/packages/twenty-cli/src/app/source/extract-define-entity.ts
index 2ac0f363f3e..80f0451442e 100644
--- a/packages/twenty-cli/src/app/source/extract-define-entity.ts
+++ b/packages/twenty-cli/src/app/source/extract-define-entity.ts
@@ -15,6 +15,7 @@ export const DEFINE_ENTITY_KEYS = {
defineRole: 'roles',
defineSkill: 'skills',
defineAgent: 'agents',
+ defineWorkflow: 'workflows',
defineConnectionProvider: 'connectionProviders',
defineFrontComponent: 'frontComponents',
defineSettingsFrontComponent: 'frontComponents',
diff --git a/packages/twenty-sdk/rollup.config.sdk-dts.mjs b/packages/twenty-sdk/rollup.config.sdk-dts.mjs
index d30f74ce425..f88a259884f 100644
--- a/packages/twenty-sdk/rollup.config.sdk-dts.mjs
+++ b/packages/twenty-sdk/rollup.config.sdk-dts.mjs
@@ -4,6 +4,9 @@ const external = (id) => {
if (id === 'twenty-shared' || id.startsWith('twenty-shared/')) {
return false;
}
+ if (id === 'zod' || id.startsWith('zod/')) {
+ return false;
+ }
if (id.startsWith('@/')) {
return false;
}
diff --git a/packages/twenty-sdk/src/cli/__tests__/apps/minimal-app/__integration__/app-dev/expected-manifest.ts b/packages/twenty-sdk/src/cli/__tests__/apps/minimal-app/__integration__/app-dev/expected-manifest.ts
index 1f8a1374d60..4515d5d9632 100644
--- a/packages/twenty-sdk/src/cli/__tests__/apps/minimal-app/__integration__/app-dev/expected-manifest.ts
+++ b/packages/twenty-sdk/src/cli/__tests__/apps/minimal-app/__integration__/app-dev/expected-manifest.ts
@@ -3,6 +3,7 @@ import type { Manifest } from 'twenty-shared/application';
import { FieldMetadataType, HTTPMethod } from 'twenty-shared/types';
export const EXPECTED_MANIFEST: Manifest = {
+ workflows: [],
commandMenuItems: [],
timelineActivityTypes: [],
settingsMenuItems: [],
diff --git a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/expected-manifest.ts b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/expected-manifest.ts
index a117b331792..1fd7c44bc69 100644
--- a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/expected-manifest.ts
+++ b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/expected-manifest.ts
@@ -17,6 +17,7 @@ import {
} from 'twenty-shared/types';
export const EXPECTED_MANIFEST: Manifest = {
+ workflows: [],
timelineActivityTypes: [
{
universalIdentifier: 'f4fa646c-6e11-4d8f-a6be-c3b7a2fc7500',
diff --git a/packages/twenty-sdk/src/cli/__tests__/bundle/__integration__/define-type-declarations.integration.spec.ts b/packages/twenty-sdk/src/cli/__tests__/bundle/__integration__/define-type-declarations.integration.spec.ts
new file mode 100644
index 00000000000..6aba172a6ca
--- /dev/null
+++ b/packages/twenty-sdk/src/cli/__tests__/bundle/__integration__/define-type-declarations.integration.spec.ts
@@ -0,0 +1,25 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const currentDir = dirname(fileURLToPath(import.meta.url));
+const packageRoot = resolve(currentDir, '../../../../..');
+const defineDeclarationsPath = resolve(packageRoot, 'dist/define/index.d.ts');
+const isBundleBuilt = existsSync(defineDeclarationsPath);
+
+describe('define type declarations', () => {
+ const runOrSkip = isBundleBuilt || process.env.CI ? it : it.skip;
+
+ runOrSkip('type defineWorkflow without requiring apps to install zod', () => {
+ if (!isBundleBuilt) {
+ throw new Error(
+ `Expected the built declarations at ${defineDeclarationsPath}. Run \`npx nx build twenty-sdk\` before this test.`,
+ );
+ }
+
+ const defineDeclarations = readFileSync(defineDeclarationsPath, 'utf8');
+
+ expect(defineDeclarations).toContain('declare const defineWorkflow');
+ expect(defineDeclarations).not.toMatch(/from ['"]zod(\/[^'"]*)?['"]/);
+ });
+});
diff --git a/packages/twenty-sdk/src/cli/utilities/build/common/plugins/__tests__/__snapshots__/stub-twenty-sdk-define.plugin.spec.ts.snap b/packages/twenty-sdk/src/cli/utilities/build/common/plugins/__tests__/__snapshots__/stub-twenty-sdk-define.plugin.spec.ts.snap
index e598a4e2ddd..bef1b64f1d9 100644
--- a/packages/twenty-sdk/src/cli/utilities/build/common/plugins/__tests__/__snapshots__/stub-twenty-sdk-define.plugin.spec.ts.snap
+++ b/packages/twenty-sdk/src/cli/utilities/build/common/plugins/__tests__/__snapshots__/stub-twenty-sdk-define.plugin.spec.ts.snap
@@ -74,6 +74,7 @@ exports[`stub-twenty-sdk-define plugin > matches the recorded export partition 1
"defineUninstallLogicFunction",
"defineView",
"defineViewField",
+ "defineWorkflow",
],
"plainData": [
"AggregateOperations",
diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-extract-config.spec.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-extract-config.spec.ts
index 8cb18d09d2b..66dfc649987 100644
--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-extract-config.spec.ts
+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-extract-config.spec.ts
@@ -64,6 +64,15 @@ describe('extractDefineEntity', () => {
expect(result).toBe('defineFrontComponent');
});
+ it('should detect defineWorkflow in default export', () => {
+ const fileContent = `
+ import { defineWorkflow } from 'twenty-sdk/define';
+ export default defineWorkflow({ name: 'myWorkflow' });
+ `;
+ const result = extractDefineEntity(fileContent);
+ expect(result).toBe('defineWorkflow');
+ });
+
it('should not detect non-target function in default export', () => {
const fileContent = `
import { someOtherFunction } from 'twenty-sdk/define';
diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-validate.spec.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-validate.spec.ts
index f3fec4f718c..604477b9554 100644
--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-validate.spec.ts
+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-validate.spec.ts
@@ -267,6 +267,47 @@ describe('manifestValidate', () => {
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
+
+ it('should not read universalIdentifier keys inside workflow step payloads', () => {
+ const stepId = '550e8400-e29b-41d4-a716-446655440062';
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [validField],
+ workflows: [
+ {
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440060',
+ name: 'Workflow',
+ version: {
+ trigger: {
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440061',
+ type: 'MANUAL',
+ nextStepIds: [stepId],
+ },
+ steps: [
+ {
+ universalIdentifier: stepId,
+ name: 'Step',
+ type: 'LOGIC_FUNCTION',
+ logicFunctionUniversalIdentifier:
+ '550e8400-e29b-41d4-a716-446655440063',
+ input: {
+ universalIdentifier: 'customer-123',
+ field: {
+ universalIdentifier: validField.universalIdentifier,
+ },
+ },
+ nextStepIds: [],
+ },
+ ],
+ },
+ },
+ ],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
});
describe('relation field validation', () => {
diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts
index 66e7f6601e8..12729769d62 100644
--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts
+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts
@@ -59,6 +59,7 @@ import {
type SettingsMenuItemManifest,
type TimelineActivityTypeManifest,
type ViewManifest,
+ type WorkflowManifest,
} from 'twenty-shared/application';
import {
getInputSchemaFromSourceCode,
@@ -116,6 +117,7 @@ export const buildManifest = async (
const roles: RoleManifest[] = [];
const skills: SkillManifest[] = [];
const agents: AgentManifest[] = [];
+ const workflows: WorkflowManifest[] = [];
const connectionProviders: ConnectionProviderManifest[] = [];
const logicFunctions: LogicFunctionManifest[] = [];
const frontComponents: FrontComponentManifest[] = [];
@@ -147,6 +149,7 @@ export const buildManifest = async (
const rolesFilePaths: string[] = [];
const skillsFilePaths: string[] = [];
const agentsFilePaths: string[] = [];
+ const workflowsFilePaths: string[] = [];
const connectionProvidersFilePaths: string[] = [];
const logicFunctionsFilePaths: string[] = [];
const frontComponentsFilePaths: string[] = [];
@@ -266,6 +269,17 @@ export const buildManifest = async (
agentsFilePaths.push(relativePath);
break;
}
+ case ManifestEntityKey.Workflows: {
+ const extract = await extractManifestFromFile<WorkflowManifest>({
+ appPath,
+ filePath,
+ });
+ workflows.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ workflowsFilePaths.push(relativePath);
+ break;
+ }
case ManifestEntityKey.ConnectionProviders: {
const extract =
await extractManifestFromFile<ConnectionProviderManifest>({
@@ -751,6 +765,7 @@ export const buildManifest = async (
roles: roles.sort(byId),
skills: skills.sort(byId),
agents: agents.sort(byId),
+ workflows: workflows.sort(byId),
connectionProviders: connectionProviders.sort(byId),
logicFunctions: logicFunctions.sort(byId),
frontComponents: frontComponents.sort(byId),
@@ -775,6 +790,7 @@ export const buildManifest = async (
roles: rolesFilePaths,
skills: skillsFilePaths,
agents: agentsFilePaths,
+ workflows: workflowsFilePaths,
connectionProviders: connectionProvidersFilePaths,
logicFunctions: logicFunctionsFilePaths,
frontComponents: frontComponentsFilePaths,
diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-extract-config.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-extract-config.ts
index 4b995b4e245..123fdcaf93a 100644
--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-extract-config.ts
+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-extract-config.ts
@@ -15,6 +15,7 @@ export enum TargetFunction {
DefineRole = 'defineRole',
DefineSkill = 'defineSkill',
DefineAgent = 'defineAgent',
+ DefineWorkflow = 'defineWorkflow',
DefineConnectionProvider = 'defineConnectionProvider',
DefineFrontComponent = 'defineFrontComponent',
DefineSettingsFrontComponent = 'defineSettingsFrontComponent',
@@ -39,6 +40,7 @@ export enum ManifestEntityKey {
Roles = 'roles',
Skills = 'skills',
Agents = 'agents',
+ Workflows = 'workflows',
ConnectionProviders = 'connectionProviders',
FrontComponents = 'frontComponents',
PublicAssets = 'publicAssets',
@@ -76,6 +78,7 @@ export const TARGET_FUNCTION_TO_ENTITY_KEY_MAPPING: Record<
[TargetFunction.DefineRole]: ManifestEntityKey.Roles,
[TargetFunction.DefineSkill]: ManifestEntityKey.Skills,
[TargetFunction.DefineAgent]: ManifestEntityKey.Agents,
+ [TargetFunction.DefineWorkflow]: ManifestEntityKey.Workflows,
[TargetFunction.DefineConnectionProvider]:
ManifestEntityKey.ConnectionProviders,
[TargetFunction.DefineFrontComponent]: ManifestEntityKey.FrontComponents,
diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-validate.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-validate.ts
index 10311b2398e..2869a442c87 100644
--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-validate.ts
+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-validate.ts
@@ -67,7 +67,11 @@ const findUniversalIdentifiers = (obj: object): string[] => {
key === 'identifyAccountLogicFunction' ||
key === 'onConnectLogicFunction' ||
key === 'onDisconnectLogicFunction' ||
- key === 'settingsFrontComponent'
+ key === 'settingsFrontComponent' ||
+ key === 'input' ||
+ key === 'expectedBody' ||
+ key === 'outputSchema' ||
+ key === 'expectedOutputSchema'
) {
continue;
}
diff --git a/packages/twenty-sdk/src/sdk/define/common/types/define-entity.type.ts b/packages/twenty-sdk/src/sdk/define/common/types/define-entity.type.ts
index 009d36618b2..f0ed971cbfd 100644
--- a/packages/twenty-sdk/src/sdk/define/common/types/define-entity.type.ts
+++ b/packages/twenty-sdk/src/sdk/define/common/types/define-entity.type.ts
@@ -22,6 +22,7 @@ import {
type SkillManifest,
type StandalonePageLayoutWidgetManifest,
type StandaloneViewFieldManifest,
+ type WorkflowManifest,
} from 'twenty-shared/application';
export type ValidationResult<T> = {
@@ -53,7 +54,8 @@ export type DefinableEntity =
| StandalonePageLayoutWidgetManifest
| PermissionFlagConfig
| CommandMenuItemConfig
- | SettingsMenuItemConfig;
+ | SettingsMenuItemConfig
+ | WorkflowManifest;
export type DefineEntity<T extends DefinableEntity = DefinableEntity> = (
config: LooseEnumValues<T>,
diff --git a/packages/twenty-sdk/src/sdk/define/common/types/loose-shared-types.type.ts b/packages/twenty-sdk/src/sdk/define/common/types/loose-shared-types.type.ts
index e5b9912277d..c116f4e4b65 100644
--- a/packages/twenty-sdk/src/sdk/define/common/types/loose-shared-types.type.ts
+++ b/packages/twenty-sdk/src/sdk/define/common/types/loose-shared-types.type.ts
@@ -92,3 +92,5 @@ export type ViewGroupManifest =
LooseEnumValues<SharedApplication.ViewGroupManifest>;
export type ViewSortManifest =
LooseEnumValues<SharedApplication.ViewSortManifest>;
+export type WorkflowManifest =
+ LooseEnumValues<SharedApplication.WorkflowManifest>;
diff --git a/packages/twenty-sdk/src/sdk/define/index.ts b/packages/twenty-sdk/src/sdk/define/index.ts
index 93fce1f6fe0..d69374f36a7 100644
--- a/packages/twenty-sdk/src/sdk/define/index.ts
+++ b/packages/twenty-sdk/src/sdk/define/index.ts
@@ -193,6 +193,8 @@ export { defineSkill } from '@/sdk/define/skills/define-skill';
export { defineView } from '@/sdk/define/views/define-view';
export { defineViewField } from '@/sdk/define/view-fields/define-view-field';
+export { defineWorkflow } from '@/sdk/define/workflows/define-workflow';
+export type { WorkflowManifest } from '@/sdk/define/common/types/loose-shared-types.type';
export {
getSystemPageLayoutTabUniversalIdentifier,
getSystemRecordPageLayoutUniversalIdentifier,
diff --git a/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts b/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts
new file mode 100644
index 00000000000..56d8f296303
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts
@@ -0,0 +1,77 @@
+import { type WorkflowManifest } from 'twenty-shared/application';
+
+import { defineWorkflow } from '@/sdk/define/workflows/define-workflow';
+
+const STEP_ID = '44444444-4444-4444-8444-444444444444';
+
+const workflow: WorkflowManifest = {
+ universalIdentifier: '11111111-1111-4111-8111-111111111111',
+ name: 'Application greeting',
+ version: {
+ trigger: {
+ universalIdentifier: '33333333-3333-4333-8333-333333333333',
+ type: 'MANUAL',
+ nextStepIds: [STEP_ID],
+ },
+ steps: [
+ {
+ universalIdentifier: STEP_ID,
+ name: 'Greet',
+ type: 'LOGIC_FUNCTION',
+ logicFunctionUniversalIdentifier:
+ '55555555-5555-4555-8555-555555555555',
+ input: { greeting: 'Hello' },
+ nextStepIds: [],
+ },
+ ],
+ },
+};
+
+const withStep = (step: Record<string, unknown>) => ({
+ ...workflow,
+ version: {
+ ...workflow.version,
+ steps: [{ ...workflow.version.steps[0], ...step }],
+ },
+});
+
+describe('defineWorkflow', () => {
+ it('accepts a manual workflow', () => {
+ expect(defineWorkflow(workflow)).toEqual({
+ success: true,
+ config: workflow,
+ errors: [],
+ warnings: [],
+ });
+ });
+
+ it.each([
+ {
+ problem: 'a step type applications cannot use',
+ definition: withStep({ type: 'CODE' }),
+ error:
+ 'version.steps.0.type: Unsupported step type. Application workflows support: LOGIC_FUNCTION, HTTP_REQUEST, CLASSIFY, ITERATOR, DELAY, WAIT_FOR_EVENT, EMPTY, CREATE_RECORD, UPDATE_RECORD, UPSERT_RECORD, DELETE_RECORD, FIND_RECORDS, PICK_RECORD, FILTER, IF_ELSE, FORM, AI_AGENT',
+ },
+ {
+ problem: 'an unknown trigger type',
+ definition: {
+ ...workflow,
+ version: {
+ ...workflow.version,
+ trigger: { ...workflow.version.trigger, type: 'UNKNOWN' },
+ },
+ },
+ error: expect.stringMatching(/^version\.trigger\.type: .*MANUAL/),
+ },
+ {
+ problem: 'a cycle',
+ definition: withStep({ nextStepIds: [STEP_ID] }),
+ error: `Workflow contains a cycle at step ${STEP_ID}`,
+ },
+ ])('rejects $problem', ({ definition, error }) => {
+ const result = defineWorkflow(definition as WorkflowManifest);
+
+ expect(result.success).toBe(false);
+ expect(result.errors).toEqual([error]);
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/define/workflows/define-workflow.ts b/packages/twenty-sdk/src/sdk/define/workflows/define-workflow.ts
new file mode 100644
index 00000000000..0f0ffc1244e
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/define/workflows/define-workflow.ts
@@ -0,0 +1,22 @@
+import {
+ type WorkflowManifest,
+ workflowManifestSchema,
+} from 'twenty-shared/application';
+
+import { type DefineEntity } from '@/sdk/define/common/types/define-entity.type';
+import { createValidationResult } from '@/sdk/define/common/utils/create-validation-result';
+
+export const defineWorkflow: DefineEntity<WorkflowManifest> = (config) => {
+ const result = workflowManifestSchema.safeParse(config);
+
+ return createValidationResult({
+ config,
+ errors: result.success
+ ? []
+ : result.error.issues.map((issue) =>
+ issue.path.length > 0
+ ? `${issue.path.join('.')}: ${issue.message}`
+ : issue.message,
+ ),
+ });
+};
diff --git a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
index a2bf75eb6a6..effc21a6d49 100644
--- a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
+++ b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
@@ -137,6 +137,9 @@ describe('workflow manifest step types', () => {
2,
'type',
]);
+ expect(result.error?.issues[0]?.message).toContain(
+ 'Unsupported step type',
+ );
},
);
});
diff --git a/packages/twenty-shared/src/application/workflowStepManifestType.ts b/packages/twenty-shared/src/application/workflowStepManifestType.ts
index 644b57f2397..c40296e5e19 100644
--- a/packages/twenty-shared/src/application/workflowStepManifestType.ts
+++ b/packages/twenty-shared/src/application/workflowStepManifestType.ts
@@ -50,7 +50,7 @@ export const workflowStepFilterManifestSchema = stepFilterSchema
const recordObjectShape = { objectUniversalIdentifier: z.uuid() };
-export const workflowStepManifestSchema = z.discriminatedUnion('type', [
+const workflowStepManifestOptions = [
z.strictObject({
...baseStepShape,
type: z.literal('LOGIC_FUNCTION'),
@@ -194,6 +194,21 @@ export const workflowStepManifestSchema = z.discriminatedUnion('type', [
responseFormat: agentResponseFormatSchema.optional(),
}),
),
-]);
+] as const;
+
+const WORKFLOW_STEP_MANIFEST_TYPES = workflowStepManifestOptions.map(
+ (option) => option.shape.type.value,
+);
+
+export const workflowStepManifestSchema = z.discriminatedUnion(
+ 'type',
+ workflowStepManifestOptions,
+ {
+ error: (issue) =>
+ issue.code === 'invalid_union'
+ ? `Unsupported step type. Application workflows support: ${WORKFLOW_STEP_MANIFEST_TYPES.join(', ')}`
+ : undefined,
+ },
+);
export type WorkflowStepManifest = z.infer<typeof workflowStepManifestSchema>;