The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Keep the run's roles in workflow AI steps without an application (#27925)
Paul Rastoine633b764a19a
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.tsindex d07f570edd0..29e57fc7e1f 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-version-mutation.resolver.ts@@ -177,7 +177,6 @@ export class CoreWorkflowVersionMutationResolver {buildWorkflowRunTriggerContext({workspaceMember,payload,- startingApplicationId: callerApplication?.id,});return this.coreWorkflowRunnerService.run({diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.tsindex ddf4ce2df5e..00864f3a0ac 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts@@ -100,27 +100,15 @@ export class CoreWorkflowAccessService {return;}- const [- workflows,- { workspaceCustomFlatApplication, twentyStandardFlatApplication },- ] = await Promise.all([- this.coreWorkflowRepository.find(workspaceId, {- where: { id: In(coreWorkflowIds) },- select: { id: true, applicationId: true },- }),- this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(- { workspaceId },- ),- ]);+ const workflows = await this.coreWorkflowRepository.find(workspaceId, {+ where: { id: In(coreWorkflowIds) },+ select: { id: true, applicationId: true },+ });const isStartable = workflows.every((workflow) =>canApplicationStartCoreWorkflow({callerApplicationId,workflowApplicationId: workflow.applicationId,- workspaceOwnedApplicationIds: [- workspaceCustomFlatApplication.id,- twentyStandardFlatApplication.id,- ],}),);diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/can-application-start-core-workflow.util.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/can-application-start-core-workflow.util.spec.tsindex ea291c5a6a3..f69649a4622 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/can-application-start-core-workflow.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/can-application-start-core-workflow.util.spec.ts@@ -1,36 +1,31 @@import { canApplicationStartCoreWorkflow } from 'src/engine/core-modules/workflow/utils/can-application-start-core-workflow.util';-const WORKSPACE_OWNED_APPLICATION_IDS = ['custom-app-id', 'standard-app-id'];-describe('canApplicationStartCoreWorkflow', () => {it('lets a request without an application start any workflow it can reach', () => {expect(canApplicationStartCoreWorkflow({callerApplicationId: undefined,workflowApplicationId: 'installed-app-id',- workspaceOwnedApplicationIds: WORKSPACE_OWNED_APPLICATION_IDS,}),).toBe(true);});- it('keeps letting applications start workspace workflows', () => {+ it('lets an application start its own workflows', () => {expect(canApplicationStartCoreWorkflow({callerApplicationId: 'installed-app-id',- workflowApplicationId: 'custom-app-id',- workspaceOwnedApplicationIds: WORKSPACE_OWNED_APPLICATION_IDS,+ workflowApplicationId: 'installed-app-id',}),).toBe(true);});- it('lets an application start its own workflows', () => {+ it('refuses an application starting a workspace workflow', () => {expect(canApplicationStartCoreWorkflow({callerApplicationId: 'installed-app-id',- workflowApplicationId: 'installed-app-id',- workspaceOwnedApplicationIds: WORKSPACE_OWNED_APPLICATION_IDS,+ workflowApplicationId: 'custom-app-id',}),- ).toBe(true);+ ).toBe(false);});it('refuses an application starting the workflow of another application', () => {@@ -38,7 +33,6 @@ describe('canApplicationStartCoreWorkflow', () => {canApplicationStartCoreWorkflow({callerApplicationId: 'other-app-id',workflowApplicationId: 'installed-app-id',- workspaceOwnedApplicationIds: WORKSPACE_OWNED_APPLICATION_IDS,}),).toBe(false);});diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-application-start-core-workflow.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-application-start-core-workflow.util.tsindex ae135796137..18da97a2727 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-application-start-core-workflow.util.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-application-start-core-workflow.util.ts@@ -3,12 +3,9 @@ import { isDefined } from 'twenty-shared/utils';export const canApplicationStartCoreWorkflow = ({callerApplicationId,workflowApplicationId,- workspaceOwnedApplicationIds,}: {callerApplicationId: string | undefined;workflowApplicationId: string;- workspaceOwnedApplicationIds: string[];}): boolean =>!isDefined(callerApplicationId) ||- workspaceOwnedApplicationIds.includes(workflowApplicationId) ||workflowApplicationId === callerApplicationId;diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.service.tsindex 61c3202288d..f6039f20905 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.service.ts@@ -67,33 +67,22 @@ export class WorkflowExecutionContextService {return this.buildExecutionContext(workflowRun, workspaceId);}- async assertStepTargetBelongsToRunApplicationOrThrow({+ assertStepTargetBelongsToRunApplicationOrThrow({application,- workspaceId,targetApplicationId,targetLabel,}: {application: FlatApplication | null;- workspaceId: string;targetApplicationId: string;targetLabel: string;- }): Promise<void> {- if (!isDefined(application) || targetApplicationId === application.id) {+ }): void {+ if (!isDefined(application)) {return;}- const { workspaceCustomFlatApplication, twentyStandardFlatApplication } =- await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(- { workspaceId },- );-assertStepTargetBelongsToRunApplication({application,targetApplicationId,- workspaceOwnedApplicationIds: [- workspaceCustomFlatApplication.id,- twentyStandardFlatApplication.id,- ],targetLabel,});}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/assert-step-target-belongs-to-run-application.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/assert-step-target-belongs-to-run-application.util.spec.tsindex 201fc783299..a54ce24e18a 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/assert-step-target-belongs-to-run-application.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/assert-step-target-belongs-to-run-application.util.spec.ts@@ -6,10 +6,6 @@ const assertTarget = (targetApplicationId: string) =>assertStepTargetBelongsToRunApplication({application: RUN_APPLICATION,targetApplicationId,- workspaceOwnedApplicationIds: [- 'workspace-custom-app-id',- 'twenty-standard-app-id',- ],targetLabel: 'Logic function "greet"',});@@ -18,12 +14,16 @@ describe('assertStepTargetBelongsToRunApplication', () => {expect(() => assertTarget('installed-app-id')).not.toThrow();});- it('lets a run use the functions and agents of the workspace', () => {- expect(() => assertTarget('workspace-custom-app-id')).not.toThrow();- expect(() => assertTarget('twenty-standard-app-id')).not.toThrow();+ it('refuses a run using the functions and agents of the workspace', () => {+ expect(() => assertTarget('workspace-custom-app-id')).toThrow(+ 'Logic function "greet" belongs to another application than "Installed app"',+ );});- it('refuses a run crossing into another installed application', () => {+ it('refuses a run crossing into another application', () => {+ expect(() => assertTarget('twenty-standard-app-id')).toThrow(+ 'Logic function "greet" belongs to another application than "Installed app"',+ );expect(() => assertTarget('other-app-id')).toThrow('Logic function "greet" belongs to another application than "Installed app"',);diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-workflow-run-created-by.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-workflow-run-created-by.util.spec.tsindex 85e0c0bd751..46a90e2f972 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-workflow-run-created-by.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-workflow-run-created-by.util.spec.ts@@ -3,7 +3,6 @@ import { type ActorMetadata, FieldActorSource } from 'twenty-shared/types';import { buildWorkflowRunCreatedBy } from 'src/modules/workflow/workflow-executor/utils/build-workflow-run-created-by.util';const CUSTOM_APPLICATION_ID = 'custom-app-id';-const STANDARD_APPLICATION_ID = 'standard-app-id';const INSTALLED_APPLICATION_ID = 'installed-app-id';const buildSource = (applicationId?: string): ActorMetadata => ({@@ -23,10 +22,7 @@ const build = ({buildWorkflowRunCreatedBy({source: buildSource(startingApplicationId),workflowApplicationId,- workspaceOwnedApplicationIds: [- CUSTOM_APPLICATION_ID,- STANDARD_APPLICATION_ID,- ],+ workspaceCustomApplicationId: CUSTOM_APPLICATION_ID,});describe('buildWorkflowRunCreatedBy', () => {@@ -35,9 +31,6 @@ describe('buildWorkflowRunCreatedBy', () => {build({ workflowApplicationId: INSTALLED_APPLICATION_ID }).context.applicationId,).toBe(INSTALLED_APPLICATION_ID);- });-- it('keeps the application that started its own workflow', () => {expect(build({workflowApplicationId: INSTALLED_APPLICATION_ID,@@ -46,27 +39,15 @@ describe('buildWorkflowRunCreatedBy', () => {).toBe(INSTALLED_APPLICATION_ID);});- it('binds a workspace workflow started by an application token to that application', () => {+ it('leaves a run of a workspace workflow unbound, whoever starts it', () => {expect(- build({- workflowApplicationId: CUSTOM_APPLICATION_ID,- startingApplicationId: INSTALLED_APPLICATION_ID,- }).context.applicationId,- ).toBe(INSTALLED_APPLICATION_ID);- });-- it('leaves a workspace workflow started without an application unbound', () => {- expect(- build({ workflowApplicationId: STANDARD_APPLICATION_ID }).context+ build({ workflowApplicationId: CUSTOM_APPLICATION_ID }).context.applicationId,).toBeUndefined();- });-- it('never binds a run to a workspace-owned application', () => {expect(build({workflowApplicationId: CUSTOM_APPLICATION_ID,- startingApplicationId: STANDARD_APPLICATION_ID,+ startingApplicationId: INSTALLED_APPLICATION_ID,}).context.applicationId,).toBeUndefined();});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/assert-step-target-belongs-to-run-application.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/assert-step-target-belongs-to-run-application.util.tsindex 5c2c17c1447..80e609c1eb7 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/assert-step-target-belongs-to-run-application.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/assert-step-target-belongs-to-run-application.util.ts@@ -7,18 +7,13 @@ import {export const assertStepTargetBelongsToRunApplication = ({application,targetApplicationId,- workspaceOwnedApplicationIds,targetLabel,}: {application: Pick<FlatApplication, 'id' | 'name'>;targetApplicationId: string;- workspaceOwnedApplicationIds: string[];targetLabel: string;}): void => {- if (- targetApplicationId === application.id ||- workspaceOwnedApplicationIds.includes(targetApplicationId)- ) {+ if (targetApplicationId === application.id) {return;}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-workflow-run-created-by.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-workflow-run-created-by.util.tsindex f9db0f41df9..d556f9c9a96 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-workflow-run-created-by.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-workflow-run-created-by.util.ts@@ -1,39 +1,26 @@import { type ActorMetadata } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';+// Only workflows of installed applications bind their runs; the workspace custom application acts across applicationsexport const buildWorkflowRunCreatedBy = ({source,workflowApplicationId,- workspaceOwnedApplicationIds,+ workspaceCustomApplicationId,}: {source: ActorMetadata;workflowApplicationId: string;- workspaceOwnedApplicationIds: string[];+ workspaceCustomApplicationId: string;}): ActorMetadata => {- const startingApplicationId = source.context?.applicationId;+ const runApplicationId =+ workflowApplicationId === workspaceCustomApplicationId+ ? undefined+ : workflowApplicationId;- const isInstalledApplicationId = (- applicationId: string | undefined,- ): applicationId is string =>- isDefined(applicationId) &&- !workspaceOwnedApplicationIds.includes(applicationId);-- if (isInstalledApplicationId(workflowApplicationId)) {- return {- ...source,- context: { ...source.context, applicationId: workflowApplicationId },- };- }-- if (- !isDefined(startingApplicationId) ||- isInstalledApplicationId(startingApplicationId)- ) {+ if (source.context?.applicationId === runApplicationId) {return source;}return {...source,- context: { ...source.context, applicationId: undefined },+ context: { ...source.context, applicationId: runApplicationId },};};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.tsindex b45743f3a6f..d7c2e004d49 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@@ -108,10 +108,9 @@ export class AiAgentWorkflowAction implements WorkflowAction {const { application } = executionContext;if (isDefined(agent)) {- await this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow(+ this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow({application,- workspaceId,targetApplicationId: agent.applicationId,targetLabel: `Agent "${agent.name}"`,},diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.tsindex fd793eddda2..1b03552dc3b 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-execution-context.util.ts@@ -40,12 +40,10 @@ export const buildWorkflowAgentRunExecutionContext = ({: null,rolePermissionConfig: executionContext.rolePermissionConfig,usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,+ agentRunRoleIds: getAgentRunRoleIdsFromRolePermissionConfig(+ executionContext.rolePermissionConfig,+ ),...(isDefined(executionContext.application)- ? {- application: executionContext.application,- agentRunRoleIds: getAgentRunRoleIdsFromRolePermissionConfig(- executionContext.rolePermissionConfig,- ),- }+ ? { application: executionContext.application }: {}),});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.tsindex cd49a9ca067..6fa0e128ec6 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts@@ -68,10 +68,9 @@ export class CodeWorkflowAction implements WorkflowAction {const { authContext, application } =await this.workflowExecutionContextService.getExecutionContext(runInfo);- await this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow(+ this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow({application,- workspaceId,targetApplicationId: flatLogicFunction.applicationId,targetLabel: `Logic function "${flatLogicFunction.name}"`,},diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.tsindex 3e9a09d34c6..d4087f6b221 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts@@ -82,10 +82,9 @@ export class LogicFunctionWorkflowAction implements WorkflowAction {const { authContext, application } =await this.workflowExecutionContextService.getExecutionContext(runInfo);- await this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow(+ this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow({application,- workspaceId,targetApplicationId: logicFunction.applicationId,targetLabel: `Logic function "${logicFunction.name}"`,},diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/services/core-workflow-runner.service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/services/core-workflow-runner.service.tsindex 4047fae89ba..098d760ffae 100644--- a/packages/twenty-server/src/modules/workflow/workflow-runner/services/core-workflow-runner.service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/services/core-workflow-runner.service.ts@@ -117,17 +117,14 @@ export class CoreWorkflowRunnerService {: isManualTrigger? WorkflowRunStatus.ENQUEUED: WorkflowRunStatus.NOT_STARTED;- const { workspaceCustomFlatApplication, twentyStandardFlatApplication } =+ const { workspaceCustomFlatApplication } =await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow({ workspaceId },);const createdBy = buildWorkflowRunCreatedBy({source,workflowApplicationId: workflow.applicationId,- workspaceOwnedApplicationIds: [- workspaceCustomFlatApplication.id,- twentyStandardFlatApplication.id,- ],+ workspaceCustomApplicationId: workspaceCustomFlatApplication.id,});const createdWorkflowRunId =await this.workflowRunWorkspaceService.createCoreWorkflowRun({diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/__tests__/build-workflow-run-trigger-context.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/__tests__/build-workflow-run-trigger-context.util.spec.tsindex 07a76985fc0..eb907ac466c 100644--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/__tests__/build-workflow-run-trigger-context.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/__tests__/build-workflow-run-trigger-context.util.spec.ts@@ -19,18 +19,4 @@ describe('buildWorkflowRunTriggerContext', () => {context: {},});});-- it('records the application a member starts a run through', () => {- expect(- buildWorkflowRunTriggerContext({- workspaceMember: WORKSPACE_MEMBER,- startingApplicationId: 'installed-app-id',- }).createdBy,- ).toEqual({- source: FieldActorSource.MANUAL,- workspaceMemberId: 'member-id',- name: 'Jane Austen',- context: { applicationId: 'installed-app-id' },- });- });});diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/build-workflow-run-trigger-context.util.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/build-workflow-run-trigger-context.util.tsindex 142c45a66ba..2da2e0c6753 100644--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/build-workflow-run-trigger-context.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/utils/build-workflow-run-trigger-context.util.ts@@ -1,4 +1,3 @@-import { isDefined } from 'twenty-shared/utils';import {WORKFLOW_TRIGGER_METADATA_KEY,WORKFLOW_TRIGGER_METADATA_WORKSPACE_MEMBER_ID_KEY,@@ -11,11 +10,9 @@ import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-membeexport const buildWorkflowRunTriggerContext = ({workspaceMember,payload,- startingApplicationId,}: {workspaceMember: Pick<WorkspaceMemberWorkspaceEntity, 'id' | 'name'>;payload?: object | null;- startingApplicationId?: string;}) => ({payload: {...payload,@@ -32,8 +29,5 @@ export const buildWorkflowRunTriggerContext = ({},workspaceMemberId: workspaceMember.id,}),- ...(isDefined(startingApplicationId)- ? { context: { applicationId: startingApplicationId } }- : {}),},});diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-execution-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-execution-permissions.integration-spec.tsindex 71fcdf6b8e9..33618af5991 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-execution-permissions.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-execution-permissions.integration-spec.ts@@ -9,7 +9,6 @@ import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';import { updateFeatureFlag } from 'test/integration/metadata/suites/utils/update-feature-flag.util';-import { buildEmailDocument } from 'test/integration/utils/build-email-document.util';import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';import {@@ -535,41 +534,23 @@ describe('application workflow execution permissions', () => {expect(ownApplicationRun.status).toBe('COMPLETED');}, 120000);- it('keeps the application bound when its token starts a workspace workflow', async () => {- const { status, stepStatus } = await runWorkflowActionStep({- name: `${RUN_PREFIX} workspace workflow started by the application`,- stepType: 'CREATE_RECORD',- input: {- objectName: 'opportunity',- objectRecord: { name: NESTED_OPPORTUNITY_NAME },- },- runToken: await buildJaneTokenThroughApplication(APP_ID),- });-- expect(status).toBe('FAILED');- expect(stepStatus).toBe('FAILED');+ it('refuses an application token starting a workspace workflow', async () => {+ await expect(+ runWorkflowActionStep({+ name: `${RUN_PREFIX} workspace workflow started by the application`,+ stepType: 'CREATE_RECORD',+ input: {+ objectName: 'opportunity',+ objectRecord: { name: NESTED_OPPORTUNITY_NAME },+ },+ runToken: await buildJaneTokenThroughApplication(APP_ID),+ }),+ ).rejects.toThrow('cannot start a workflow owned by another application');expect(await countRecordsByName('opportunity', NESTED_OPPORTUNITY_NAME),).toBe(0);}, 120000);- it('refuses email steps when an application token starts a workspace workflow', async () => {- const { status, stepStatus, stepError } = await runWorkflowActionStep({- name: `${RUN_PREFIX} workspace email workflow started by the application`,- stepType: 'SEND_EMAIL',- input: {- recipients: { to: '[email protected]' },- subject: 'Application workflow permissions',- body: JSON.stringify(buildEmailDocument('Should never be sent')),- },- runToken: await buildJaneTokenThroughApplication(APP_ID),- });-- expect(status).toBe('FAILED');- expect(stepStatus).toBe('FAILED');- expect(stepError).toContain('Applications cannot use SEND_EMAIL steps');- }, 120000);-it('only lets the values of a form step change on an application workflow run', async () => {const workflowRunId = await runWorkflow(FORM_WORKFLOW);const [formStep] = FORM_WORKFLOW.steps;diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-ai-step-run-roles.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-ai-step-run-roles.integration-spec.tsnew file mode 100644index 00000000000..405f697aee4--- /dev/null+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-ai-step-run-roles.integration-spec.ts@@ -0,0 +1,396 @@+import { randomUUID } from 'node:crypto';++import { type LanguageModelV4CallOptions } from '@ai-sdk/provider';+import { MockLanguageModelV4 } from 'ai/test';+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';+import {+ createCoreWorkflow,+ deleteCoreWorkflows,+ runCoreWorkflowVersion,+} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';+import { waitForWorkflowCompletion } from 'test/integration/graphql/suites/workflow/utils/workflow-run-test.util';+import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';+import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';+import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';+import { createOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/create-one-object-metadata.util';+import { deleteOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/delete-one-object-metadata.util';+import { updateOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/update-one-object-metadata.util';+import { upsertObjectPermissions } from 'test/integration/metadata/suites/object-permission/utils/upsert-object-permissions.util';+import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';+import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';+import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';+import { updateWorkspaceMemberRole } from 'test/integration/metadata/suites/role/utils/update-workspace-member-role.util';+import { upsertPermissionFlags } from 'test/integration/metadata/suites/role-permission-flag/utils/upsert-permission-flags.util';+import { upsertRowLevelPermissionPredicates } from 'test/integration/metadata/suites/row-level-permission-predicate/utils/upsert-row-level-permission-predicates.util';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { RowLevelPermissionPredicateOperand } from 'twenty-shared/types';+import { WorkflowActionType } from 'twenty-shared/workflow';+import { PermissionFlagType } from 'twenty-shared/constants';++import {+ type AiModelRegistryService,+ type RegisteredAiModel,+} from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';+import { type WorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';++const schema = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);+const OBJECT_NAME = 'aiStepRunRoleRecord';+const OBJECT_PLURAL = 'aiStepRunRoleRecords';+const FIND_TOOL_NAME = 'find_many_ai_step_run_role_records';+const VISIBLE_RECORD_NAME = 'Visible to the member';+const HIDDEN_RECORD_NAME = 'Hidden from the member';++const USAGE = {+ inputTokens: {+ total: 1,+ noCache: 1,+ cacheRead: undefined,+ cacheWrite: undefined,+ },+ outputTokens: { total: 1, text: 1, reasoning: undefined },+};++type ModelCall = {+ offeredToolNames: string[];+ toolOutputs: string[];+};++// The model calls the find tool once, then answers, so the test sees the tools the step offers and what they return+const mockModelCallingFindTool = (): ModelCall[] => {+ const calls: ModelCall[] = [];+ const model = new MockLanguageModelV4({+ doGenerate: async (options: LanguageModelV4CallOptions) => {+ calls.push({+ offeredToolNames: (options.tools ?? []).map((tool) => tool.name),+ toolOutputs: options.prompt+ .filter((message) => message.role === 'tool')+ .flatMap((message) => message.content)+ .map((part) => JSON.stringify(part)),+ });++ return calls.length === 1+ ? {+ content: [+ {+ type: 'tool-call',+ toolCallId: 'find-1',+ toolName: FIND_TOOL_NAME,+ input: JSON.stringify({ select: ['id', 'name'] }),+ },+ ],+ finishReason: { unified: 'tool-calls', raw: undefined },+ usage: USAGE,+ warnings: [],+ }+ : {+ content: [{ type: 'text', text: 'Done' }],+ finishReason: { unified: 'stop', raw: undefined },+ usage: USAGE,+ warnings: [],+ };+ },+ });+ const aiModelRegistryService =+ getAppProviderByClassName<AiModelRegistryService>('AiModelRegistryService');++ jest.spyOn(aiModelRegistryService, 'resolveModelForAgent').mockReturnValue({+ modelId: TEST_AI_MODEL_ID,+ sdkPackage: '@ai-sdk/openai',+ model,+ } as unknown as RegisteredAiModel);++ return calls;+};++describe('workflow AI step when a member runs a workspace-owned workflow (integration)', () => {+ let objectMetadataId: string;+ let nameFieldMetadataId: string;+ let originalMemberRoleId: string;+ let memberRoleId: string;+ let agentRoleId: string;+ let agentId: string;+ const coreWorkflowIds: string[] = [];++ const setMemberObjectAccess = (canReadObjectRecords: boolean) =>+ upsertObjectPermissions({+ expectToFail: false,+ input: {+ roleId: memberRoleId,+ objectPermissions: [+ {+ objectMetadataId,+ canReadObjectRecords,+ canUpdateObjectRecords: canReadObjectRecords,+ canSoftDeleteObjectRecords: canReadObjectRecords,+ canDestroyObjectRecords: canReadObjectRecords,+ },+ ],+ },+ });++ const setMemberRowRule = (predicates: { value: string }[]) =>+ upsertRowLevelPermissionPredicates({+ expectToFail: false,+ input: {+ roleId: memberRoleId,+ objectMetadataId,+ predicates: predicates.map(({ value }) => ({+ fieldMetadataId: nameFieldMetadataId,+ operand: RowLevelPermissionPredicateOperand.CONTAINS,+ value,+ })),+ predicateGroups: [],+ },+ });++ const createAgentStepWorkflow = async (): Promise<string> => {+ const { coreWorkflowId, coreWorkflowVersionId, workspaceWorkflowId } =+ await createCoreWorkflow({ name: 'AI step run roles' });++ coreWorkflowIds.push(coreWorkflowId);++ const step = {+ id: randomUUID(),+ name: 'Read the records',+ type: WorkflowActionType.AI_AGENT,+ valid: true,+ nextStepIds: [],+ settings: {+ input: { agentId, prompt: 'List the records' },+ outputSchema: {},+ errorHandlingOptions: {+ retryOnFailure: { value: 0 },+ continueOnFailure: { value: false },+ },+ },+ } as WorkflowAiAgentAction;+ const trigger = {+ name: 'Manual trigger',+ type: 'MANUAL',+ settings: { outputSchema: {} },+ nextStepIds: [step.id],+ };+ const [{ workspaceWorkflowVersionId }] = await global.testDataSource.query(+ `SELECT "workspaceWorkflowVersionId" FROM core."workflowVersion" WHERE id = $1`,+ [coreWorkflowVersionId],+ );++ await global.testDataSource.query(+ `UPDATE core."workflowVersion" SET triggers = $2, steps = $3, status = 'ACTIVE' WHERE id = $1`,+ [+ coreWorkflowVersionId,+ JSON.stringify([trigger]),+ JSON.stringify([step]),+ ],+ );+ await global.testDataSource.query(+ `UPDATE "${schema}"."workflowVersion" SET trigger = $2, steps = $3, status = 'ACTIVE' WHERE id = $1`,+ [+ workspaceWorkflowVersionId,+ JSON.stringify(trigger),+ JSON.stringify([step]),+ ],+ );+ await global.testDataSource.query(+ `UPDATE "${schema}".workflow SET "lastPublishedVersionId" = $2 WHERE id = $1`,+ [workspaceWorkflowId, workspaceWorkflowVersionId],+ );+ await global.testDataSource.query(+ `UPDATE core.workflow SET "lastPublishedCoreWorkflowVersionId" = $2, "lastPublishedVersionId" = $3 WHERE id = $1`,+ [coreWorkflowId, coreWorkflowVersionId, workspaceWorkflowVersionId],+ );++ return coreWorkflowVersionId;+ };++ const runAsMemberUntilDone = async (coreWorkflowVersionId: string) => {+ const workflowRunId = await runCoreWorkflowVersion({+ coreWorkflowVersionId,+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,+ });++ return (await waitForWorkflowCompletion(workflowRunId))?.status;+ };++ beforeAll(async () => {+ originalMemberRoleId = (await findOneRoleByLabel({ label: 'Member' })).id;++ const { data: memberRoleData } = await createOneRole({+ expectToFail: false,+ input: {+ label: 'AI step run roles member',+ description: 'Member role that can run workflows',+ canUpdateAllSettings: false,+ canAccessAllTools: true,+ canReadAllObjectRecords: true,+ canUpdateAllObjectRecords: true,+ canSoftDeleteAllObjectRecords: true,+ canDestroyAllObjectRecords: true,+ canBeAssignedToUsers: true,+ canBeAssignedToAgents: false,+ canBeAssignedToApiKeys: false,+ },+ });++ memberRoleId = memberRoleData.createOneRole.id;++ await upsertPermissionFlags({+ expectToFail: false,+ input: {+ roleId: memberRoleId,+ permissionFlagKeys: [PermissionFlagType.WORKFLOWS],+ },+ });+ await updateWorkspaceMemberRole({+ expectToFail: false,+ input: {+ roleId: memberRoleId,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ },+ });++ const { data: objectData } = await createOneObjectMetadata({+ input: {+ nameSingular: OBJECT_NAME,+ namePlural: OBJECT_PLURAL,+ labelSingular: 'AI step run role record',+ labelPlural: 'AI step run role records',+ icon: 'IconRobot',+ isLabelSyncedWithName: false,+ },+ gqlFields: 'id labelIdentifierFieldMetadataId',+ });++ objectMetadataId = objectData.createOneObject.id;+ nameFieldMetadataId =+ objectData.createOneObject.labelIdentifierFieldMetadataId!;++ for (const name of [VISIBLE_RECORD_NAME, HIDDEN_RECORD_NAME]) {+ await makeGraphqlApiRequest(+ createOneOperationFactory({+ objectMetadataSingularName: OBJECT_NAME,+ gqlFields: 'id',+ data: { name },+ }),+ );+ }++ const { data: roleData } = await createOneRole({+ expectToFail: false,+ input: {+ label: 'AI step run roles agent',+ description: 'Agent role that can read the test records',+ canUpdateAllSettings: false,+ canAccessAllTools: false,+ canReadAllObjectRecords: false,+ canUpdateAllObjectRecords: false,+ canSoftDeleteAllObjectRecords: false,+ canDestroyAllObjectRecords: false,+ canBeAssignedToUsers: false,+ canBeAssignedToAgents: true,+ canBeAssignedToApiKeys: false,+ },+ });++ agentRoleId = roleData.createOneRole.id;++ await upsertObjectPermissions({+ expectToFail: false,+ input: {+ roleId: agentRoleId,+ objectPermissions: [+ {+ objectMetadataId,+ canReadObjectRecords: true,+ canUpdateObjectRecords: false,+ canSoftDeleteObjectRecords: false,+ canDestroyObjectRecords: false,+ },+ ],+ },+ });++ const { data: agentData } = await createOneAgent({+ expectToFail: false,+ input: {+ label: 'AI step run roles agent',+ prompt: 'Read the records you are asked about',+ modelId: TEST_AI_MODEL_ID,+ roleId: agentRoleId,+ },+ });++ agentId = agentData.createOneAgent.id;+ });++ afterEach(async () => {+ jest.restoreAllMocks();+ await setMemberRowRule([]);+ await setMemberObjectAccess(true);+ });++ afterAll(async () => {+ for (const coreWorkflowId of coreWorkflowIds) {+ await global.testDataSource.query(+ `DELETE FROM "${schema}"."workflowRun" WHERE "coreWorkflowId" = $1`,+ [coreWorkflowId],+ );+ }+ await deleteCoreWorkflows({ coreWorkflowIds });+ await deleteOneAgent({ expectToFail: false, input: { id: agentId } });+ await updateWorkspaceMemberRole({+ expectToFail: false,+ input: {+ roleId: originalMemberRoleId,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ },+ });+ for (const roleId of [agentRoleId, memberRoleId]) {+ await deleteOneRole({+ expectToFail: false,+ input: { idToDelete: roleId },+ });+ }+ await updateOneObjectMetadata({+ expectToFail: false,+ input: {+ idToUpdate: objectMetadataId,+ updatePayload: { isActive: false },+ },+ });+ await deleteOneObjectMetadata({+ expectToFail: false,+ input: { idToDelete: objectMetadataId },+ });+ });++ it('refuses the step the records its member cannot read, even when its agent can', async () => {+ await setMemberObjectAccess(false);+ const calls = mockModelCallingFindTool();++ expect(await runAsMemberUntilDone(await createAgentStepWorkflow())).toBe(+ 'COMPLETED',+ );++ expect(calls[0].offeredToolNames).not.toContain(FIND_TOOL_NAME);+ expect(calls[1].toolOutputs.join()).not.toContain(VISIBLE_RECORD_NAME);+ expect(calls[1].toolOutputs.join()).not.toContain(HIDDEN_RECORD_NAME);+ });++ it('applies the row rules of its member to what the step reads', async () => {+ await setMemberRowRule([{ value: 'Visible' }]);+ const calls = mockModelCallingFindTool();++ expect(await runAsMemberUntilDone(await createAgentStepWorkflow())).toBe(+ 'COMPLETED',+ );++ expect(calls[0].offeredToolNames).toContain(FIND_TOOL_NAME);+ expect(calls[1].toolOutputs.join()).toContain(VISIBLE_RECORD_NAME);+ expect(calls[1].toolOutputs.join()).not.toContain(HIDDEN_RECORD_NAME);+ });+});