The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Bind workflow runs to their application and drop standard application exceptions (#29317)
Paul Rastoin24b839fb2e1e
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.service.ts b/packages/twenty-server/src/engine/core-modules/application/application.service.tsindex b24ce348725..fd2f687eb14 100644--- a/packages/twenty-server/src/engine/core-modules/application/application.service.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application.service.ts@@ -470,42 +470,6 @@ export class ApplicationService {}));}- async findTwentyStandardApplicationOrThrow(workspaceId: string): Promise<{- application: ApplicationEntity;- workspace: WorkspaceEntity;- }> {- const workspace = await this.workspaceRepository.findOne({- where: { id: workspaceId },- });-- if (!isDefined(workspace)) {- throw new ApplicationException(- `Could not find workspace ${workspaceId}`,- ApplicationExceptionCode.APPLICATION_NOT_FOUND,- );- }-- const { twentyStandardFlatApplication } =- await this.findWorkspaceTwentyStandardAndCustomApplicationOrThrow({- workspace,- });-- const application = await this.applicationRepository.findOne(workspace.id, {- where: {- id: twentyStandardFlatApplication.id,- },- });-- if (!isDefined(application)) {- throw new ApplicationException(- `Standard application not found for workspace ${workspace.id}`,- ApplicationExceptionCode.APPLICATION_NOT_FOUND,- );- }-- return { application, workspace };- }-async createTwentyStandardApplication({workspaceId,diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/is-twenty-standard-application.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/is-twenty-standard-application.util.spec.tsdeleted file mode 100644index e337818e51c..00000000000--- a/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/is-twenty-standard-application.util.spec.ts+++ /dev/null@@ -1,21 +0,0 @@-import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';--import { isTwentyStandardApplication } from 'src/engine/core-modules/application/utils/is-twenty-standard-application.util';--describe('isTwentyStandardApplication', () => {- it('should recognize the standard application', () => {- expect(- isTwentyStandardApplication({- universalIdentifier: TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,- }),- ).toBe(true);- });-- it('should not recognize another application', () => {- expect(- isTwentyStandardApplication({- universalIdentifier: 'b1a4c0d2-6e1f-4a6b-9c1d-0f2e3a4b5c6d',- }),- ).toBe(false);- });-});diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/is-twenty-standard-application.util.ts b/packages/twenty-server/src/engine/core-modules/application/utils/is-twenty-standard-application.util.tsdeleted file mode 100644index b23881d7382..00000000000--- a/packages/twenty-server/src/engine/core-modules/application/utils/is-twenty-standard-application.util.ts+++ /dev/null@@ -1,9 +0,0 @@-import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';--import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';--export const isTwentyStandardApplication = (- application: Pick<FlatApplication, 'universalIdentifier'>,-): boolean =>- application.universalIdentifier ===- TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER;diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/get-auth-context-application.util.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/get-auth-context-application.util.spec.tsnew file mode 100644index 00000000000..bded49cad1d--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/get-auth-context-application.util.spec.ts@@ -0,0 +1,79 @@+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';++import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';+import { getAuthContextApplication } from 'src/engine/core-modules/auth/utils/get-auth-context-application.util';+import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';++const workspace = {+ id: 'workspace-id',+ workspaceCustomApplicationId: 'workspace-custom-application-id',+} as FlatWorkspace;++const workspaceCustomApplication = {+ id: 'workspace-custom-application-id',+ universalIdentifier: 'workspace-custom-application-id',+} as FlatApplication;++const standardApplication = {+ id: 'standard-application-id',+ universalIdentifier: TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,+} as FlatApplication;++const installedApplication = {+ id: 'installed-application-id',+ universalIdentifier: 'installed-application-universal-identifier',+} as FlatApplication;++describe('getAuthContextApplication', () => {+ it.each([+ ['workspace custom', workspaceCustomApplication],+ ['standard', standardApplication],+ ['installed', installedApplication],+ ])(+ 'should return the %s application a token acts through',+ (_, application) => {+ expect(+ getAuthContextApplication({+ type: 'application',+ workspace,+ application,+ }),+ ).toBe(application);+ },+ );++ it('should return the application a member acts through', () => {+ expect(+ getAuthContextApplication({+ type: 'user',+ workspace,+ viaApplication: standardApplication,+ } as WorkspaceAuthContext),+ ).toBe(standardApplication);+ });++ it('should prefer application over viaApplication for a member', () => {+ expect(+ getAuthContextApplication({+ type: 'user',+ workspace,+ application: installedApplication,+ viaApplication: standardApplication,+ } as WorkspaceAuthContext),+ ).toBe(installedApplication);+ });++ it('should return no application for a member acting directly', () => {+ expect(+ getAuthContextApplication({+ type: 'user',+ workspace,+ } as WorkspaceAuthContext),+ ).toBeUndefined();+ });++ it('should return no application without an auth context', () => {+ expect(getAuthContextApplication(undefined)).toBeUndefined();+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-calling-application.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/get-auth-context-application.util.tssimilarity index 55%rename from packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-calling-application.util.tsrename to packages/twenty-server/src/engine/core-modules/auth/utils/get-auth-context-application.util.tsindex d8c4a93f729..558d7f3b309 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-calling-application.util.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/get-auth-context-application.util.ts@@ -1,14 +1,17 @@import { isDefined } from 'twenty-shared/utils';import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';-import { isTwentyStandardApplication } from 'src/engine/core-modules/application/utils/is-twenty-standard-application.util';import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';-const getAuthContextApplication = (- authContext: WorkspaceAuthContext,+export const getAuthContextApplication = (+ authContext?: WorkspaceAuthContext,): FlatApplication | undefined => {+ if (!isDefined(authContext)) {+ return undefined;+ }+if (isApplicationAuthContext(authContext)) {return authContext.application;}@@ -19,20 +22,3 @@ const getAuthContextApplication = (return undefined;};--// Automated workspace workflow runs and the built-in helper agent act through-// the standard application, and keep their workspace-wide reach until they act-// through the application that owns them-export const resolveAgentRunCallingApplication = (- authContext?: WorkspaceAuthContext,-): FlatApplication | undefined => {- if (!isDefined(authContext)) {- return undefined;- }-- const application = getAuthContextApplication(authContext);-- return isDefined(application) && isTwentyStandardApplication(application)- ? undefined- : application;-};diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/listeners/__tests__/pending-wake-up-database-event.listener.spec.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/listeners/__tests__/pending-wake-up-database-event.listener.spec.tsnew file mode 100644index 00000000000..e3804b102bb--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/listeners/__tests__/pending-wake-up-database-event.listener.spec.ts@@ -0,0 +1,85 @@+import { type ObjectRecordEvent } from 'twenty-shared/database-events';++import { type PendingWakeUpEntity } from 'src/engine/core-modules/pending-wake-up/entities/pending-wake-up.entity';+import { PendingWakeUpDatabaseEventListener } from 'src/engine/core-modules/pending-wake-up/listeners/pending-wake-up-database-event.listener';+import { type PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up.service';+import { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';++const buildWakeUp = (overrides: Partial<PendingWakeUpEntity> = {}) =>+ ({+ id: 'wake-up-id',+ workspaceId: 'workspace-id',+ ownerType: 'WORKFLOW_STEP',+ ownerId: 'workflow-run-id',+ ownerKey: 'step-id',+ eventName: 'company.updated',+ condition: {+ type: 'EVENT',+ eventName: 'company.updated',+ recordId: 'record-b',+ },+ resumeAt: null,+ ...overrides,+ }) as PendingWakeUpEntity;++const buildUpdateEvent = (recordId: string) =>+ ({+ recordId,+ properties: {+ before: { name: 'Before' },+ after: { name: 'After' },+ updatedFields: ['name'],+ diff: {},+ },+ }) as unknown as ObjectRecordEvent;++const payload = {+ workspaceId: 'workspace-id',+ name: 'company.updated',+ events: [buildUpdateEvent('record-a'), buildUpdateEvent('record-b')],+} as unknown as WorkspaceEventBatch<ObjectRecordEvent>;++const buildListener = (wakeUps: PendingWakeUpEntity[]) => {+ const pendingWakeUpService = {+ findEventWakeUps: jest.fn().mockResolvedValue(wakeUps),+ scheduleResolution: jest.fn(),+ };++ return {+ listener: new PendingWakeUpDatabaseEventListener(+ pendingWakeUpService as unknown as PendingWakeUpService,+ ),+ pendingWakeUpService,+ };+};++describe('PendingWakeUpDatabaseEventListener', () => {+ it('hands the matching event to its resolution without checking it against any role', async () => {+ const wakeUp = buildWakeUp();+ const { listener, pendingWakeUpService } = buildListener([wakeUp]);++ await listener.handleObjectRecordUpdateEvent(payload);++ expect(pendingWakeUpService.scheduleResolution).toHaveBeenCalledTimes(1);+ expect(pendingWakeUpService.scheduleResolution).toHaveBeenCalledWith({+ wakeUp,+ event: {+ eventName: 'company.updated',+ recordId: 'record-b',+ record: { name: 'After' },+ before: { name: 'Before' },+ updatedFields: ['name'],+ },+ });+ });++ it('leaves an expired wake-up to its timeout', async () => {+ const { listener, pendingWakeUpService } = buildListener([+ buildWakeUp({ resumeAt: new Date(Date.now() - 1000) }),+ ]);++ await listener.handleObjectRecordUpdateEvent(payload);++ expect(pendingWakeUpService.scheduleResolution).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/listeners/pending-wake-up-database-event.listener.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/listeners/pending-wake-up-database-event.listener.tsindex d477a5ba509..3424779e23a 100644--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/listeners/pending-wake-up-database-event.listener.ts+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/listeners/pending-wake-up-database-event.listener.ts@@ -9,18 +9,11 @@ import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runnerimport { PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up.service';import { buildPendingWakeUpEvent } from 'src/engine/core-modules/pending-wake-up/utils/build-pending-wake-up-event.util';import { doesEventMatchPendingWakeUp } from 'src/engine/core-modules/pending-wake-up/utils/does-event-match-pending-wake-up.util';-import { RecordAccessPolicyService } from 'src/engine/permissions/combine/services/record-access-policy.service';-import { resolveAutomationAdmittedRecordIds } from 'src/engine/permissions/combine/utils/resolve-automation-admitted-record-ids.util';-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';import { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';@Injectable()export class PendingWakeUpDatabaseEventListener {- constructor(- private readonly pendingWakeUpService: PendingWakeUpService,- private readonly workspaceCacheService: WorkspaceCacheService,- private readonly recordAccessPolicyService: RecordAccessPolicyService,- ) {}+ constructor(private readonly pendingWakeUpService: PendingWakeUpService) {}@OnDatabaseBatchEvent('*', DatabaseEventAction.CREATED)async handleObjectRecordCreateEvent(@@ -68,12 +61,6 @@ export class PendingWakeUpDatabaseEventListener {return;}- const admittedRecordIds = await resolveAutomationAdmittedRecordIds({- payload,- workspaceCacheService: this.workspaceCacheService,- recordAccessPolicyService: this.recordAccessPolicyService,- });-const now = Date.now();for (const eventWakeUp of eventWakeUps) {@@ -85,13 +72,12 @@ export class PendingWakeUpDatabaseEventListener {continue;}- const matchingEvent = payload.events.find(- (event) =>- admittedRecordIds.has(event.recordId) &&- doesEventMatchPendingWakeUp({- condition: eventWakeUp.condition,- event,- }),+ // the resolution reads the record with the permissions of the run waiting on it+ const matchingEvent = payload.events.find((event) =>+ doesEventMatchPendingWakeUp({+ condition: eventWakeUp.condition,+ event,+ }),);if (!isDefined(matchingEvent)) {diff --git a/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.module.ts b/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.module.tsindex 508232f35db..c08499da18b 100644--- a/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.module.ts+++ b/packages/twenty-server/src/engine/core-modules/pending-wake-up/pending-wake-up.module.ts@@ -10,17 +10,10 @@ import { PendingWakeUpOwnerHandlerRegistryService } from 'src/engine/core-moduleimport { PendingWakeUpResolverService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up-resolver.service';import { PendingWakeUpService } from 'src/engine/core-modules/pending-wake-up/services/pending-wake-up.service';import { RecordCrudModule } from 'src/engine/core-modules/record-crud/record-crud.module';-import { RecordShareModule } from 'src/engine/permissions/record-share/record-share.module';import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';-import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';@Module({- imports: [- TypeOrmModule.forFeature([PendingWakeUpEntity]),- RecordCrudModule,- RecordShareModule,- WorkspaceCacheModule,- ],+ imports: [TypeOrmModule.forFeature([PendingWakeUpEntity]), RecordCrudModule],providers: [PendingWakeUpService,PendingWakeUpOwnerHandlerRegistryService,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-turn.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-turn.service.tsindex 78b13756183..656d01c1aba 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-turn.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-turn.service.ts@@ -22,6 +22,7 @@ import {import { type Repository } from 'typeorm';import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';+import { getAuthContextApplication } from 'src/engine/core-modules/auth/utils/get-auth-context-application.util';import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/tool-context.type';import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';@@ -45,7 +46,6 @@ import { assertAgentResponseFormatHasOutputFieldsOrThrow } from 'src/engine/metaimport { buildAgentRolePermissionConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util';import { buildStrictAgentResponseSchema } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-strict-agent-response-schema.util';import { getCallLevelProviderOptions } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/provider-options.util';-import { resolveAgentRunCallingApplication } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-calling-application.util';import { replaceUnsupportedFileParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/replace-unsupported-file-parts.util';import { AiAgentRoleService } from 'src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service';import { STRUCTURED_OUTPUT_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/structured-output-system-prompt.const';@@ -368,7 +368,7 @@ export class AgentRunTurnService {workspaceId: agent.workspaceId,agentId: agent.id,authContext,- application: resolveAgentRunCallingApplication(authContext),+ application: getAuthContextApplication(authContext),actorContext,rolePermissionConfig: buildAgentRolePermissionConfig({agentRoleId,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.tsindex 46a95befaa0..55f5ad1ba76 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts@@ -505,10 +505,7 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {// a run never exceeds the agent's application, whoever calls itconst agentRunRoleIds: AgentRunRoleIds = {...callerRoleIds,- ...resolveApplicationRoleId({- application: agentContext.application,- isMissingApplicationRoleTolerated: true,- }),+ ...resolveApplicationRoleId({ application: agentContext.application }),};return {diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/resolve-agent-run-calling-application.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/resolve-agent-run-calling-application.util.spec.tsdeleted file mode 100644index 1c0a98cbe16..00000000000--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/resolve-agent-run-calling-application.util.spec.ts+++ /dev/null@@ -1,70 +0,0 @@-import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';--import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';-import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';-import { resolveAgentRunCallingApplication } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-calling-application.util';--const workspace = {- id: 'workspace-id',- workspaceCustomApplicationId: 'workspace-custom-application-id',-} as FlatWorkspace;--const workspaceCustomApplication = {- id: 'workspace-custom-application-id',- universalIdentifier: 'workspace-custom-application-id',-} as FlatApplication;--const standardApplication = {- id: 'standard-application-id',- universalIdentifier: TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,-} as FlatApplication;--const installedApplication = {- id: 'installed-application-id',- universalIdentifier: 'installed-application-universal-identifier',-} as FlatApplication;--const buildApplicationContext = (- application: FlatApplication,-): WorkspaceAuthContext => ({ type: 'application', workspace, application });--describe('resolveAgentRunCallingApplication', () => {- it('should keep the workspace custom application', () => {- expect(- resolveAgentRunCallingApplication(- buildApplicationContext(workspaceCustomApplication),- ),- ).toBe(workspaceCustomApplication);- });-- it('should keep an installed application', () => {- expect(- resolveAgentRunCallingApplication(- buildApplicationContext(installedApplication),- ),- ).toBe(installedApplication);- });-- it('should drop the standard application', () => {- expect(- resolveAgentRunCallingApplication(- buildApplicationContext(standardApplication),- ),- ).toBeUndefined();- });-- it('should drop the standard application a member acts through', () => {- expect(- resolveAgentRunCallingApplication({- type: 'user',- workspace,- viaApplication: standardApplication,- } as WorkspaceAuthContext),- ).toBeUndefined();- });-- it('should resolve no application without an auth context', () => {- expect(resolveAgentRunCallingApplication(undefined)).toBeUndefined();- });-});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.tsindex fd39d115ff7..70e50fb6584 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts@@ -207,7 +207,6 @@ export class AgentTriggerRunnerService// the agent never exceeds its application, as in its runAgent runsconst agentRunRoleIds: AgentRunRoleIds = resolveApplicationRoleId({application,- isMissingApplicationRoleTolerated: true,});const actingAgent = { id: agent.id, label: agent.label };diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.tsindex ff826666066..ffe82f9efc4 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts@@ -17,6 +17,7 @@ import {} from 'twenty-shared/types';import { getAppPath, isDefined } from 'twenty-shared/utils';+import { getAuthContextApplication } from 'src/engine/core-modules/auth/utils/get-auth-context-application.util';import { type CodeExecutionStreamEmitter } from 'src/engine/core-modules/tool-provider/interfaces/code-execution-stream-emitter.type';import { CodeInterpreterService } from 'src/engine/core-modules/code-interpreter/code-interpreter.service';@@ -33,7 +34,6 @@ import {} from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-turn.service';import { guideUncallableToolCallsToMetaTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/guide-uncallable-tool-calls-to-meta-tool.util';import { replaceUnsupportedFileParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/replace-unsupported-file-parts.util';-import { resolveAgentRunCallingApplication } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-calling-application.util';import { type BrowsingContextType } from 'src/engine/metadata-modules/ai/ai-agent/types/browsing-context.type';import { AGENT_CHAT_KEEPALIVE_INTERVAL_MS } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-keepalive-interval-ms.constant';import { AI_CHAT_EXCLUDED_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-chat/constants/ai-chat-excluded-tool-names.const';@@ -169,7 +169,7 @@ export class ChatExecutionService {locale,onCodeExecutionUpdate,...authorization,- application: resolveAgentRunCallingApplication(authorization.authContext),+ application: getAuthContextApplication(authorization.authContext),resolveExecutionContext,};diff --git a/packages/twenty-server/src/engine/permissions/combine/utils/resolve-automation-admitted-record-ids.util.ts b/packages/twenty-server/src/engine/permissions/combine/utils/resolve-automation-admitted-record-ids.util.tsdeleted file mode 100644index 478f5bd01db..00000000000--- a/packages/twenty-server/src/engine/permissions/combine/utils/resolve-automation-admitted-record-ids.util.ts+++ /dev/null@@ -1,47 +0,0 @@-import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';-import { type ObjectRecordEvent } from 'twenty-shared/database-events';-import { isDefined } from 'twenty-shared/utils';--import { findActiveFlatApplicationByUniversalIdentifier } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-universal-identifier.util';-import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';-import { type RecordAccessPolicyService } from 'src/engine/permissions/combine/services/record-access-policy.service';-import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';-import { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';-import { STANDARD_ROLE } from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-role.constant';--export const resolveAutomationAdmittedRecordIds = async ({- payload,- workspaceCacheService,- recordAccessPolicyService,-}: {- payload: WorkspaceEventBatch<ObjectRecordEvent>;- workspaceCacheService: WorkspaceCacheService;- recordAccessPolicyService: RecordAccessPolicyService;-}): Promise<Set<string>> => {- const { flatApplicationMaps, flatRoleMaps } =- await workspaceCacheService.getOrRecompute(payload.workspaceId, [- 'flatApplicationMaps',- 'flatRoleMaps',- ]);-- const roleId =- findActiveFlatApplicationByUniversalIdentifier(- flatApplicationMaps,- TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,- )?.defaultRoleId ??- findFlatEntityByUniversalIdentifier({- flatEntityMaps: flatRoleMaps,- universalIdentifier: STANDARD_ROLE.admin.universalIdentifier,- })?.id;-- if (!isDefined(roleId)) {- return new Set();- }-- return recordAccessPolicyService- .buildEventRecordAccessGate(payload)- .resolveAdmittedRecordIds({- workspaceId: payload.workspaceId,- intersectionOf: { applicationRoleId: roleId },- });-};diff --git a/packages/twenty-server/src/engine/permissions/permissions.service.ts b/packages/twenty-server/src/engine/permissions/permissions.service.tsindex e84457daac2..7ec34845549 100644--- a/packages/twenty-server/src/engine/permissions/permissions.service.ts+++ b/packages/twenty-server/src/engine/permissions/permissions.service.ts@@ -287,6 +287,7 @@ export class PermissionsService {application,flatRoleMaps,}),+ sourceType: application.sourceType,},});}diff --git a/packages/twenty-server/src/engine/permissions/principal/utils/__tests__/resolve-application-role-id.util.spec.ts b/packages/twenty-server/src/engine/permissions/principal/utils/__tests__/resolve-application-role-id.util.spec.tsindex ca9779086a8..6ab6ab9bd02 100644--- a/packages/twenty-server/src/engine/permissions/principal/utils/__tests__/resolve-application-role-id.util.spec.ts+++ b/packages/twenty-server/src/engine/permissions/principal/utils/__tests__/resolve-application-role-id.util.spec.ts@@ -1,42 +1,58 @@+import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';import { resolveApplicationRoleId } from 'src/engine/permissions/principal/utils/resolve-application-role-id.util';describe('resolveApplicationRoleId', () => {- it.each([true, false])(- 'restricts to the application role (missing role tolerated: %s)',- (isMissingApplicationRoleTolerated) => {- expect(- resolveApplicationRoleId({- application: { defaultRoleId: 'application-role-id' },- isMissingApplicationRoleTolerated,- }),- ).toEqual({ applicationRoleId: 'application-role-id' });- },- );-- it('denies an application without a role when a missing role is not tolerated', () => {+ it.each([+ ApplicationRegistrationSourceType.NPM,+ ApplicationRegistrationSourceType.OAUTH_ONLY,+ ])('restricts to the role of a %s application', (sourceType) => {expect(resolveApplicationRoleId({- application: { defaultRoleId: null },- isMissingApplicationRoleTolerated: false,+ application: { defaultRoleId: 'application-role-id', sourceType },}),- ).toEqual({ applicationRoleId: null });+ ).toEqual({ applicationRoleId: 'application-role-id' });});- it('adds no restriction for an application without a role when a missing role is tolerated', () => {+ it.each([+ ApplicationRegistrationSourceType.LOCAL,+ ApplicationRegistrationSourceType.NPM,+ ApplicationRegistrationSourceType.TARBALL,+ ])('denies a %s application without a role', (sourceType) => {expect(resolveApplicationRoleId({- application: { defaultRoleId: null },- isMissingApplicationRoleTolerated: true,+ application: { defaultRoleId: null, sourceType },}),- ).toEqual({});+ ).toEqual({ applicationRoleId: null });});- it('adds no restriction without an application', () => {+ it('lends the member role to an OAuth-only application without a role', () => {expect(resolveApplicationRoleId({- application: undefined,- isMissingApplicationRoleTolerated: true,+ application: {+ defaultRoleId: null,+ sourceType: ApplicationRegistrationSourceType.OAUTH_ONLY,+ },+ userRoleId: 'user-role-id',}),- ).toEqual({});+ ).toEqual({ applicationRoleId: 'user-role-id' });+ });++ it.each([undefined, null])(+ 'denies an OAuth-only application without a role when no member role backs it (member role: %s)',+ (userRoleId) => {+ expect(+ resolveApplicationRoleId({+ application: {+ defaultRoleId: null,+ sourceType: ApplicationRegistrationSourceType.OAUTH_ONLY,+ },+ userRoleId,+ }),+ ).toEqual({ applicationRoleId: null });+ },+ );++ it('adds no restriction without an application', () => {+ expect(resolveApplicationRoleId({ application: undefined })).toEqual({});});});diff --git a/packages/twenty-server/src/engine/permissions/principal/utils/__tests__/resolve-role-permission-config.util.spec.ts b/packages/twenty-server/src/engine/permissions/principal/utils/__tests__/resolve-role-permission-config.util.spec.tsindex 0dea5a81703..a27f16cec5d 100644--- a/packages/twenty-server/src/engine/permissions/principal/utils/__tests__/resolve-role-permission-config.util.spec.ts+++ b/packages/twenty-server/src/engine/permissions/principal/utils/__tests__/resolve-role-permission-config.util.spec.ts@@ -1,3 +1,4 @@+import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';import { type FlatRoleTargetByAgentIdMaps } from 'src/engine/metadata-modules/flat-agent/types/flat-role-target-by-agent-id-maps.type';import { resolveRolePermissionConfig } from 'src/engine/permissions/principal/utils/resolve-role-permission-config.util';@@ -16,7 +17,10 @@ const buildUserContext = ({application,}: {userWorkspaceId?: string;- application?: { defaultRoleId: string | null };+ application?: {+ defaultRoleId: string | null;+ sourceType?: ApplicationRegistrationSourceType;+ };} = {}): WorkspaceAuthContext =>({type: 'user',@@ -37,11 +41,12 @@ const buildApiKeyContext = (apiKeyId: string): WorkspaceAuthContext =>const buildApplicationContext = (defaultRoleId: string | null,+ sourceType?: ApplicationRegistrationSourceType,): WorkspaceAuthContext =>({type: 'application',workspace: { id: 'workspace-1' },- application: { defaultRoleId },+ application: { defaultRoleId, sourceType },}) as unknown as WorkspaceAuthContext;const withAgent = (@@ -91,10 +96,35 @@ describe('resolveRolePermissionConfig', () => {});});- it('adds no application restriction when the application has no role', () => {+ it('bounds a user acting through an OAuth-only application without a role by the user role alone', () => {expect(- resolve(buildUserContext({ application: { defaultRoleId: null } })),- ).toEqual({ intersectionOf: { userWorkspaceRoleId: USER_ROLE_ID } });+ resolve(+ buildUserContext({+ application: {+ defaultRoleId: null,+ sourceType: ApplicationRegistrationSourceType.OAUTH_ONLY,+ },+ }),+ ),+ ).toEqual({+ intersectionOf: {+ userWorkspaceRoleId: USER_ROLE_ID,+ applicationRoleId: USER_ROLE_ID,+ },+ });+ });++ it('allows nothing for a user acting through an installed application without a role', () => {+ expect(+ resolve(+ buildUserContext({+ application: {+ defaultRoleId: null,+ sourceType: ApplicationRegistrationSourceType.NPM,+ },+ }),+ ),+ ).toBeNull();});it('allows nothing for a user without a role, even with an application', () => {@@ -145,6 +175,20 @@ describe('resolveRolePermissionConfig', () => {expect(resolve(buildApplicationContext(null))).toBeNull();});+ it('allows nothing for an OAuth-only application without a role acting alone, even with an agent', () => {+ expect(+ resolve(+ withAgent(+ buildApplicationContext(+ null,+ ApplicationRegistrationSourceType.OAUTH_ONLY,+ ),+ AGENT_ID,+ ),+ ),+ ).toBeNull();+ });+it('narrows a user application token to the role of the agent it carries', () => {expect(resolve(diff --git a/packages/twenty-server/src/engine/permissions/principal/utils/build-user-role-ids-by-source.util.ts b/packages/twenty-server/src/engine/permissions/principal/utils/build-user-role-ids-by-source.util.tsindex 9183145c082..2628a7f3ab2 100644--- a/packages/twenty-server/src/engine/permissions/principal/utils/build-user-role-ids-by-source.util.ts+++ b/packages/twenty-server/src/engine/permissions/principal/utils/build-user-role-ids-by-source.util.ts@@ -1,3 +1,4 @@+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';import { type RoleIdsBySource } from 'src/engine/permissions/principal/types/role-permission-config.type';import { resolveApplicationRoleId } from 'src/engine/permissions/principal/utils/resolve-application-role-id.util';@@ -7,11 +8,10 @@ export const buildUserRoleIdsBySource = ({application,}: {userRoleId: string | null | undefined;- application: { defaultRoleId: string | null } | undefined;+ application:+ | Pick<FlatApplication, 'defaultRoleId' | 'sourceType'>+ | undefined;}): RoleIdsBySource => ({userWorkspaceRoleId: userRoleId ?? null,- ...resolveApplicationRoleId({- application,- isMissingApplicationRoleTolerated: true,- }),+ ...resolveApplicationRoleId({ application, userRoleId }),});diff --git a/packages/twenty-server/src/engine/permissions/principal/utils/resolve-application-role-id.util.ts b/packages/twenty-server/src/engine/permissions/principal/utils/resolve-application-role-id.util.tsindex 59c21b03bf5..83947b61d3d 100644--- a/packages/twenty-server/src/engine/permissions/principal/utils/resolve-application-role-id.util.ts+++ b/packages/twenty-server/src/engine/permissions/principal/utils/resolve-application-role-id.util.ts@@ -1,22 +1,34 @@import { isDefined } from 'twenty-shared/utils';+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';+import { isOAuthOnlyApplication } from 'src/engine/core-modules/application/utils/is-oauth-only-application.util';import { type RoleIdsBySource } from 'src/engine/permissions/principal/types/role-permission-config.type';-// Temporary: an application without a role adds no restriction when it acts with a-// member or an agent, which the workspace custom and Twenty standard applications rely on-// until they get a role. It covers every application without a role, not only those two.+// RoleIdsBySource tells no restriction (undefined) apart from allows nothing (null);+// we may want explicit literals for both instead of relying on that difference+const NO_APPLICATION_RESTRICTION = {} as const;++const APPLICATION_ALLOWS_NOTHING = { applicationRoleId: null } as const;++// OAuth-only applications have no role yet, so they act with the role of the member they act forexport const resolveApplicationRoleId = ({application,- isMissingApplicationRoleTolerated,+ userRoleId,}: {- application: { defaultRoleId: string | null } | undefined;- isMissingApplicationRoleTolerated: boolean;+ application:+ | Pick<FlatApplication, 'defaultRoleId' | 'sourceType'>+ | undefined;+ userRoleId?: string | null;}): Pick<RoleIdsBySource, 'applicationRoleId'> => {- const applicationRoleId = application?.defaultRoleId;+ if (!isDefined(application)) {+ return NO_APPLICATION_RESTRICTION;+ }- if (isDefined(applicationRoleId)) {- return { applicationRoleId };+ if (isDefined(application.defaultRoleId)) {+ return { applicationRoleId: application.defaultRoleId };}- return isMissingApplicationRoleTolerated ? {} : { applicationRoleId: null };+ return isOAuthOnlyApplication(application) && isDefined(userRoleId)+ ? { applicationRoleId: userRoleId }+ : APPLICATION_ALLOWS_NOTHING;};diff --git a/packages/twenty-server/src/engine/permissions/principal/utils/resolve-role-permission-config.util.ts b/packages/twenty-server/src/engine/permissions/principal/utils/resolve-role-permission-config.util.tsindex 887a3760113..04000ef9def 100644--- a/packages/twenty-server/src/engine/permissions/principal/utils/resolve-role-permission-config.util.ts+++ b/packages/twenty-server/src/engine/permissions/principal/utils/resolve-role-permission-config.util.ts@@ -11,7 +11,6 @@ import {} from 'src/engine/permissions/principal/types/role-permission-config.type';import { buildAgentRoleIdsBySource } from 'src/engine/permissions/principal/utils/build-agent-role-ids-by-source.util';import { buildUserRoleIdsBySource } from 'src/engine/permissions/principal/utils/build-user-role-ids-by-source.util';-import { resolveApplicationRoleId } from 'src/engine/permissions/principal/utils/resolve-application-role-id.util';import { isDenyingRoleIdsBySource } from 'src/engine/permissions/principal/utils/is-denying-role-ids-by-source.util';const resolveRoleIdsBySourceFromAuthContext = ({@@ -44,10 +43,7 @@ const resolveRoleIdsBySourceFromAuthContext = ({if (isApplicationAuthContext(authContext)) {return {- ...resolveApplicationRoleId({- application: authContext.application,- isMissingApplicationRoleTolerated: false,- }),+ applicationRoleId: authContext.application.defaultRoleId ?? null,...buildAgentRoleIdsBySource({agentId: authContext.agentId,flatRoleTargetByAgentIdMaps,diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.tsindex 05a0b364811..f687b665a73 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts@@ -305,10 +305,7 @@ export class DevSeederWorkflowPendingInputWorkspaceService {workflowRunId,stepId: step.id,}),- runSpec: buildWorkflowAgentRunSpec({- step,- isApplicationBound: false,- }),+ runSpec: buildWorkflowAgentRunSpec({ step }),summary: null,continuationCount: 0,},diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/services/__tests__/workflow-execution-context.service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/services/__tests__/workflow-execution-context.service.spec.tsindex 394143370c9..5a7676ad0b2 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/services/__tests__/workflow-execution-context.service.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/services/__tests__/workflow-execution-context.service.spec.ts@@ -1,17 +1,17 @@import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';-import { type Repository } from 'typeorm';+import { FieldActorSource } from 'twenty-shared/types';import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';-import { type ApplicationService } from 'src/engine/core-modules/application/application.service';import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';import { type UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';-import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';-import { type RoleService } from 'src/engine/metadata-modules/role/role.service';+import { type CoreEntityCacheService } from 'src/engine/core-entity-cache/services/core-entity-cache.service';import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';import { type WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';+const WORKSPACE_ID = 'workspace-id';const WORKSPACE_CUSTOM_APPLICATION_ID = 'workspace-custom-app-id';const authContext = {@@ -23,6 +23,8 @@ const installedApplication = {name: 'Installed app',universalIdentifier: 'installed-app-universal-identifier',sourceType: ApplicationRegistrationSourceType.NPM,+ defaultRoleId: 'installed-app-role-id',+ deletedAt: null,} as FlatApplication;const workspaceCustomApplication = {@@ -30,6 +32,8 @@ const workspaceCustomApplication = {name: 'Workspace',universalIdentifier: WORKSPACE_CUSTOM_APPLICATION_ID,sourceType: ApplicationRegistrationSourceType.LOCAL,+ defaultRoleId: 'workspace-custom-app-role-id',+ deletedAt: null,} as FlatApplication;const standardApplication = {@@ -37,42 +41,187 @@ const standardApplication = {name: 'Standard',universalIdentifier: TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,sourceType: ApplicationRegistrationSourceType.LOCAL,+ defaultRoleId: 'twenty-standard-app-role-id',+ deletedAt: null,} as FlatApplication;-describe('WorkflowExecutionContextService', () => {- const workflowExecutionContextService = new WorkflowExecutionContextService(- {} as WorkflowRunWorkspaceService,+const INSTALLED_APPLICATION_WORKFLOW_ID = 'installed-app-workflow-id';+const WORKSPACE_WORKFLOW_ID = 'workspace-workflow-id';++const workflows = [+ {+ id: INSTALLED_APPLICATION_WORKFLOW_ID,+ universalIdentifier: 'installed-app-workflow-universal-identifier',+ applicationId: installedApplication.id,+ },+ {+ id: WORKSPACE_WORKFLOW_ID,+ universalIdentifier: 'workspace-workflow-universal-identifier',+ applicationId: WORKSPACE_CUSTOM_APPLICATION_ID,+ },+];++const buildWorkflowRun = ({+ coreWorkflowId,+ stampedApplicationId,+}: {+ coreWorkflowId: string | null;+ stampedApplicationId?: string;+}) =>+ ({+ id: 'workflow-run-id',+ coreWorkflowId,+ createdBy: {+ source: FieldActorSource.WORKFLOW,+ workspaceMemberId: null,+ name: 'Workflow',+ context: { applicationId: stampedApplicationId },+ },+ }) as WorkflowRunWorkspaceEntity;++const buildService = ({+ workflowRun = buildWorkflowRun({ coreWorkflowId: WORKSPACE_WORKFLOW_ID }),+ applications = [installedApplication, workspaceCustomApplication],+}: {+ workflowRun?: WorkflowRunWorkspaceEntity;+ applications?: FlatApplication[];+} = {}) =>+ new WorkflowExecutionContextService(+ {+ getWorkflowRunOrFail: jest.fn().mockResolvedValue(workflowRun),+ } as unknown as WorkflowRunWorkspaceService,{} as UserWorkspaceService,- {} as ApplicationService,- {} as RoleService,- {} as WorkspaceCacheService,- {} as Repository<WorkspaceEntity>,+ {+ getOrRecompute: jest.fn().mockResolvedValue({+ flatApplicationMaps: {+ byId: Object.fromEntries(+ applications.map((application) => [application.id, application]),+ ),+ },+ flatWorkflowMaps: {+ byUniversalIdentifier: Object.fromEntries(+ workflows.map((workflow) => [+ workflow.universalIdentifier,+ workflow,+ ]),+ ),+ universalIdentifierById: Object.fromEntries(+ workflows.map((workflow) => [+ workflow.id,+ workflow.universalIdentifier,+ ]),+ ),+ },+ userWorkspaceRoleMap: {},+ }),+ } as unknown as WorkspaceCacheService,+ {+ get: jest.fn().mockResolvedValue({+ id: WORKSPACE_ID,+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,+ }),+ } as unknown as CoreEntityCacheService,);+const runInfo = { workflowRunId: 'workflow-run-id', workspaceId: WORKSPACE_ID };++describe('WorkflowExecutionContextService', () => {+ describe('getExecutionContext', () => {+ it('runs an automated run through the application owning its workflow, with its role', async () => {+ const executionContext = await buildService({+ workflowRun: buildWorkflowRun({+ coreWorkflowId: INSTALLED_APPLICATION_WORKFLOW_ID,+ }),+ }).getExecutionContext(runInfo);++ expect(executionContext.application).toBe(installedApplication);+ expect(executionContext.authContext).toMatchObject({+ type: 'application',+ application: installedApplication,+ });+ expect(executionContext.rolePermissionConfig).toEqual({+ intersectionOf: { applicationRoleId: 'installed-app-role-id' },+ });+ });++ it('takes the application from the workflow of the run, not from the one stamped on it', async () => {+ const executionContext = await buildService({+ workflowRun: buildWorkflowRun({+ coreWorkflowId: INSTALLED_APPLICATION_WORKFLOW_ID,+ stampedApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,+ }),+ }).getExecutionContext(runInfo);++ expect(executionContext.application).toBe(installedApplication);+ });++ it.each([null, 'deleted-workflow-id'])(+ 'refuses a run whose workflow no longer exists (workflow: %s)',+ async (coreWorkflowId) => {+ await expect(+ buildService({+ workflowRun: buildWorkflowRun({ coreWorkflowId }),+ }).getExecutionContext(runInfo),+ ).rejects.toThrow('The workflow of this run no longer exists');+ },+ );++ it('refuses a run whose application has no role instead of falling back to another one', async () => {+ await expect(+ buildService({+ workflowRun: buildWorkflowRun({+ coreWorkflowId: WORKSPACE_WORKFLOW_ID,+ }),+ applications: [+ { ...workspaceCustomApplication, defaultRoleId: null },+ ],+ }).getExecutionContext(runInfo),+ ).rejects.toThrow('has no role');+ });+ });++ describe('getFormRecordReadContext', () => {+ it('returns none for a workspace workflow run, so its forms read as before', async () => {+ const workflowRun = buildWorkflowRun({+ coreWorkflowId: WORKSPACE_WORKFLOW_ID,+ });++ expect(+ await buildService({ workflowRun }).getFormRecordReadContext({+ workflowRun,+ workspaceId: WORKSPACE_ID,+ }),+ ).toBeNull();+ });++ it('reads with the permissions of an installed application run', async () => {+ const workflowRun = buildWorkflowRun({+ coreWorkflowId: INSTALLED_APPLICATION_WORKFLOW_ID,+ stampedApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,+ });++ expect(+ await buildService({ workflowRun }).getFormRecordReadContext({+ workflowRun,+ workspaceId: WORKSPACE_ID,+ }),+ ).toMatchObject({ application: installedApplication });+ });+ });+describe('assertRunApplicationCanTriggerStepTargetOrThrow', () => {const assertTarget = ({application,targetApplicationId,}: {- application: FlatApplication | null;+ application: FlatApplication;targetApplicationId: string;}) =>- workflowExecutionContextService.assertRunApplicationCanTriggerStepTargetOrThrow(- {- executionContext: { application, authContext },- targetApplicationId,- targetLabel: 'Logic function "greet"',- },- );-- it('lets a run without an application use any function or agent', () => {- expect(() =>- assertTarget({- application: null,- targetApplicationId: 'other-app-id',- }),- ).not.toThrow();- });+ buildService().assertRunApplicationCanTriggerStepTargetOrThrow({+ executionContext: { application, authContext },+ targetApplicationId,+ targetLabel: 'Logic function "greet"',+ });it('lets a run use the functions and agents of its application', () => {expect(() =>diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/services/application-workflow-step-permission.service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/services/application-workflow-step-permission.service.tsindex 7ab1667b23e..96054c00ba8 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/services/application-workflow-step-permission.service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/services/application-workflow-step-permission.service.ts@@ -14,19 +14,18 @@ import {export class ApplicationWorkflowStepPermissionService {constructor(private readonly permissionsService: PermissionsService) {}- // Runs without an application keep the reach of whoever built the workflowasync assertRunApplicationMayUseStepOrThrow({workspaceId,runApplicationId,stepType,}: {workspaceId: string;- runApplicationId?: string;+ runApplicationId: string;stepType: WorkflowActionType;}): Promise<void> {const permissionFlag = APPLICATION_WORKFLOW_STEP_PERMISSION_FLAGS[stepType];- if (!isDefined(runApplicationId) || !isDefined(permissionFlag)) {+ if (!isDefined(permissionFlag)) {return;}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.module.tsindex 4240bdcaf48..e9234446cd4 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.module.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-execution-context.module.ts@@ -1,22 +1,17 @@import { Module } from '@nestjs/common';-import { TypeOrmModule } from '@nestjs/typeorm';-import { ApplicationModule } from 'src/engine/core-modules/application/application.module';+import { CoreEntityCacheModule } from 'src/engine/core-entity-cache/core-entity-cache.module';import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';-import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';-import { RoleModule } from 'src/engine/metadata-modules/role/role.module';import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';@Module({imports: [- ApplicationModule,- RoleModule,UserWorkspaceModule,WorkflowRunModule,WorkspaceCacheModule,- TypeOrmModule.forFeature([WorkspaceEntity]),+ CoreEntityCacheModule,],providers: [WorkflowExecutionContextService],exports: [WorkflowExecutionContextService],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 47055e0d7db..3e9d99fd33d 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@@ -1,24 +1,22 @@import { Injectable } from '@nestjs/common';-import { InjectRepository } from '@nestjs/typeorm';import { FieldActorSource } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';-import { Repository } from 'typeorm';-import { ApplicationService } from 'src/engine/core-modules/application/application.service';import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';import { canCallerReachApplication } from 'src/engine/core-modules/application/utils/can-caller-reach-application.util';import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';import { buildApplicationAuthContext } from 'src/engine/core-modules/auth/utils/build-application-auth-context.util';import { buildUserAuthContext } from 'src/engine/core-modules/auth/utils/build-user-auth-context.util';import { fromUserEntityToFlat } from 'src/engine/core-modules/user/utils/from-user-entity-to-flat.util';-import { fromWorkspaceEntityToFlat } from 'src/engine/core-modules/workspace/utils/from-workspace-entity-to-flat.util';-import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';-import { RoleService } from 'src/engine/metadata-modules/role/role.service';+import { CoreEntityCacheService } from 'src/engine/core-entity-cache/services/core-entity-cache.service';+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';+import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';+import { type FlatWorkflow } from 'src/engine/metadata-modules/flat-workflow/types/flat-workflow.type';import { resolveRolePermissionConfig } from 'src/engine/permissions/principal/utils/resolve-role-permission-config.util';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';-import { STANDARD_ROLE } from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-role.constant';import { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';import {WorkflowStepExecutorException,@@ -35,36 +33,47 @@ export class WorkflowExecutionContextService {constructor(private readonly workflowRunService: WorkflowRunService,private readonly userWorkspaceService: UserWorkspaceService,- private readonly applicationService: ApplicationService,- private readonly roleService: RoleService,private readonly workspaceCacheService: WorkspaceCacheService,- @InjectRepository(WorkspaceEntity)- private readonly workspaceRepository: Repository<WorkspaceEntity>,+ private readonly coreEntityCacheService: CoreEntityCacheService,) {}async getExecutionContext(runInfo: WorkflowRunInfo,): Promise<WorkflowExecutionContext> {- const workflowRun = await this.workflowRunService.getWorkflowRunOrFail({- workflowRunId: runInfo.workflowRunId,- workspaceId: runInfo.workspaceId,- });-- return this.buildExecutionContext(workflowRun, runInfo.workspaceId);+ const [workflowRun, workspace] = await Promise.all([+ this.workflowRunService.getWorkflowRunOrFail({+ workflowRunId: runInfo.workflowRunId,+ workspaceId: runInfo.workspaceId,+ }),+ this.findWorkspaceOrThrow(runInfo.workspaceId),+ ]);++ return this.buildExecutionContext(workflowRun, workspace);}- async getApplicationBoundExecutionContext({+ // workspace workflow forms still read picked records unrestricted, relations included+ async getFormRecordReadContext({workflowRun,workspaceId,}: {workflowRun: WorkflowRunWorkspaceEntity;workspaceId: string;}): Promise<WorkflowExecutionContext | null> {- if (!isDefined(workflowRun.createdBy.context?.applicationId)) {+ const [workspace, { flatWorkflowMaps }] = await Promise.all([+ this.findWorkspaceOrThrow(workspaceId),+ this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatWorkflowMaps',+ ]),+ ]);++ if (+ this.getRunApplicationId(workflowRun, flatWorkflowMaps) ===+ workspace.workspaceCustomApplicationId+ ) {return null;}- return this.buildExecutionContext(workflowRun, workspaceId);+ return this.buildExecutionContext(workflowRun, workspace);}assertRunApplicationCanTriggerStepTargetOrThrow({@@ -80,7 +89,6 @@ export class WorkflowExecutionContextService {targetLabel: string;}): void {if (- !isDefined(application) ||canCallerReachApplication({callingApplication: application,applicationId: targetApplicationId,@@ -100,25 +108,31 @@ export class WorkflowExecutionContextService {private async buildExecutionContext(workflowRun: WorkflowRunWorkspaceEntity,- workspaceId: string,+ workspace: FlatWorkspace,): Promise<WorkflowExecutionContext> {- const application = await this.findRunApplication(workflowRun, workspaceId);+ const { flatApplicationMaps, flatWorkflowMaps, userWorkspaceRoleMap } =+ await this.workspaceCacheService.getOrRecompute(workspace.id, [+ 'flatApplicationMaps',+ 'flatWorkflowMaps',+ 'userWorkspaceRoleMap',+ ]);++ const application = resolveWorkflowRunApplicationOrThrow({+ applicationId: this.getRunApplicationId(workflowRun, flatWorkflowMaps),+ applicationsById: flatApplicationMaps.byId,+ });const isActingOnBehalfOfUser =workflowRun.createdBy.source === FieldActorSource.MANUAL &&isDefined(workflowRun.createdBy.workspaceMemberId);- const authContext = await this.buildAuthContext({- workflowRun,- workspaceId,- application,- isActingOnBehalfOfUser,- });-- const { userWorkspaceRoleMap } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'userWorkspaceRoleMap',- ]);+ const authContext = isActingOnBehalfOfUser+ ? await this.buildMemberAuthContext({+ workflowRun,+ workspace,+ application,+ })+ : buildApplicationAuthContext({ workspace, application });const rolePermissionConfig = resolveRolePermissionConfig({authContext,@@ -143,67 +157,51 @@ export class WorkflowExecutionContextService {};}- private async findRunApplication(- workflowRun: WorkflowRunWorkspaceEntity,- workspaceId: string,- ): Promise<FlatApplication | null> {- if (!isDefined(workflowRun.createdBy.context?.applicationId)) {- return null;+ private getRunApplicationId(+ workflowRun: Pick<WorkflowRunWorkspaceEntity, 'coreWorkflowId'>,+ flatWorkflowMaps: FlatEntityMaps<FlatWorkflow>,+ ): string {+ const workflow = isDefined(workflowRun.coreWorkflowId)+ ? findFlatEntityByIdInFlatEntityMaps({+ flatEntityId: workflowRun.coreWorkflowId,+ flatEntityMaps: flatWorkflowMaps,+ })+ : undefined;++ if (!isDefined(workflow)) {+ throw new WorkflowStepExecutorException(+ 'The workflow of this run no longer exists',+ WorkflowStepExecutorExceptionCode.FORBIDDEN,+ );}- const { flatApplicationMaps } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'flatApplicationMaps',- ]);-- return resolveWorkflowRunApplicationOrThrow({- workflowRun,- applicationsById: flatApplicationMaps.byId,- });+ return workflow.applicationId;}- private buildAuthContext({+ private async buildMemberAuthContext({workflowRun,- workspaceId,+ workspace,application,- isActingOnBehalfOfUser,}: {workflowRun: WorkflowRunWorkspaceEntity;- workspaceId: string;- application: FlatApplication | null;- isActingOnBehalfOfUser: boolean;+ workspace: FlatWorkspace;+ application: FlatApplication;}): Promise<WorkspaceAuthContext> {- if (isActingOnBehalfOfUser) {- return this.buildMemberAuthContext(workflowRun, workspaceId, application);- }-- if (isDefined(application)) {- return this.buildBoundApplicationAuthContext(workspaceId, application);- }-- return this.buildStandardApplicationAuthContext(workspaceId);- }-- private async buildMemberAuthContext(- workflowRun: WorkflowRunWorkspaceEntity,- workspaceId: string,- application: FlatApplication | null,- ): Promise<WorkspaceAuthContext> {const workspaceMember =await this.userWorkspaceService.getWorkspaceMemberOrThrow({workspaceMemberId: workflowRun.createdBy.workspaceMemberId!,- workspaceId,+ workspaceId: workspace.id,});const userWorkspace =await this.userWorkspaceService.getUserWorkspaceForUserOrThrow({userId: workspaceMember.userId,- workspaceId,- relations: ['workspace', 'user'],+ workspaceId: workspace.id,+ relations: ['user'],});return buildUserAuthContext({- workspace: fromWorkspaceEntityToFlat(userWorkspace.workspace),+ workspace,userWorkspaceId: userWorkspace.id,user: fromUserEntityToFlat(userWorkspace.user),workspaceMemberId: workspaceMember.id,@@ -212,47 +210,21 @@ export class WorkflowExecutionContextService {});}- private async buildBoundApplicationAuthContext(+ private async findWorkspaceOrThrow(workspaceId: string,- application: FlatApplication,- ): Promise<WorkspaceAuthContext> {- const workspace = await this.workspaceRepository.findOneOrFail({- where: { id: workspaceId },- });-- return buildApplicationAuthContext({- workspace: fromWorkspaceEntityToFlat(workspace),- application,- });- }+ ): Promise<FlatWorkspace> {+ const workspace = await this.coreEntityCacheService.get(+ 'workspaceEntity',+ workspaceId,+ );- private async buildStandardApplicationAuthContext(- workspaceId: string,- ): Promise<WorkspaceAuthContext> {- const { application, workspace } =- await this.applicationService.findTwentyStandardApplicationOrThrow(- workspaceId,+ if (!isDefined(workspace)) {+ throw new WorkflowStepExecutorException(+ 'Workspace not found',+ WorkflowStepExecutorExceptionCode.SCOPED_WORKSPACE_NOT_FOUND,);-- // In the future we should probably assign the Admin role to the Standard Application- let roleId = application.defaultRoleId;-- if (!isDefined(roleId)) {- // Fallback: Look up admin role for existing workspaces without defaultRoleId- const adminRole = await this.roleService.getRoleByUniversalIdentifier({- universalIdentifier: STANDARD_ROLE.admin.universalIdentifier,- workspaceId,- });-- roleId = adminRole?.id ?? null;}- return buildApplicationAuthContext({- workspace: fromWorkspaceEntityToFlat(workspace),- application: {- ...application,- defaultRoleId: roleId,- },- });+ return workspace;}}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-execution-context.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-execution-context.type.tsindex f13f4c6898b..d835cf61c00 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-execution-context.type.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-execution-context.type.ts@@ -9,5 +9,5 @@ export type WorkflowExecutionContext = {initiator: ActorMetadata;rolePermissionConfig: RolePermissionConfig;authContext: WorkspaceAuthContext;- application: FlatApplication | null;+ application: FlatApplication;};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 46a90e2f972..dd763fa901c 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@@ -22,7 +22,6 @@ const build = ({buildWorkflowRunCreatedBy({source: buildSource(startingApplicationId),workflowApplicationId,- workspaceCustomApplicationId: CUSTOM_APPLICATION_ID,});describe('buildWorkflowRunCreatedBy', () => {@@ -39,16 +38,16 @@ describe('buildWorkflowRunCreatedBy', () => {).toBe(INSTALLED_APPLICATION_ID);});- it('leaves a run of a workspace workflow unbound, whoever starts it', () => {+ it('binds a run of a workspace workflow to the workspace custom application, whoever starts it', () => {expect(build({ workflowApplicationId: CUSTOM_APPLICATION_ID }).context.applicationId,- ).toBeUndefined();+ ).toBe(CUSTOM_APPLICATION_ID);expect(build({workflowApplicationId: CUSTOM_APPLICATION_ID,startingApplicationId: INSTALLED_APPLICATION_ID,}).context.applicationId,- ).toBeUndefined();+ ).toBe(CUSTOM_APPLICATION_ID);});});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/resolve-workflow-run-application-or-throw.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/resolve-workflow-run-application-or-throw.util.spec.tsindex 5f29d07c705..6766c433100 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/resolve-workflow-run-application-or-throw.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/resolve-workflow-run-application-or-throw.util.spec.ts@@ -1,5 +1,3 @@-import { FieldActorSource } from 'twenty-shared/types';-import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';import { resolveWorkflowRunApplicationOrThrow } from 'src/modules/workflow/workflow-executor/utils/resolve-workflow-run-application-or-throw.util';@@ -17,55 +15,28 @@ const INSTALLED_APPLICATION: TestApplication = {deletedAt: null,};-const resolve = ({- applicationId,- application = INSTALLED_APPLICATION,-}: {- applicationId?: string;- application?: TestApplication | null;-}) =>+const resolve = (application: TestApplication | null) =>resolveWorkflowRunApplicationOrThrow({- workflowRun: {- createdBy: {- source: FieldActorSource.MANUAL,- workspaceMemberId: 'member-id',- name: 'Tim Apple',- context: { applicationId },- },- },+ applicationId: INSTALLED_APPLICATION_ID,applicationsById: application ? { [application.id]: application } : {},});describe('resolveWorkflowRunApplicationOrThrow', () => {- it('leaves a run that no application bounds unbound', () => {- expect(resolve({})).toBeNull();- });-- it('returns the application the run was bound to', () => {- expect(resolve({ applicationId: INSTALLED_APPLICATION_ID })).toBe(- INSTALLED_APPLICATION,- );+ it('returns the application the run acts through', () => {+ expect(resolve(INSTALLED_APPLICATION)).toBe(INSTALLED_APPLICATION);});it('refuses a run whose application is no longer installed', () => {- expect(() =>- resolve({ applicationId: INSTALLED_APPLICATION_ID, application: null }),- ).toThrow('no longer installed');+ expect(() => resolve(null)).toThrow('no longer installed');expect(() =>- resolve({- applicationId: INSTALLED_APPLICATION_ID,- application: { ...INSTALLED_APPLICATION, deletedAt: new Date() },- }),+ resolve({ ...INSTALLED_APPLICATION, deletedAt: new Date() }),).toThrow('no longer installed');});it('refuses a run whose application has no role rather than widening it', () => {expect(() =>- resolve({- applicationId: INSTALLED_APPLICATION_ID,- application: { ...INSTALLED_APPLICATION, defaultRoleId: null },- }),+ resolve({ ...INSTALLED_APPLICATION, defaultRoleId: null }),).toThrow('has no role');});});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 d556f9c9a96..134bf946a3b 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,26 +1,19 @@import { type ActorMetadata } from 'twenty-shared/types';-// Only workflows of installed applications bind their runs; the workspace custom application acts across applications+// A run acts through the application owning its workflow, whoever starts itexport const buildWorkflowRunCreatedBy = ({source,workflowApplicationId,- workspaceCustomApplicationId,}: {source: ActorMetadata;workflowApplicationId: string;- workspaceCustomApplicationId: string;}): ActorMetadata => {- const runApplicationId =- workflowApplicationId === workspaceCustomApplicationId- ? undefined- : workflowApplicationId;-- if (source.context?.applicationId === runApplicationId) {+ if (source.context?.applicationId === workflowApplicationId) {return source;}return {...source,- context: { ...source.context, applicationId: runApplicationId },+ context: { ...source.context, applicationId: workflowApplicationId },};};diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/resolve-workflow-run-application-or-throw.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/resolve-workflow-run-application-or-throw.util.tsindex 4a3be3346ae..f6dd2bc321b 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/resolve-workflow-run-application-or-throw.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/resolve-workflow-run-application-or-throw.util.ts@@ -1,7 +1,6 @@import { isDefined } from 'twenty-shared/utils';import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';-import { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';import {WorkflowStepExecutorException,WorkflowStepExecutorExceptionCode,@@ -13,18 +12,12 @@ export const resolveWorkflowRunApplicationOrThrow = <'name' | 'deletedAt' | 'defaultRoleId'>,>({- workflowRun,+ applicationId,applicationsById,}: {- workflowRun: Pick<WorkflowRunWorkspaceEntity, 'createdBy'>;+ applicationId: string;applicationsById: Partial<Record<string, TApplication>>;-}): TApplication | null => {- const applicationId = workflowRun.createdBy.context?.applicationId;-- if (!isDefined(applicationId)) {- return null;- }-+}): TApplication => {const application = applicationsById[applicationId];if (!isDefined(application) || isDefined(application.deletedAt)) {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 df34842c13f..bfa8d9b79a4 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@@ -6,7 +6,6 @@ import { isDefined, isValidUuid, resolveInput } from 'twenty-shared/utils';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';-import { isWorkspaceCustomApplication } from 'src/engine/core-modules/application/utils/is-workspace-custom-application.util';import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';import { buildStartedAgentRunSummary } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-started-agent-run-summary.util';import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';@@ -163,17 +162,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {workflowRunId: runInfo.workflowRunId,stepId: currentStepId,}),- spec: buildWorkflowAgentRunSpec({- step,- isApplicationBound:- isDefined(executionContext.application) &&- !isWorkspaceCustomApplication({- application: executionContext.application,- workspaceCustomApplicationId:- executionContext.authContext.workspace- .workspaceCustomApplicationId,- }),- }),+ spec: buildWorkflowAgentRunSpec({ step }),prompt: isDefined(resolvedPrompt)? {messages: [{ role: 'user', content: resolvedPrompt }],diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant.tsdeleted file mode 100644index d980d70cbf4..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant.ts+++ /dev/null@@ -1,18 +0,0 @@-import { type ActionToolId } from 'src/engine/core-modules/tool-provider/constants/action-tool-label.constant';-import { SEND_CAMPAIGN_TEST_TOOL_NAME } from 'src/modules/emailing/constants/send-campaign-test-tool-name.constant';-import { SEND_CAMPAIGN_TOOL_NAME } from 'src/modules/emailing/constants/send-campaign-tool-name.constant';--export const APPLICATION_BOUND_AGENT_EXCLUDED_TOOL_NAMES = [- 'code_interpreter',- 'save_campaign',- SEND_CAMPAIGN_TOOL_NAME,- SEND_CAMPAIGN_TEST_TOOL_NAME,- 'send_email',- 'draft_email',- 'find_connected_accounts',- 'create_calendar_event',-] as const satisfies readonly (- | ActionToolId- | typeof SEND_CAMPAIGN_TOOL_NAME- | typeof SEND_CAMPAIGN_TEST_TOOL_NAME-)[];diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.tsindex 2936993936e..97e25a03581 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts@@ -30,7 +30,6 @@ describe('buildWorkflowAgentRunSpec', () => {prompt: 'Draft the quote',humanInputInstructions: ' ',}),- isApplicationBound: false,});expect(spec).toMatchObject({@@ -50,7 +49,6 @@ describe('buildWorkflowAgentRunSpec', () => {agentId: 'agent-id',humanInputInstructions: ' Ask before choosing a plan. ',}),- isApplicationBound: false,});expect(spec.agentId).toBe('agent-id');@@ -60,15 +58,6 @@ describe('buildWorkflowAgentRunSpec', () => {expect(spec.instructions).toMatch(/Ask before choosing a plan\.$/);});- it('keeps tools out of reach of an application-bound run', () => {- expect(- buildWorkflowAgentRunSpec({- step: buildStep({ agentId: 'agent-id', prompt: 'Draft the quote' }),- isApplicationBound: true,- }).additionalExcludedToolNames,- ).toContain('send_email');- });-it("asks for the step's output format", () => {const responseFormat = {type: 'json' as const,@@ -80,7 +69,6 @@ describe('buildWorkflowAgentRunSpec', () => {const spec = buildWorkflowAgentRunSpec({step: buildStep({ agentId: 'agent-id', responseFormat }),- isApplicationBound: false,});expect(spec.responseFormat).toEqual(responseFormat);@@ -89,7 +77,6 @@ describe('buildWorkflowAgentRunSpec', () => {it("leaves the agent's output format to apply when the step gives none", () => {const spec = buildWorkflowAgentRunSpec({step: buildStep({ agentId: 'agent-id' }),- isApplicationBound: false,});expect(spec).not.toHaveProperty('responseFormat');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 e5ffb10bade..cc2d7072988 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@@ -1,5 +1,4 @@import { type ActorMetadata } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';import { type AgentRunExecutionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type';@@ -41,7 +40,5 @@ export const buildWorkflowAgentRunExecutionContext = ({agentRunRoleIds: getAgentRunRoleIdsFromRolePermissionConfig(executionContext.rolePermissionConfig,),- ...(isDefined(executionContext.application)- ? { application: executionContext.application }- : {}),+ application: executionContext.application,});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.tsindex 8a3d9aa05ee..7f376597ed6 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts@@ -4,16 +4,13 @@ import { isDefined } from 'twenty-shared/utils';import { type AgentRunSpec } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type';import { WORKFLOW_BASE_SYSTEM_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-base-system-prompt.constant';import { type WorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';-import { APPLICATION_BOUND_AGENT_EXCLUDED_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant';import { WORKFLOW_AGENT_HUMAN_INPUT_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant';// what the engine needs to run the step's agent, and to continue it after a pauseexport const buildWorkflowAgentRunSpec = ({step,- isApplicationBound,}: {step: WorkflowAiAgentAction;- isApplicationBound: boolean;}): AgentRunSpec => {const { agentId, humanInputInstructions, responseFormat } =step.settings.input;@@ -31,12 +28,5 @@ export const buildWorkflowAgentRunSpec = ({canAskHumans,},...(isDefined(responseFormat) ? { responseFormat } : {}),- ...(isApplicationBound- ? {- additionalExcludedToolNames: [- ...APPLICATION_BOUND_AGENT_EXCLUDED_TOOL_NAMES,- ],- }- : {}),};};diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.tsindex 33e1ef28d3b..20315b6a648 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts@@ -182,7 +182,7 @@ export class WorkflowExecutorWorkspaceService {workflowRunId,workspaceId,billingSpenders,- runApplicationId: workflowRun.createdBy.context?.applicationId,+ runApplicationId: workflow.applicationId,}));if (isDefined(actionOutput.error) && !actionOutput.isUserError) {@@ -587,7 +587,7 @@ export class WorkflowExecutorWorkspaceService {workflowRunId: string;workspaceId: string;billingSpenders: WorkflowBillingSpenders;- runApplicationId?: string;+ runApplicationId: string;}) {const stepId = step.id;diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/services/__tests__/core-workflow-runner.service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/services/__tests__/core-workflow-runner.service.spec.tsindex 5a8192adece..b072bd14fc4 100644--- a/packages/twenty-server/src/modules/workflow/workflow-runner/services/__tests__/core-workflow-runner.service.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/services/__tests__/core-workflow-runner.service.spec.ts@@ -74,13 +74,6 @@ const buildService = (triggerType: WorkflowTriggerType) => {increaseWorkflowRunNotStartedCount: jest.fn(),} as never,{} as never,- {- findWorkspaceTwentyStandardAndCustomApplicationOrThrow: jest- .fn()- .mockResolvedValue({- workspaceCustomFlatApplication: { id: 'workspace-custom-app' },- }),- } as never,new WorkflowRunJobScopeWorkspaceService(workspaceCacheService as never,{} as never,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 21e40c5efec..cbb6c150e6e 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@@ -3,7 +3,6 @@ import { Injectable, Logger } from '@nestjs/common';import { type ActorMetadata } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';-import { ApplicationService } from 'src/engine/core-modules/application/application.service';import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';@@ -41,7 +40,6 @@ export class CoreWorkflowRunnerService {private readonly billingUsageService: BillingUsageService,private readonly workflowThrottlingWorkspaceService: WorkflowThrottlingWorkspaceService,private readonly metricsService: MetricsService,- private readonly applicationService: ApplicationService,private readonly workflowRunJobScopeWorkspaceService: WorkflowRunJobScopeWorkspaceService,@InjectMessageQueue(MessageQueue.workflowQueue)private readonly messageQueueService: MessageQueueService,@@ -119,14 +117,9 @@ export class CoreWorkflowRunnerService {: isManualTrigger? WorkflowRunStatus.ENQUEUED: WorkflowRunStatus.NOT_STARTED;- const { workspaceCustomFlatApplication } =- await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(- { workspaceId },- );const createdBy = buildWorkflowRunCreatedBy({source,workflowApplicationId: workflow.applicationId,- workspaceCustomApplicationId: workspaceCustomFlatApplication.id,});const createdWorkflowRunId =await this.workflowRunWorkspaceService.createCoreWorkflowRun({diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.tsindex c65c69e3307..ad9de1be16e 100644--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts@@ -198,24 +198,23 @@ export class WorkflowRunnerWorkspaceService {return undefined;}- const applicationBoundExecutionContext =- await this.workflowExecutionContextService- .getApplicationBoundExecutionContext({ workflowRun, workspaceId })- .catch((error: unknown) => {- if (error instanceof WorkflowStepExecutorException) {- throw new WorkflowVersionStepException(- error.message,- WorkflowVersionStepExceptionCode.INVALID_REQUEST,- {- userFriendlyMessage: msg`The permissions of this run no longer allow submitting this form.`,- },- );- }-- throw error;- });+ const formRecordReadContext = await this.workflowExecutionContextService+ .getFormRecordReadContext({ workflowRun, workspaceId })+ .catch((error: unknown) => {+ if (error instanceof WorkflowStepExecutorException) {+ throw new WorkflowVersionStepException(+ error.message,+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,+ {+ userFriendlyMessage: msg`The permissions of this run no longer allow submitting this form.`,+ },+ );+ }++ throw error;+ });- return applicationBoundExecutionContext ?? undefined;+ return formRecordReadContext ?? undefined;}async stopWorkflowRun(workspaceId: string, workflowRunId: string) {diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.tsindex 564c31c8396..cb5fdebf4c1 100644--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts@@ -45,7 +45,6 @@ import {type UpdateEventTriggerSettings,} from 'src/modules/workflow/workflow-trigger/automated-trigger/constants/automated-trigger-settings';import { resolveEventsReadableByRole } from 'src/engine/permissions/combine/utils/resolve-events-readable-by-role.util';-import { resolveAutomationAdmittedRecordIds } from 'src/engine/permissions/combine/utils/resolve-automation-admitted-record-ids.util';import { type CoreDispatchIds } from 'src/engine/core-modules/workflow/types/workflow-automated-trigger-maps.type';import {WorkflowTriggerJob,@@ -402,10 +401,12 @@ export class WorkflowDatabaseEventTriggerListener {admittedEventsByApplicationId.set(applicationId,await this.resolveAdmittedEvents({- payload,- enrichedPayload,+ workspaceEventBatch: standardAndCustomApplicationIds.has(+ applicationId,+ )+ ? enrichedPayload+ : payload,applicationId,- standardAndCustomApplicationIds,}),);}@@ -492,43 +493,30 @@ export class WorkflowDatabaseEventTriggerListener {}private async resolveAdmittedEvents({- payload,- enrichedPayload,+ workspaceEventBatch,applicationId,- standardAndCustomApplicationIds,}: {- payload: WorkspaceEventBatch<ObjectRecordEvent>;- enrichedPayload: WorkspaceEventBatch<ObjectRecordEvent>;+ workspaceEventBatch: WorkspaceEventBatch<ObjectRecordEvent>;applicationId: string;- standardAndCustomApplicationIds: Set<string>;}): Promise<ObjectRecordEvent[]> {- if (standardAndCustomApplicationIds.has(applicationId)) {- const admittedRecordIds = await resolveAutomationAdmittedRecordIds({- payload: enrichedPayload,- workspaceCacheService: this.workspaceCacheService,- recordAccessPolicyService: this.recordAccessPolicyService,- });-- return enrichedPayload.events.filter((event) =>- admittedRecordIds.has(event.recordId),- );- }-const { flatApplicationMaps } =- await this.workspaceCacheService.getOrRecompute(payload.workspaceId, [- 'flatApplicationMaps',- ]);+ await this.workspaceCacheService.getOrRecompute(+ workspaceEventBatch.workspaceId,+ ['flatApplicationMaps'],+ );return resolveEventsReadableByRole({roleId:findActiveFlatApplicationById(flatApplicationMaps, applicationId)?.defaultRoleId ?? null,- workspaceEventBatch: payload,+ workspaceEventBatch,eventRecordAccessGate:- this.recordAccessPolicyService.buildEventRecordAccessGate(payload),+ this.recordAccessPolicyService.buildEventRecordAccessGate(+ workspaceEventBatch,+ ),metadataMaps:await this.recordAccessPolicyService.loadPermissionsMetadataMaps(- payload.workspaceId,+ workspaceEventBatch.workspaceId,),});}diff --git a/packages/twenty-server/test/integration/graphql/suites/settings-permissions/settings-permission-resolution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/settings-permissions/settings-permission-resolution.integration-spec.tsindex 7777af3daa8..c5c857ba591 100644--- a/packages/twenty-server/test/integration/graphql/suites/settings-permissions/settings-permission-resolution.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/settings-permissions/settings-permission-resolution.integration-spec.ts@@ -390,8 +390,8 @@ describe('Settings permission resolution', () => {);});- it('bounds the user by the user role alone when the application has no default role', async () => {- expectAllowed(+ it('denies a user acting through an application without a default role', async () => {+ expectPermissionDenied(await queryApiKeys(await generateApplicationAccessToken({applicationId: rolelessApplication.id,diff --git a/packages/twenty-server/test/integration/metadata/suites/application-default-role/successful-automated-workflow-run-standard-application-default-role.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application-default-role/successful-automated-workflow-run-application-default-role.integration-spec.tssimilarity index 74%rename from packages/twenty-server/test/integration/metadata/suites/application-default-role/successful-automated-workflow-run-standard-application-default-role.integration-spec.tsrename to packages/twenty-server/test/integration/metadata/suites/application-default-role/successful-automated-workflow-run-application-default-role.integration-spec.tsindex faf1c002310..ac62d5fbe0b 100644--- a/packages/twenty-server/test/integration/metadata/suites/application-default-role/successful-automated-workflow-run-standard-application-default-role.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/application-default-role/successful-automated-workflow-run-application-default-role.integration-spec.ts@@ -7,16 +7,19 @@ import {updateCoreWorkflowVersionTrigger,} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';-import { findApplicationDefaultRole } from 'test/integration/metadata/suites/application-default-role/utils/find-application-default-role.util';+import {+ findApplicationDefaultRole,+ findWorkspaceCustomApplicationId,+} from 'test/integration/metadata/suites/application-default-role/utils/find-application-default-role.util';import { expectEventually } from 'test/integration/utils/expect-eventually.util';import { isDefined } from 'twenty-shared/utils';import { WorkflowActionType } from 'twenty-shared/workflow';-import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';-import { STANDARD_ROLE } from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-role.constant';+import { WORKSPACE_CUSTOM_APPLICATION_ROLE_UNIVERSAL_IDENTIFIER } from 'src/engine/core-modules/application/constants/workspace-custom-application-role.constant';type WorkflowRun = {status: string;+ createdBy: { context: { applicationId: string | null } | null };state: {stepInfos: Record<string, { result?: { totalCount?: number | string } }>;};@@ -28,7 +31,7 @@ const findWorkflowRuns = async (const response = await workflowGraphqlRequest(`query WorkflowRuns($coreWorkflowId: UUID!) {workflowRuns(filter: { coreWorkflowId: { eq: $coreWorkflowId } }) {- edges { node { status state } }+ edges { node { status state createdBy { context { applicationId } } } }}}`,{ coreWorkflowId },@@ -41,7 +44,7 @@ const findWorkflowRuns = async ();};-describe('An automated workflow run acts with the standard application default role', () => {+describe('An automated workflow run acts with the default role of its workflow application', () => {let coreWorkflowId: string | undefined;let findCompaniesStepId: string;let companyId: string | undefined;@@ -50,7 +53,7 @@ describe('An automated workflow run acts with the standard application default rjest.useRealTimers();const createdCoreWorkflow = await createCoreWorkflow({- name: 'Automated run with the standard application role',+ name: 'Automated run with its application role',});coreWorkflowId = createdCoreWorkflow.coreWorkflowId;@@ -102,15 +105,14 @@ describe('An automated workflow run acts with the standard application default r}});- it('reads records with Admin as the standard application default role', async () => {- const standardApplicationDefaultRole = await findApplicationDefaultRole({- input: {- universalIdentifier: TWENTY_STANDARD_APPLICATION.universalIdentifier,- },+ it('reads records through the workspace custom application and its default role', async () => {+ const customApplicationId = await findWorkspaceCustomApplicationId();+ const customApplicationDefaultRole = await findApplicationDefaultRole({+ input: { id: customApplicationId },});- expect(standardApplicationDefaultRole?.universalIdentifier).toBe(- STANDARD_ROLE.admin.universalIdentifier,+ expect(customApplicationDefaultRole?.universalIdentifier).toBe(+ WORKSPACE_CUSTOM_APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,);const response = await workflowGraphqlRequest(@@ -128,6 +130,10 @@ describe('An automated workflow run acts with the standard application default rexpect(workflowRun?.status).toBe('COMPLETED');});+ expect(workflowRun?.createdBy.context?.applicationId).toBe(+ customApplicationId,+ );+expect(Number(workflowRun?.state.stepInfos[findCompaniesStepId]?.result?.totalCount,