Skip to content

The open alternative to Salesforce, designed for AI.

Align on-demand logic function runs with the workflow action rule (#26860)

Paul Rastoin3448259a4b3d
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index b366d118989..66b700edd9f 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -262,6 +262,7 @@ type LogicFunction {
universalIdentifier: UUID
createdAt: DateTime!
updatedAt: DateTime!
+ canRunOnDemand: Boolean
}
enum LogicFunctionExecutionMode {
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 11348de484d..4ae8eba9215 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -184,6 +184,7 @@ export interface LogicFunction {
universalIdentifier?: Scalars['UUID']
createdAt: Scalars['DateTime']
updatedAt: Scalars['DateTime']
+ canRunOnDemand?: Scalars['Boolean']
__typename: 'LogicFunction'
}
@@ -3944,6 +3945,7 @@ export interface LogicFunctionGenqlSelection{
universalIdentifier?: boolean | number
createdAt?: boolean | number
updatedAt?: boolean | number
+ canRunOnDemand?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 2e4b585204c..da8bb8e5153 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -543,6 +543,9 @@ export default {
"updatedAt": [
4
],
+ "canRunOnDemand": [
+ 8
+ ],
"__typename": [
1
]
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 3a51726e2f3..76dc2aa6859 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -2649,6 +2649,7 @@ export type Location = {
export type LogicFunction = {
__typename?: 'LogicFunction';
applicationId?: Maybe<Scalars['UUID']['output']>;
+ canRunOnDemand?: Maybe<Scalars['Boolean']['output']>;
createdAt: Scalars['DateTime']['output'];
cronTriggerSettings?: Maybe<Scalars['JSON']['output']>;
databaseEventTriggerSettings?: Maybe<Scalars['JSON']['output']>;
@@ -8747,7 +8748,7 @@ export type FindOneLogicFunctionQueryVariables = Exact<{
}>;
-export type FindOneLogicFunctionQuery = { __typename?: 'Query', findOneLogicFunction: { __typename?: 'LogicFunction', id: string, name: string, description?: string | null, runtime: string, timeoutSeconds: number, executionMode: LogicFunctionExecutionMode, sourceHandlerPath: string, handlerName: string, cronTriggerSettings?: any | null, databaseEventTriggerSettings?: any | null, httpRouteTriggerSettings?: any | null, toolTriggerSettings?: any | null, workflowActionTriggerSettings?: any | null, applicationId?: string | null, universalIdentifier?: string | null, createdAt: string, updatedAt: string } };
+export type FindOneLogicFunctionQuery = { __typename?: 'Query', findOneLogicFunction: { __typename?: 'LogicFunction', canRunOnDemand?: boolean | null, id: string, name: string, description?: string | null, runtime: string, timeoutSeconds: number, executionMode: LogicFunctionExecutionMode, sourceHandlerPath: string, handlerName: string, cronTriggerSettings?: any | null, databaseEventTriggerSettings?: any | null, httpRouteTriggerSettings?: any | null, toolTriggerSettings?: any | null, workflowActionTriggerSettings?: any | null, applicationId?: string | null, universalIdentifier?: string | null, createdAt: string, updatedAt: string } };
export type GetLogicFunctionSourceCodeQueryVariables = Exact<{
input: LogicFunctionIdInput;
@@ -10598,7 +10599,7 @@ export const ExecuteOneLogicFunctionDocument = {"kind":"Document","definitions":
export const UpdateOneLogicFunctionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateOneLogicFunction"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateLogicFunctionFromSourceInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateOneLogicFunction"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<UpdateOneLogicFunctionMutation, UpdateOneLogicFunctionMutationVariables>;
export const FindManyAvailablePackagesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyAvailablePackages"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"LogicFunctionIdInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAvailablePackages"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<FindManyAvailablePackagesQuery, FindManyAvailablePackagesQueryVariables>;
export const FindManyLogicFunctionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyLogicFunctions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findManyLogicFunctions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"LogicFunctionFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"LogicFunctionFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"LogicFunction"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"runtime"}},{"kind":"Field","name":{"kind":"Name","value":"timeoutSeconds"}},{"kind":"Field","name":{"kind":"Name","value":"executionMode"}},{"kind":"Field","name":{"kind":"Name","value":"sourceHandlerPath"}},{"kind":"Field","name":{"kind":"Name","value":"handlerName"}},{"kind":"Field","name":{"kind":"Name","value":"cronTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"databaseEventTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"httpRouteTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"toolTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"workflowActionTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<FindManyLogicFunctionsQuery, FindManyLogicFunctionsQueryVariables>;
-export const FindOneLogicFunctionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneLogicFunction"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"LogicFunctionIdInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findOneLogicFunction"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"LogicFunctionFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"LogicFunctionFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"LogicFunction"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"runtime"}},{"kind":"Field","name":{"kind":"Name","value":"timeoutSeconds"}},{"kind":"Field","name":{"kind":"Name","value":"executionMode"}},{"kind":"Field","name":{"kind":"Name","value":"sourceHandlerPath"}},{"kind":"Field","name":{"kind":"Name","value":"handlerName"}},{"kind":"Field","name":{"kind":"Name","value":"cronTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"databaseEventTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"httpRouteTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"toolTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"workflowActionTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<FindOneLogicFunctionQuery, FindOneLogicFunctionQueryVariables>;
+export const FindOneLogicFunctionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneLogicFunction"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"LogicFunctionIdInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findOneLogicFunction"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"LogicFunctionFields"}},{"kind":"Field","name":{"kind":"Name","value":"canRunOnDemand"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"LogicFunctionFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"LogicFunction"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"runtime"}},{"kind":"Field","name":{"kind":"Name","value":"timeoutSeconds"}},{"kind":"Field","name":{"kind":"Name","value":"executionMode"}},{"kind":"Field","name":{"kind":"Name","value":"sourceHandlerPath"}},{"kind":"Field","name":{"kind":"Name","value":"handlerName"}},{"kind":"Field","name":{"kind":"Name","value":"cronTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"databaseEventTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"httpRouteTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"toolTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"workflowActionTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<FindOneLogicFunctionQuery, FindOneLogicFunctionQueryVariables>;
export const GetLogicFunctionSourceCodeDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetLogicFunctionSourceCode"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"LogicFunctionIdInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getLogicFunctionSourceCode"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<GetLogicFunctionSourceCodeQuery, GetLogicFunctionSourceCodeQueryVariables>;
export const InstallApplicationDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"InstallApplication"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"installApplication"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"universalIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}}]}}]}}]} as unknown as DocumentNode<InstallApplicationMutation, InstallApplicationMutationVariables>;
export const SyncMarketplaceCatalogDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SyncMarketplaceCatalog"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"syncMarketplaceCatalog"}}]}}]} as unknown as DocumentNode<SyncMarketplaceCatalogMutation, SyncMarketplaceCatalogMutationVariables>;
diff --git a/packages/twenty-front/src/modules/logic-functions/graphql/queries/findOneLogicFunction.ts b/packages/twenty-front/src/modules/logic-functions/graphql/queries/findOneLogicFunction.ts
index 2670668aa3f..3e5f2a8d413 100644
--- a/packages/twenty-front/src/modules/logic-functions/graphql/queries/findOneLogicFunction.ts
+++ b/packages/twenty-front/src/modules/logic-functions/graphql/queries/findOneLogicFunction.ts
@@ -6,6 +6,7 @@ export const FIND_ONE_LOGIC_FUNCTION = gql`
query FindOneLogicFunction($input: LogicFunctionIdInput!) {
findOneLogicFunction(input: $input) {
...LogicFunctionFields
+ canRunOnDemand
}
}
`;
diff --git a/packages/twenty-front/src/pages/settings/logic-functions/SettingsLogicFunctionDetail.tsx b/packages/twenty-front/src/pages/settings/logic-functions/SettingsLogicFunctionDetail.tsx
index c04f8663497..931b4e486a2 100644
--- a/packages/twenty-front/src/pages/settings/logic-functions/SettingsLogicFunctionDetail.tsx
+++ b/packages/twenty-front/src/pages/settings/logic-functions/SettingsLogicFunctionDetail.tsx
@@ -71,6 +71,8 @@ export const SettingsLogicFunctionDetail = () => {
logicFunctionId,
});
+ const canTestFunction = logicFunction?.canRunOnDemand ?? false;
+
const handleTestFunction = async () => {
navigate(
{ search: location.search, hash: '#test' },
@@ -88,14 +90,20 @@ export const SettingsLogicFunctionDetail = () => {
hide: isReadonly,
},
{ id: 'settings', title: t`Settings`, Icon: IconSettings },
- { id: 'test', title: t`Test`, Icon: IconPlayerPlay },
+ {
+ id: 'test',
+ title: t`Test`,
+ Icon: IconPlayerPlay,
+ disabled: !canTestFunction,
+ hide: !canTestFunction,
+ },
{ id: 'triggers', title: t`Triggers`, Icon: IconBolt },
];
const isEditorTab = activeTabId === 'editor';
const isTriggersTab = activeTabId === 'triggers';
const isSettingsTab = activeTabId === 'settings';
- const isTestTab = activeTabId === 'test';
+ const isTestTab = activeTabId === 'test' && canTestFunction;
const breadcrumbLinks = isDefined(applicationId)
? (() => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.exception.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.exception.ts
index bae9240d6ee..4874acbaaea 100644
--- a/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.exception.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.exception.ts
@@ -6,6 +6,7 @@ import { CustomException } from 'src/utils/custom-exception';
export enum LogicFunctionExceptionCode {
LOGIC_FUNCTION_NOT_FOUND = 'LOGIC_FUNCTION_NOT_FOUND',
+ LOGIC_FUNCTION_FORBIDDEN = 'LOGIC_FUNCTION_FORBIDDEN',
LOGIC_FUNCTION_ALREADY_EXIST = 'LOGIC_FUNCTION_ALREADY_EXIST',
LOGIC_FUNCTION_NOT_READY = 'LOGIC_FUNCTION_NOT_READY',
LOGIC_FUNCTION_BUILDING = 'LOGIC_FUNCTION_BUILDING',
@@ -29,6 +30,8 @@ const getLogicFunctionExceptionUserFriendlyMessage = (
switch (code) {
case LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND:
return msg`Function not found.`;
+ case LogicFunctionExceptionCode.LOGIC_FUNCTION_FORBIDDEN:
+ return msg`You are not allowed to access this function.`;
case LogicFunctionExceptionCode.LOGIC_FUNCTION_ALREADY_EXIST:
return msg`A function with this name already exists.`;
case LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_READY:
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.module.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.module.ts
index 6cf66ae03d2..8a3de3c0471 100644
--- a/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.module.ts
@@ -1,6 +1,7 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
+import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { EventLogLiveModule } from 'src/engine/core-modules/event-logs/live/event-log-live.module';
@@ -26,6 +27,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
TypeOrmModule.forFeature([
LogicFunctionEntity,
ApplicationEntity,
+ ApplicationRegistrationEntity,
FeatureFlagEntity,
]),
ThrottlerModule,
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts
index 494089fe65e..afd8a41102e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts
@@ -1,5 +1,12 @@
import { UseFilters, UseGuards, UsePipes } from '@nestjs/common';
-import { Args, Mutation, Query, Subscription } from '@nestjs/graphql';
+import {
+ Args,
+ Mutation,
+ Parent,
+ Query,
+ ResolveField,
+ Subscription,
+} from '@nestjs/graphql';
import graphqlTypeJson from 'graphql-type-json';
import { PermissionFlagType } from 'twenty-shared/constants';
@@ -34,6 +41,7 @@ import { LogicFunctionLogsDTO } from 'src/engine/metadata-modules/logic-function
import { LogicFunctionLogsInput } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-logs.input';
import { LogicFunctionDTO } from 'src/engine/metadata-modules/logic-function/dtos/logic-function.dto';
import { UpdateLogicFunctionFromSourceInput } from 'src/engine/metadata-modules/logic-function/dtos/update-logic-function-from-source.input';
+import { LogicFunctionFromSourceHelperService } from 'src/engine/metadata-modules/logic-function/services/logic-function-from-source-helper.service';
import { LogicFunctionFromSourceService } from 'src/engine/metadata-modules/logic-function/services/logic-function-from-source.service';
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
import { findFlatLogicFunctionOrThrow } from 'src/engine/metadata-modules/logic-function/utils/find-flat-logic-function-or-throw.util';
@@ -46,7 +54,7 @@ import { wrapAsyncIteratorWithLifecycle } from 'src/engine/subscriptions/utils/w
import { EventLogLiveService } from 'src/engine/core-modules/event-logs/live/event-log-live.service';
@UseGuards(WorkspaceAuthGuard, FeatureFlagGuard, NoPermissionGuard)
-@MetadataResolver()
+@MetadataResolver(() => LogicFunctionDTO)
@UsePipes(ResolverValidationPipe)
@UseFilters(
UsageLimitGraphqlApiExceptionFilter,
@@ -57,6 +65,7 @@ import { EventLogLiveService } from 'src/engine/core-modules/event-logs/live/eve
export class LogicFunctionResolver {
constructor(
private readonly logicFunctionFromSourceService: LogicFunctionFromSourceService,
+ private readonly logicFunctionFromSourceHelperService: LogicFunctionFromSourceHelperService,
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
private readonly subscriptionService: SubscriptionService,
private readonly eventLogLiveService: EventLogLiveService,
@@ -126,6 +135,20 @@ export class LogicFunctionResolver {
}
}
+ @ResolveField(() => Boolean, { nullable: true })
+ async canRunOnDemand(
+ @Parent() { id }: Pick<LogicFunctionDTO, 'id'>,
+ @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
+ ): Promise<boolean> {
+ try {
+ return await this.logicFunctionFromSourceHelperService.isLogicFunctionRunnableOnDemand(
+ { id, workspaceId },
+ );
+ } catch (error) {
+ return logicFunctionGraphQLApiExceptionHandler(error);
+ }
+ }
+
@Query(() => graphqlTypeJson)
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
async getAvailablePackages(
@@ -172,6 +195,10 @@ export class LogicFunctionResolver {
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
): Promise<LogicFunctionDTO> {
try {
+ await this.logicFunctionFromSourceHelperService.findWorkspaceCustomLogicFunctionOrThrow(
+ { id, workspaceId },
+ );
+
return await this.logicFunctionFromSourceService.deleteOneWithSource({
id,
workspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source-helper.service.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source-helper.service.ts
index 397069ad14f..cce83d73283 100644
--- a/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source-helper.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source-helper.service.ts
@@ -1,14 +1,24 @@
import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
import { join } from 'path';
+import { isDefined } from 'twenty-shared/utils';
+import { Repository } from 'typeorm';
+
+import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
import {
DEFAULT_BUILT_HANDLER_PATH,
DEFAULT_SOURCE_HANDLER_PATH,
} from 'src/engine/metadata-modules/logic-function/constants/handler.contant';
+import {
+ LogicFunctionException,
+ LogicFunctionExceptionCode,
+} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
import { findFlatLogicFunctionOrThrow } from 'src/engine/metadata-modules/logic-function/utils/find-flat-logic-function-or-throw.util';
import { getLogicFunctionSubfolderForFromSource } from 'src/engine/metadata-modules/logic-function/utils/get-logic-function-subfolder-for-from-source';
@@ -22,6 +32,8 @@ export class LogicFunctionFromSourceHelperService {
private readonly applicationService: ApplicationService,
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
+ @InjectRepository(ApplicationRegistrationEntity)
+ private readonly applicationRegistrationRepository: Repository<ApplicationRegistrationEntity>,
) {}
async findLogicFunctionAndApplicationOrThrow({
@@ -31,28 +43,145 @@ export class LogicFunctionFromSourceHelperService {
id: string;
workspaceId: string;
}) {
- const [{ flatLogicFunctionMaps }, { workspaceCustomFlatApplication }] =
- await Promise.all([
- this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps({
- workspaceId,
- flatMapsKeys: ['flatLogicFunctionMaps'],
- }),
- this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
- { workspaceId },
- ),
- ]);
+ const [
+ { flatLogicFunctionMaps, flatApplicationMaps },
+ { workspaceCustomFlatApplication },
+ ] = await Promise.all([
+ this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps({
+ workspaceId,
+ flatMapsKeys: ['flatLogicFunctionMaps', 'flatApplicationMaps'],
+ }),
+ this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId },
+ ),
+ ]);
const flatLogicFunction = findFlatLogicFunctionOrThrow({
id,
flatLogicFunctionMaps,
});
+ const ownerFlatApplication =
+ flatApplicationMaps.byId[flatLogicFunction.applicationId];
+
+ if (!isDefined(ownerFlatApplication)) {
+ throw new LogicFunctionException(
+ `Application not found for logic function ${id}`,
+ LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
+ );
+ }
+
return {
flatLogicFunction,
- ownerFlatApplication: workspaceCustomFlatApplication,
+ ownerFlatApplication,
+ workspaceCustomFlatApplication,
};
}
+ async findWorkspaceCustomLogicFunctionOrThrow({
+ id,
+ workspaceId,
+ }: {
+ id: string;
+ workspaceId: string;
+ }) {
+ const {
+ flatLogicFunction,
+ ownerFlatApplication,
+ workspaceCustomFlatApplication,
+ } = await this.findLogicFunctionAndApplicationOrThrow({ id, workspaceId });
+
+ if (ownerFlatApplication.id !== workspaceCustomFlatApplication.id) {
+ throw new LogicFunctionException(
+ 'Only logic functions written in this workspace can be read or changed from source',
+ LogicFunctionExceptionCode.LOGIC_FUNCTION_FORBIDDEN,
+ );
+ }
+
+ return { flatLogicFunction, ownerFlatApplication };
+ }
+
+ async findLogicFunctionRunnableOnDemandOrThrow({
+ id,
+ workspaceId,
+ }: {
+ id: string;
+ workspaceId: string;
+ }) {
+ const {
+ flatLogicFunction,
+ ownerFlatApplication,
+ workspaceCustomFlatApplication,
+ } = await this.findLogicFunctionAndApplicationOrThrow({ id, workspaceId });
+
+ const isRunnableOnDemand = await this.isRunnableOnDemand({
+ flatLogicFunction,
+ ownerFlatApplication,
+ workspaceCustomFlatApplication,
+ workspaceId,
+ });
+
+ if (!isRunnableOnDemand) {
+ throw new LogicFunctionException(
+ 'Only logic functions written in this workspace or exposed as workflow actions can be run on demand',
+ LogicFunctionExceptionCode.LOGIC_FUNCTION_FORBIDDEN,
+ );
+ }
+
+ return { flatLogicFunction, ownerFlatApplication };
+ }
+
+ async isLogicFunctionRunnableOnDemand({
+ id,
+ workspaceId,
+ }: {
+ id: string;
+ workspaceId: string;
+ }): Promise<boolean> {
+ const {
+ flatLogicFunction,
+ ownerFlatApplication,
+ workspaceCustomFlatApplication,
+ } = await this.findLogicFunctionAndApplicationOrThrow({ id, workspaceId });
+
+ return this.isRunnableOnDemand({
+ flatLogicFunction,
+ ownerFlatApplication,
+ workspaceCustomFlatApplication,
+ workspaceId,
+ });
+ }
+
+ private async isRunnableOnDemand({
+ flatLogicFunction,
+ ownerFlatApplication,
+ workspaceCustomFlatApplication,
+ workspaceId,
+ }: {
+ flatLogicFunction: FlatLogicFunction;
+ ownerFlatApplication: FlatApplication;
+ workspaceCustomFlatApplication: FlatApplication;
+ workspaceId: string;
+ }): Promise<boolean> {
+ if (
+ ownerFlatApplication.id === workspaceCustomFlatApplication.id ||
+ isDefined(flatLogicFunction.workflowActionTriggerSettings)
+ ) {
+ return true;
+ }
+
+ if (!isDefined(ownerFlatApplication.applicationRegistrationId)) {
+ return false;
+ }
+
+ return this.applicationRegistrationRepository.exists({
+ where: {
+ id: ownerFlatApplication.applicationRegistrationId,
+ ownerWorkspaceId: workspaceId,
+ },
+ });
+ }
+
buildHandlerPaths(logicFunctionId: string) {
const logicFunctionSubfolder =
getLogicFunctionSubfolderForFromSource(logicFunctionId);
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source.service.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source.service.ts
index 6b553f599ef..fd8075267c6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/services/logic-function-from-source.service.ts
@@ -135,7 +135,7 @@ export class LogicFunctionFromSourceService {
workspaceId: string;
}): Promise<{ id: string }> {
const { flatLogicFunction: existingLogicFunction, ownerFlatApplication } =
- await this.helperService.findLogicFunctionAndApplicationOrThrow({
+ await this.helperService.findWorkspaceCustomLogicFunctionOrThrow({
id: existingLogicFunctionId,
workspaceId,
});
@@ -209,7 +209,7 @@ export class LogicFunctionFromSourceService {
workspaceId: string;
}): Promise<void> {
const { flatLogicFunction, ownerFlatApplication } =
- await this.helperService.findLogicFunctionAndApplicationOrThrow({
+ await this.helperService.findWorkspaceCustomLogicFunctionOrThrow({
id: updateLogicFunctionFromSourceInput.id,
workspaceId,
});
@@ -253,14 +253,14 @@ export class LogicFunctionFromSourceService {
}): Promise<LogicFunctionDTO> {
const {
flatLogicFunction: existingFlatLogicFunction,
- ownerFlatApplication: resolvedOwnerFlatApplication,
+ workspaceCustomFlatApplication,
} = await this.helperService.findLogicFunctionAndApplicationOrThrow({
id,
workspaceId,
});
const effectiveOwnerFlatApplication =
- ownerFlatApplication ?? resolvedOwnerFlatApplication;
+ ownerFlatApplication ?? workspaceCustomFlatApplication;
const validateAndBuildResult =
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
@@ -299,7 +299,7 @@ export class LogicFunctionFromSourceService {
workspaceId: string;
}): Promise<void> {
const { flatLogicFunction, ownerFlatApplication } =
- await this.helperService.findLogicFunctionAndApplicationOrThrow({
+ await this.helperService.findWorkspaceCustomLogicFunctionOrThrow({
id,
workspaceId,
});
@@ -358,7 +358,7 @@ export class LogicFunctionFromSourceService {
userWorkspaceId?: string;
}): Promise<LogicFunctionExecutionResultDTO> {
const { flatLogicFunction } =
- await this.helperService.findLogicFunctionAndApplicationOrThrow({
+ await this.helperService.findLogicFunctionRunnableOnDemandOrThrow({
id,
workspaceId,
});
@@ -401,7 +401,7 @@ export class LogicFunctionFromSourceService {
workspaceId: string;
}): Promise<string | null> {
const { flatLogicFunction, ownerFlatApplication } =
- await this.helperService.findLogicFunctionAndApplicationOrThrow({
+ await this.helperService.findWorkspaceCustomLogicFunctionOrThrow({
id,
workspaceId,
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/logic-function-graphql-api-exception-handler.utils.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/logic-function-graphql-api-exception-handler.utils.ts
index 47d4ca7cbd0..2ed710ef4e9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/logic-function-graphql-api-exception-handler.utils.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/logic-function-graphql-api-exception-handler.utils.ts
@@ -20,6 +20,7 @@ export const logicFunctionGraphQLApiExceptionHandler = (error: any) => {
throw new NotFoundError(error);
case LogicFunctionExceptionCode.LOGIC_FUNCTION_ALREADY_EXIST:
throw new ConflictError(error);
+ case LogicFunctionExceptionCode.LOGIC_FUNCTION_FORBIDDEN:
case LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_READY:
case LogicFunctionExceptionCode.LOGIC_FUNCTION_BUILDING:
case LogicFunctionExceptionCode.LOGIC_FUNCTION_EXECUTION_LIMIT_REACHED:
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts
index b9c4c0ef720..f98220985ae 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts
@@ -10,6 +10,10 @@ import {
AiException,
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
+import {
+ LogicFunctionException,
+ LogicFunctionExceptionCode,
+} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
@@ -87,6 +91,24 @@ describe('isUserFacingWorkflowExecutorError', () => {
expect(isUserFacingWorkflowExecutorError(error)).toBe(false);
});
+ it('returns true for a code step pointing at a function it may not run', () => {
+ const error = new LogicFunctionException(
+ 'Forbidden',
+ LogicFunctionExceptionCode.LOGIC_FUNCTION_FORBIDDEN,
+ );
+
+ expect(isUserFacingWorkflowExecutorError(error)).toBe(true);
+ });
+
+ it('returns false for a logic function failure the user cannot resolve', () => {
+ const error = new LogicFunctionException(
+ 'Not ready',
+ LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_READY,
+ );
+
+ expect(isUserFacingWorkflowExecutorError(error)).toBe(false);
+ });
+
it('returns false for a plain error', () => {
expect(isUserFacingWorkflowExecutorError(new Error('boom'))).toBe(false);
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts
index 116eae9656e..b495fda02ab 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts
@@ -3,6 +3,10 @@ import {
AiException,
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
+import {
+ LogicFunctionException,
+ LogicFunctionExceptionCode,
+} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
@@ -39,5 +43,9 @@ export const isUserFacingWorkflowExecutorError = (error: unknown): boolean => {
return USER_FACING_AI_EXCEPTION_CODES.includes(error.code);
}
+ if (error instanceof LogicFunctionException) {
+ return error.code === LogicFunctionExceptionCode.LOGIC_FUNCTION_FORBIDDEN;
+ }
+
return false;
};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code-action.module.ts
index 55c0ab75360..a163bc98be1 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code-action.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code-action.module.ts
@@ -3,6 +3,7 @@ import { Module } from '@nestjs/common';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { LogicFunctionModule } from 'src/engine/core-modules/logic-function/logic-function.module';
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
+import { LogicFunctionModule as LogicFunctionMetadataModule } from 'src/engine/metadata-modules/logic-function/logic-function.module';
import { RoleModule } from 'src/engine/metadata-modules/role/role.module';
import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';
import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';
@@ -14,6 +15,7 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow
imports: [
ApplicationModule,
LogicFunctionModule,
+ LogicFunctionMetadataModule,
WorkflowRunModule,
UserWorkspaceModule,
UserRoleModule,
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.ts
index 5e1147a3e6e..2c058157ac1 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
@@ -6,6 +6,7 @@ import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/inte
import { type LogicFunctionExecuteResult } from 'src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface';
import { LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
+import { LogicFunctionFromSourceHelperService } from 'src/engine/metadata-modules/logic-function/services/logic-function-from-source-helper.service';
import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
import { getUserFromAuthContext } from 'src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util';
import {
@@ -26,6 +27,7 @@ export class CodeWorkflowAction implements WorkflowAction {
constructor(
private readonly logicFunctionExecutorService: LogicFunctionExecutorService,
+ private readonly logicFunctionFromSourceHelperService: LogicFunctionFromSourceHelperService,
private readonly workflowExecutionContextService: WorkflowExecutionContextService,
private readonly workflowRunStepLogService: WorkflowRunStepLogWorkspaceService,
) {}
@@ -55,6 +57,13 @@ export class CodeWorkflowAction implements WorkflowAction {
const { workspaceId } = runInfo;
+ await this.logicFunctionFromSourceHelperService.findLogicFunctionRunnableOnDemandOrThrow(
+ {
+ id: workflowActionInput.logicFunctionId,
+ workspaceId,
+ },
+ );
+
const { authContext } =
await this.workflowExecutionContextService.getExecutionContext(runInfo);
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/code-step-logic-function-ownership.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/code-step-logic-function-ownership.integration-spec.ts
new file mode 100644
index 00000000000..1e658b77a06
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/code-step-logic-function-ownership.integration-spec.ts
@@ -0,0 +1,99 @@
+import { runWorkflowActionStep } from 'test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util';
+import { transferApplicationRegistrationOwnership } from 'test/integration/metadata/suites/application-registration/utils/transfer-application-registration-ownership.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithResources,
+ setupApplicationWithResources,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-resources.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+
+import { type LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
+import { LogicFunctionExecutionStatus } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-execution-result.dto';
+
+describe('Workflow code step running an installed application function', () => {
+ let installedApplication: ApplicationWithResources;
+ let executeSpy: jest.SpyInstance;
+
+ beforeAll(async () => {
+ installedApplication = await setupApplicationWithResources({
+ name: 'Code Step Target Application',
+ });
+
+ jest.useRealTimers();
+
+ await transferApplicationRegistrationOwnership({
+ input: {
+ applicationRegistrationId:
+ installedApplication.applicationRegistrationId,
+ targetWorkspaceSubdomain: 'yc',
+ },
+ expectToFail: false,
+ });
+ }, 120000);
+
+ beforeEach(() => {
+ executeSpy = jest
+ .spyOn(
+ getAppProviderByClassName<LogicFunctionExecutorService>(
+ 'LogicFunctionExecutorService',
+ ),
+ 'execute',
+ )
+ .mockResolvedValue({
+ data: { ran: true },
+ duration: 1,
+ billedDurationMs: 1,
+ logs: '',
+ status: LogicFunctionExecutionStatus.SUCCESS,
+ });
+ });
+
+ afterEach(() => {
+ executeSpy.mockRestore();
+ });
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: installedApplication.universalIdentifier,
+ });
+ });
+
+ it('should fail the step for a function that is not a workflow action', async () => {
+ const { status, stepStatus, stepError } = await runWorkflowActionStep({
+ name: 'Code step running a non workflow action function',
+ stepType: 'CODE',
+ input: {
+ logicFunctionId: installedApplication.logicFunctionId,
+ logicFunctionInput: { chosenBy: 'workflow author' },
+ },
+ });
+
+ expect(status).toBe('FAILED');
+ expect(stepStatus).toBe('FAILED');
+ expect(stepError).toBe(
+ 'Only logic functions written in this workspace or exposed as workflow actions can be run on demand',
+ );
+ expect(executeSpy).not.toHaveBeenCalled();
+ });
+
+ it('should run a function exposed as a workflow action', async () => {
+ const { status, stepStatus, stepResult } = await runWorkflowActionStep({
+ name: 'Code step running a workflow action function',
+ stepType: 'CODE',
+ input: {
+ logicFunctionId: installedApplication.workflowActionLogicFunctionId,
+ logicFunctionInput: { chosenBy: 'workflow author' },
+ },
+ });
+
+ expect(status).toBe('COMPLETED');
+ expect(stepStatus).toBe('SUCCESS');
+ expect(stepResult).toEqual({ ran: true });
+ expect(executeSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ logicFunctionId: installedApplication.workflowActionLogicFunctionId,
+ payload: { chosenBy: 'workflow author' },
+ }),
+ );
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts
index e4f4ed183ec..1de521f6f16 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts
@@ -13,7 +13,8 @@ type WorkflowActionStepType =
| 'SEND_EMAIL'
| 'DRAFT_EMAIL'
| 'CREATE_CALENDAR_EVENT'
- | 'UPDATE_RECORD';
+ | 'UPDATE_RECORD'
+ | 'CODE';
type WorkflowVersionStep = {
id: string;
diff --git a/packages/twenty-server/test/integration/metadata/suites/logic-function/__snapshots__/on-demand-logic-function-execution.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/logic-function/__snapshots__/on-demand-logic-function-execution.integration-spec.ts.snap
new file mode 100644
index 00000000000..9b5bd85503d
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/logic-function/__snapshots__/on-demand-logic-function-execution.integration-spec.ts.snap
@@ -0,0 +1,49 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`On-demand logic function execution from a session with an installed application whose registration the workspace does not own should refuse to delete the function 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "LOGIC_FUNCTION_FORBIDDEN",
+ "userFriendlyMessage": "You are not allowed to access this function.",
+ },
+ "message": "Only logic functions written in this workspace can be read or changed from source",
+ "name": "ForbiddenError",
+}
+`;
+
+exports[`On-demand logic function execution from a session with an installed application whose registration the workspace does not own should refuse to read the function source from the custom application folder 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "LOGIC_FUNCTION_FORBIDDEN",
+ "userFriendlyMessage": "You are not allowed to access this function.",
+ },
+ "message": "Only logic functions written in this workspace can be read or changed from source",
+ "name": "ForbiddenError",
+}
+`;
+
+exports[`On-demand logic function execution from a session with an installed application whose registration the workspace does not own should refuse to run a function that is not a workflow action 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "LOGIC_FUNCTION_FORBIDDEN",
+ "userFriendlyMessage": "You are not allowed to access this function.",
+ },
+ "message": "Only logic functions written in this workspace or exposed as workflow actions can be run on demand",
+ "name": "ForbiddenError",
+}
+`;
+
+exports[`On-demand logic function execution from a session with an installed application whose registration the workspace does not own should refuse to write the function source into the custom application folder 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "LOGIC_FUNCTION_FORBIDDEN",
+ "userFriendlyMessage": "You are not allowed to access this function.",
+ },
+ "message": "Only logic functions written in this workspace can be read or changed from source",
+ "name": "ForbiddenError",
+}
+`;
diff --git a/packages/twenty-server/test/integration/metadata/suites/logic-function/on-demand-logic-function-execution.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/logic-function/on-demand-logic-function-execution.integration-spec.ts
new file mode 100644
index 00000000000..8911fe9ab93
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/logic-function/on-demand-logic-function-execution.integration-spec.ts
@@ -0,0 +1,237 @@
+import { existsSync, rmSync } from 'fs';
+import { join } from 'path';
+
+import { getCurrentUser } from 'test/integration/graphql/utils/get-current-user.util';
+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';
+import { transferApplicationRegistrationOwnership } from 'test/integration/metadata/suites/application-registration/utils/transfer-application-registration-ownership.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithResources,
+ setupApplicationWithResources,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-resources.util';
+import { createOneLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/create-logic-function.util';
+import { deleteLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/delete-logic-function.util';
+import { executeLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/execute-logic-function.util';
+import { findOneLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/find-one-logic-function.util';
+import { getLogicFunctionSourceCode } from 'test/integration/metadata/suites/logic-function/utils/get-logic-function-source-code.util';
+import { updateLogicFunctionSource } from 'test/integration/metadata/suites/logic-function/utils/update-logic-function-source.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
+import { v4 as uuidv4 } from 'uuid';
+
+import { type LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
+import { LogicFunctionExecutionStatus } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-execution-result.dto';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const findCanRunOnDemand = async (logicFunctionId: string) => {
+ const { data } = await findOneLogicFunction({
+ input: { id: logicFunctionId },
+ gqlFields: 'canRunOnDemand',
+ expectToFail: false,
+ });
+
+ return data.findOneLogicFunction.canRunOnDemand;
+};
+
+describe('On-demand logic function execution from a session', () => {
+ let installedApplication: ApplicationWithResources;
+ let customLogicFunctionId: string;
+ let workspaceCustomApplicationUniversalIdentifier: string;
+ let executeSpy: jest.SpyInstance;
+
+ beforeAll(async () => {
+ installedApplication = await setupApplicationWithResources({
+ name: 'Installed Application',
+ });
+
+ const { data: createData } = await createOneLogicFunction({
+ input: { name: `custom-function-${uuidv4()}` },
+ expectToFail: false,
+ });
+
+ customLogicFunctionId = createData.createOneLogicFunction.id;
+
+ const { data: currentUserData } = await getCurrentUser({
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ const { currentWorkspace } = currentUserData.currentUser;
+
+ jestExpectToBeDefined(currentWorkspace);
+
+ workspaceCustomApplicationUniversalIdentifier =
+ currentWorkspace.workspaceCustomApplicationId;
+ }, 120000);
+
+ beforeEach(() => {
+ executeSpy = jest
+ .spyOn(
+ getAppProviderByClassName<LogicFunctionExecutorService>(
+ 'LogicFunctionExecutorService',
+ ),
+ 'execute',
+ )
+ .mockResolvedValue({
+ data: { ran: true },
+ duration: 1,
+ billedDurationMs: 1,
+ logs: '',
+ status: LogicFunctionExecutionStatus.SUCCESS,
+ });
+ });
+
+ afterEach(() => {
+ executeSpy.mockRestore();
+ });
+
+ afterAll(async () => {
+ await deleteLogicFunction({
+ input: { id: customLogicFunctionId },
+ expectToFail: false,
+ });
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: installedApplication.universalIdentifier,
+ });
+ });
+
+ it('should run a function written in the workspace', async () => {
+ const { data } = await executeLogicFunction({
+ input: { id: customLogicFunctionId, payload: {} },
+ expectToFail: false,
+ });
+
+ expect(data.executeOneLogicFunction.data).toEqual({ ran: true });
+ expect(executeSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ logicFunctionId: customLogicFunctionId }),
+ );
+ expect(await findCanRunOnDemand(customLogicFunctionId)).toBe(true);
+ });
+
+ it('should keep reading the source of a function written in the workspace', async () => {
+ const { data } = await getLogicFunctionSourceCode({
+ input: { id: customLogicFunctionId },
+ expectToFail: false,
+ });
+
+ expect(data.getLogicFunctionSourceCode).toEqual(expect.any(String));
+ });
+
+ it('should run a function of an application whose registration the workspace owns', async () => {
+ const { data } = await executeLogicFunction({
+ input: { id: installedApplication.logicFunctionId, payload: {} },
+ expectToFail: false,
+ });
+
+ expect(data.executeOneLogicFunction.data).toEqual({ ran: true });
+ expect(executeSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ logicFunctionId: installedApplication.logicFunctionId,
+ }),
+ );
+ expect(await findCanRunOnDemand(installedApplication.logicFunctionId)).toBe(
+ true,
+ );
+ });
+
+ describe('with an installed application whose registration the workspace does not own', () => {
+ beforeAll(async () => {
+ await transferApplicationRegistrationOwnership({
+ input: {
+ applicationRegistrationId:
+ installedApplication.applicationRegistrationId,
+ targetWorkspaceSubdomain: 'yc',
+ },
+ expectToFail: false,
+ });
+ });
+
+ it('should refuse to run a function that is not a workflow action', async () => {
+ const { errors } = await executeLogicFunction({
+ input: { id: installedApplication.logicFunctionId, payload: {} },
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ expect(executeSpy).not.toHaveBeenCalled();
+ expect(
+ await findCanRunOnDemand(installedApplication.logicFunctionId),
+ ).toBe(false);
+ });
+
+ it('should run a function exposed as a workflow action', async () => {
+ const { data } = await executeLogicFunction({
+ input: {
+ id: installedApplication.workflowActionLogicFunctionId,
+ payload: {},
+ },
+ expectToFail: false,
+ });
+
+ expect(data.executeOneLogicFunction.data).toEqual({ ran: true });
+ expect(executeSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ logicFunctionId: installedApplication.workflowActionLogicFunctionId,
+ }),
+ );
+ expect(
+ await findCanRunOnDemand(
+ installedApplication.workflowActionLogicFunctionId,
+ ),
+ ).toBe(true);
+ });
+
+ it('should refuse to read the function source from the custom application folder', async () => {
+ const { errors } = await getLogicFunctionSourceCode({
+ input: { id: installedApplication.logicFunctionId },
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should refuse to write the function source into the custom application folder', async () => {
+ const customApplicationSourcePath = join(
+ process.cwd(),
+ '.local-storage',
+ SEED_APPLE_WORKSPACE_ID,
+ workspaceCustomApplicationUniversalIdentifier,
+ 'source',
+ 'src/handler.ts',
+ );
+
+ rmSync(customApplicationSourcePath, { force: true });
+
+ const { errors } = await updateLogicFunctionSource({
+ input: {
+ id: installedApplication.logicFunctionId,
+ update: {
+ sourceHandlerCode: 'export const handler = () => "overwritten";',
+ },
+ },
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ expect(existsSync(customApplicationSourcePath)).toBe(false);
+ });
+
+ it('should refuse to delete the function', async () => {
+ const { errors } = await deleteLogicFunction({
+ input: { id: installedApplication.logicFunctionId },
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+
+ const { data } = await findOneLogicFunction({
+ input: { id: installedApplication.logicFunctionId },
+ expectToFail: false,
+ });
+
+ expect(data.findOneLogicFunction.id).toBe(
+ installedApplication.logicFunctionId,
+ );
+ });
+ });
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/logic-function/utils/find-one-logic-function.util.ts b/packages/twenty-server/test/integration/metadata/suites/logic-function/utils/find-one-logic-function.util.ts
index a1e8480a642..cf907326512 100644
--- a/packages/twenty-server/test/integration/metadata/suites/logic-function/utils/find-one-logic-function.util.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/logic-function/utils/find-one-logic-function.util.ts
@@ -16,7 +16,7 @@ export const findOneLogicFunction = async ({
expectToFail = false,
token,
}: PerformMetadataQueryParams<FindOneLogicFunctionFactoryInput>): CommonResponseBody<{
- findOneLogicFunction: LogicFunctionDTO;
+ findOneLogicFunction: LogicFunctionDTO & { canRunOnDemand?: boolean };
}> => {
const graphqlOperation = findOneLogicFunctionQueryFactory({
input,