Skip to content

The open alternative to Salesforce, designed for AI.

Declare application reach per operation (#28710)

Paul Rastoinf17b193e10c2
diff --git a/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts b/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
index d02ae59a0e9..eb319bf33ff 100644
--- a/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
+++ b/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
@@ -316,6 +316,7 @@ export class McpProtocolService {
userId: options?.userId,
userWorkspaceId: options?.userWorkspaceId,
excludeTools: MCP_EXCLUDED_TOOL_NAMES,
+ authContext: options?.authContext,
application: options?.application,
}),
annotations: MCP_CLOSED_WORLD_READ_ONLY_TOOL_ANNOTATIONS,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application.resolver.ts
index 90faf9935e3..64a8221ad80 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application.resolver.ts
@@ -139,7 +139,8 @@ export class ApplicationResolver {
@ResolveField(() => [AgentDTO])
agents(
@Parent() application: Pick<ApplicationDTO, 'id'>,
- @AuthWorkspace() workspace: WorkspaceEntity,
+ @AuthWorkspace()
+ { id: workspaceId, workspaceCustomApplicationId }: WorkspaceEntity,
@Context() context: { loaders: IDataloaders },
@AuthApplication({ allowUndefined: true })
callingApplication: FlatApplication | undefined,
@@ -148,13 +149,15 @@ export class ApplicationResolver {
!canCallerReachApplication({
callingApplication,
applicationId: application.id,
+ operation: 'read',
+ workspaceCustomApplicationId,
})
) {
return [];
}
return context.loaders.agentsByApplicationIdLoader.load({
- workspaceId: workspace.id,
+ workspaceId,
applicationId: application.id,
});
}
@@ -162,7 +165,8 @@ export class ApplicationResolver {
@ResolveField(() => [FrontComponentDTO])
frontComponents(
@Parent() application: Pick<ApplicationDTO, 'id'>,
- @AuthWorkspace() workspace: WorkspaceEntity,
+ @AuthWorkspace()
+ { id: workspaceId, workspaceCustomApplicationId }: WorkspaceEntity,
@Context() context: { loaders: IDataloaders },
@AuthApplication({ allowUndefined: true })
callingApplication: FlatApplication | undefined,
@@ -171,13 +175,15 @@ export class ApplicationResolver {
!canCallerReachApplication({
callingApplication,
applicationId: application.id,
+ operation: 'read',
+ workspaceCustomApplicationId,
})
) {
return [];
}
return context.loaders.frontComponentsByApplicationIdLoader.load({
- workspaceId: workspace.id,
+ workspaceId,
applicationId: application.id,
});
}
@@ -185,7 +191,8 @@ export class ApplicationResolver {
@ResolveField(() => [CommandMenuItemDTO])
commandMenuItems(
@Parent() application: Pick<ApplicationDTO, 'id'>,
- @AuthWorkspace() workspace: WorkspaceEntity,
+ @AuthWorkspace()
+ { id: workspaceId, workspaceCustomApplicationId }: WorkspaceEntity,
@Context() context: { loaders: IDataloaders },
@AuthApplication({ allowUndefined: true })
callingApplication: FlatApplication | undefined,
@@ -194,13 +201,15 @@ export class ApplicationResolver {
!canCallerReachApplication({
callingApplication,
applicationId: application.id,
+ operation: 'read',
+ workspaceCustomApplicationId,
})
) {
return [];
}
return context.loaders.commandMenuItemsByApplicationIdLoader.load({
- workspaceId: workspace.id,
+ workspaceId,
applicationId: application.id,
});
}
@@ -208,7 +217,8 @@ export class ApplicationResolver {
@ResolveField(() => [SettingsMenuItemDTO], { nullable: true })
settingsMenuItems(
@Parent() application: Pick<ApplicationDTO, 'id'>,
- @AuthWorkspace() workspace: WorkspaceEntity,
+ @AuthWorkspace()
+ { id: workspaceId, workspaceCustomApplicationId }: WorkspaceEntity,
@Context() context: { loaders: IDataloaders },
@AuthApplication({ allowUndefined: true })
callingApplication: FlatApplication | undefined,
@@ -217,13 +227,15 @@ export class ApplicationResolver {
!canCallerReachApplication({
callingApplication,
applicationId: application.id,
+ operation: 'read',
+ workspaceCustomApplicationId,
})
) {
return [];
}
return context.loaders.settingsMenuItemsByApplicationIdLoader.load({
- workspaceId: workspace.id,
+ workspaceId,
applicationId: application.id,
});
}
@@ -231,7 +243,8 @@ export class ApplicationResolver {
@ResolveField(() => [LogicFunctionDTO])
logicFunctions(
@Parent() application: Pick<ApplicationDTO, 'id'>,
- @AuthWorkspace() workspace: WorkspaceEntity,
+ @AuthWorkspace()
+ { id: workspaceId, workspaceCustomApplicationId }: WorkspaceEntity,
@Context() context: { loaders: IDataloaders },
@AuthApplication({ allowUndefined: true })
callingApplication: FlatApplication | undefined,
@@ -240,13 +253,15 @@ export class ApplicationResolver {
!canCallerReachApplication({
callingApplication,
applicationId: application.id,
+ operation: 'read',
+ workspaceCustomApplicationId,
})
) {
return [];
}
return context.loaders.logicFunctionsByApplicationIdLoader.load({
- workspaceId: workspace.id,
+ workspaceId,
applicationId: application.id,
});
}
@@ -254,7 +269,8 @@ export class ApplicationResolver {
@ResolveField(() => [ObjectMetadataDTO])
objects(
@Parent() application: Pick<ApplicationDTO, 'id'>,
- @AuthWorkspace() workspace: WorkspaceEntity,
+ @AuthWorkspace()
+ { id: workspaceId, workspaceCustomApplicationId }: WorkspaceEntity,
@Context() context: { loaders: IDataloaders },
@AuthApplication({ allowUndefined: true })
callingApplication: FlatApplication | undefined,
@@ -263,13 +279,15 @@ export class ApplicationResolver {
!canCallerReachApplication({
callingApplication,
applicationId: application.id,
+ operation: 'read',
+ workspaceCustomApplicationId,
})
) {
return [];
}
return context.loaders.objectMetadataByApplicationIdLoader.load({
- workspaceId: workspace.id,
+ workspaceId,
applicationId: application.id,
});
}
@@ -286,6 +304,7 @@ export class ApplicationResolver {
!canCallerReachApplication({
callingApplication,
applicationId: application.id,
+ operation: 'manage',
})
) {
throw new ForbiddenError(
diff --git a/packages/twenty-server/src/engine/core-modules/application/types/application-caller-operation.type.ts b/packages/twenty-server/src/engine/core-modules/application/types/application-caller-operation.type.ts
new file mode 100644
index 00000000000..8885a40b416
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/types/application-caller-operation.type.ts
@@ -0,0 +1,15 @@
+import { type ApplicationOperation } from 'src/engine/core-modules/application/types/application-operation.type';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+
+export type ApplicationCallerOperation = {
+ callingApplication:
+ | Pick<FlatApplication, 'id' | 'universalIdentifier' | 'sourceType'>
+ | null
+ | undefined;
+} & (
+ | { operation: 'manage'; workspaceCustomApplicationId?: never }
+ | {
+ operation: Exclude<ApplicationOperation, 'manage'>;
+ workspaceCustomApplicationId: string | undefined;
+ }
+);
diff --git a/packages/twenty-server/src/engine/core-modules/application/types/application-operation.type.ts b/packages/twenty-server/src/engine/core-modules/application/types/application-operation.type.ts
new file mode 100644
index 00000000000..c170e08630e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/types/application-operation.type.ts
@@ -0,0 +1,2 @@
+// manage also covers reading an application's configuration, which stays with its owner
+export type ApplicationOperation = 'read' | 'trigger' | 'manage';
diff --git a/packages/twenty-server/src/engine/core-modules/application/types/reachable-applications.type.ts b/packages/twenty-server/src/engine/core-modules/application/types/reachable-applications.type.ts
new file mode 100644
index 00000000000..f09462393c0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/types/reachable-applications.type.ts
@@ -0,0 +1,3 @@
+export type ReachableApplications =
+ | { type: 'all' }
+ | { type: 'own'; applicationId: string };
diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/can-caller-reach-application.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/can-caller-reach-application.util.spec.ts
index b00014b13f7..cd7e9cb7b94 100644
--- a/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/can-caller-reach-application.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/can-caller-reach-application.util.spec.ts
@@ -1,3 +1,5 @@
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+
import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
import { canCallerReachApplication } from 'src/engine/core-modules/application/utils/can-caller-reach-application.util';
@@ -5,41 +7,154 @@ const CALLING_APPLICATION_ID = 'b1a4c0d2-6e1f-4a6b-9c1d-0f2e3a4b5c6d';
const OTHER_APPLICATION_ID = 'e5f6a7b8-c9d0-4e1f-a2b3-c4d5e6f7a8b9';
+const WORKSPACE_CUSTOM_APPLICATION_ID = 'c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f';
+
+const STANDARD_APPLICATION_ID = 'd4e5f6a7-b8c9-4d0e-9f1a-2b3c4d5e6f7a';
+
describe('canCallerReachApplication', () => {
describe.each([
ApplicationRegistrationSourceType.LOCAL,
ApplicationRegistrationSourceType.NPM,
ApplicationRegistrationSourceType.TARBALL,
- ])('with a %s application caller', (sourceType) => {
- const callingApplication = { id: CALLING_APPLICATION_ID, sourceType };
+ ])('with an installed %s application caller', (sourceType) => {
+ const callingApplication = {
+ id: CALLING_APPLICATION_ID,
+ universalIdentifier: CALLING_APPLICATION_ID,
+ sourceType,
+ };
- it('should reach its own application', () => {
+ it.each(['read', 'trigger'] as const)(
+ 'should %s its own application only',
+ (operation) => {
+ expect(
+ canCallerReachApplication({
+ callingApplication,
+ applicationId: CALLING_APPLICATION_ID,
+ operation,
+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ }),
+ ).toBe(true);
+ expect(
+ canCallerReachApplication({
+ callingApplication,
+ applicationId: OTHER_APPLICATION_ID,
+ operation,
+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ }),
+ ).toBe(false);
+ },
+ );
+
+ it('should manage its own application only', () => {
expect(
canCallerReachApplication({
callingApplication,
applicationId: CALLING_APPLICATION_ID,
+ operation: 'manage',
}),
).toBe(true);
+ expect(
+ canCallerReachApplication({
+ callingApplication,
+ applicationId: OTHER_APPLICATION_ID,
+ operation: 'manage',
+ }),
+ ).toBe(false);
});
+ });
+
+ describe('with the workspace custom application as caller', () => {
+ const callingApplication = {
+ id: WORKSPACE_CUSTOM_APPLICATION_ID,
+ universalIdentifier: WORKSPACE_CUSTOM_APPLICATION_ID,
+ sourceType: ApplicationRegistrationSourceType.LOCAL,
+ };
+
+ it.each(['read', 'trigger'] as const)(
+ 'should %s another application',
+ (operation) => {
+ expect(
+ canCallerReachApplication({
+ callingApplication,
+ applicationId: OTHER_APPLICATION_ID,
+ operation,
+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ }),
+ ).toBe(true);
+ },
+ );
- it('should not reach another application', () => {
+ it('should manage its own application only', () => {
+ expect(
+ canCallerReachApplication({
+ callingApplication,
+ applicationId: callingApplication.id,
+ operation: 'manage',
+ }),
+ ).toBe(true);
expect(
canCallerReachApplication({
callingApplication,
applicationId: OTHER_APPLICATION_ID,
+ operation: 'manage',
}),
).toBe(false);
});
});
+ it.each(['read', 'trigger'] as const)(
+ 'should let the standard application %s its own application only',
+ (operation) => {
+ const callingApplication = {
+ id: STANDARD_APPLICATION_ID,
+ universalIdentifier: TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ sourceType: ApplicationRegistrationSourceType.LOCAL,
+ };
+
+ expect(
+ canCallerReachApplication({
+ callingApplication,
+ applicationId: STANDARD_APPLICATION_ID,
+ operation,
+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ }),
+ ).toBe(true);
+ expect(
+ canCallerReachApplication({
+ callingApplication,
+ applicationId: OTHER_APPLICATION_ID,
+ operation,
+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ }),
+ ).toBe(false);
+ },
+ );
+
+ it("should confine the workspace custom application when the workspace's custom application is unknown", () => {
+ expect(
+ canCallerReachApplication({
+ callingApplication: {
+ id: WORKSPACE_CUSTOM_APPLICATION_ID,
+ universalIdentifier: WORKSPACE_CUSTOM_APPLICATION_ID,
+ sourceType: ApplicationRegistrationSourceType.LOCAL,
+ },
+ applicationId: OTHER_APPLICATION_ID,
+ operation: 'read',
+ workspaceCustomApplicationId: undefined,
+ }),
+ ).toBe(false);
+ });
+
it('should let an OAuth-only application caller reach another application', () => {
expect(
canCallerReachApplication({
callingApplication: {
id: CALLING_APPLICATION_ID,
+ universalIdentifier: CALLING_APPLICATION_ID,
sourceType: ApplicationRegistrationSourceType.OAUTH_ONLY,
},
applicationId: OTHER_APPLICATION_ID,
+ operation: 'manage',
}),
).toBe(true);
});
@@ -49,6 +164,7 @@ describe('canCallerReachApplication', () => {
canCallerReachApplication({
callingApplication: undefined,
applicationId: OTHER_APPLICATION_ID,
+ operation: 'manage',
}),
).toBe(true);
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/get-reachable-applications.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/get-reachable-applications.util.spec.ts
new file mode 100644
index 00000000000..5becb7dd204
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/get-reachable-applications.util.spec.ts
@@ -0,0 +1,67 @@
+import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
+import { getReachableApplications } from 'src/engine/core-modules/application/utils/get-reachable-applications.util';
+
+const WORKSPACE_CUSTOM_APPLICATION_ID = 'c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f';
+
+const INSTALLED_APPLICATION_ID = 'b1a4c0d2-6e1f-4a6b-9c1d-0f2e3a4b5c6d';
+
+const workspaceCustomApplication = {
+ id: WORKSPACE_CUSTOM_APPLICATION_ID,
+ universalIdentifier: WORKSPACE_CUSTOM_APPLICATION_ID,
+ sourceType: ApplicationRegistrationSourceType.LOCAL,
+};
+
+const installedApplication = {
+ id: INSTALLED_APPLICATION_ID,
+ universalIdentifier: INSTALLED_APPLICATION_ID,
+ sourceType: ApplicationRegistrationSourceType.NPM,
+};
+
+describe('getReachableApplications', () => {
+ it('should reach every application without a calling application', () => {
+ expect(
+ getReachableApplications({
+ callingApplication: undefined,
+ operation: 'manage',
+ }),
+ ).toEqual({ type: 'all' });
+ });
+
+ it.each(['read', 'trigger'] as const)(
+ 'should let the workspace custom application %s every application',
+ (operation) => {
+ expect(
+ getReachableApplications({
+ callingApplication: workspaceCustomApplication,
+ operation,
+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ }),
+ ).toEqual({ type: 'all' });
+ },
+ );
+
+ it('should let the workspace custom application manage its own application only', () => {
+ expect(
+ getReachableApplications({
+ callingApplication: workspaceCustomApplication,
+ operation: 'manage',
+ }),
+ ).toEqual({
+ type: 'own',
+ applicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ });
+ });
+
+ it('should keep an installed application to its own application', () => {
+ expect(
+ getReachableApplications({
+ callingApplication: installedApplication,
+ operation: 'read',
+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ }),
+ ).toEqual({
+ type: 'own',
+ applicationId: INSTALLED_APPLICATION_ID,
+ });
+ });
+});
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.ts
new file mode 100644
index 00000000000..e337818e51c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/is-twenty-standard-application.util.spec.ts
@@ -0,0 +1,21 @@
+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/__tests__/is-workspace-custom-application.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/is-workspace-custom-application.util.spec.ts
new file mode 100644
index 00000000000..afe2542d566
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/is-workspace-custom-application.util.spec.ts
@@ -0,0 +1,32 @@
+import { isWorkspaceCustomApplication } from 'src/engine/core-modules/application/utils/is-workspace-custom-application.util';
+
+const WORKSPACE_CUSTOM_APPLICATION_ID = 'c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f';
+
+describe('isWorkspaceCustomApplication', () => {
+ it('should recognize the workspace custom application', () => {
+ expect(
+ isWorkspaceCustomApplication({
+ application: { id: WORKSPACE_CUSTOM_APPLICATION_ID },
+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ }),
+ ).toBe(true);
+ });
+
+ it('should not recognize another application', () => {
+ expect(
+ isWorkspaceCustomApplication({
+ application: { id: 'b1a4c0d2-6e1f-4a6b-9c1d-0f2e3a4b5c6d' },
+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ }),
+ ).toBe(false);
+ });
+
+ it("should not recognize the custom application when the workspace's one is unknown", () => {
+ expect(
+ isWorkspaceCustomApplication({
+ application: { id: WORKSPACE_CUSTOM_APPLICATION_ID },
+ workspaceCustomApplicationId: undefined,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/can-caller-reach-application.util.ts b/packages/twenty-server/src/engine/core-modules/application/utils/can-caller-reach-application.util.ts
index c8b872af177..13989127c0d 100644
--- a/packages/twenty-server/src/engine/core-modules/application/utils/can-caller-reach-application.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/can-caller-reach-application.util.ts
@@ -1,25 +1,16 @@
-import { isDefined } from 'twenty-shared/utils';
+import { type ApplicationCallerOperation } from 'src/engine/core-modules/application/types/application-caller-operation.type';
+import { getReachableApplications } from 'src/engine/core-modules/application/utils/get-reachable-applications.util';
-import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
-import { getScopedCallingApplication } from 'src/engine/core-modules/application/utils/get-scoped-calling-application.util';
-
-// Sessions and API keys keep workspace-wide reach behind their permission
-// flags; an application token only reaches its own application.
export const canCallerReachApplication = ({
- callingApplication,
applicationId,
-}: {
- callingApplication:
- | Pick<FlatApplication, 'id' | 'sourceType'>
- | null
- | undefined;
+ ...callerOperation
+}: ApplicationCallerOperation & {
applicationId: string | null | undefined;
}): boolean => {
- const scopedCallingApplication =
- getScopedCallingApplication(callingApplication);
+ const reachableApplications = getReachableApplications(callerOperation);
return (
- !isDefined(scopedCallingApplication) ||
- applicationId === scopedCallingApplication.id
+ reachableApplications.type === 'all' ||
+ reachableApplications.applicationId === applicationId
);
};
diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/get-reachable-applications.util.ts b/packages/twenty-server/src/engine/core-modules/application/utils/get-reachable-applications.util.ts
new file mode 100644
index 00000000000..559399aadc3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/get-reachable-applications.util.ts
@@ -0,0 +1,42 @@
+import { assertUnreachable, isDefined } from 'twenty-shared/utils';
+
+import { type ApplicationCallerOperation } from 'src/engine/core-modules/application/types/application-caller-operation.type';
+import { type ReachableApplications } from 'src/engine/core-modules/application/types/reachable-applications.type';
+import { getScopedCallingApplication } from 'src/engine/core-modules/application/utils/get-scoped-calling-application.util';
+import { isWorkspaceCustomApplication } from 'src/engine/core-modules/application/utils/is-workspace-custom-application.util';
+
+// Sessions and API keys reach every application, behind their permission
+// flags, and so does the workspace custom application when it reads or
+// triggers. Any other caller reaches its own application only.
+export const getReachableApplications = ({
+ callingApplication,
+ operation,
+ workspaceCustomApplicationId,
+}: ApplicationCallerOperation): ReachableApplications => {
+ const scopedCallingApplication =
+ getScopedCallingApplication(callingApplication);
+
+ if (!isDefined(scopedCallingApplication)) {
+ return { type: 'all' };
+ }
+
+ const ownApplication: ReachableApplications = {
+ type: 'own',
+ applicationId: scopedCallingApplication.id,
+ };
+
+ switch (operation) {
+ case 'read':
+ case 'trigger':
+ return isWorkspaceCustomApplication({
+ application: scopedCallingApplication,
+ workspaceCustomApplicationId,
+ })
+ ? { type: 'all' }
+ : ownApplication;
+ case 'manage':
+ return ownApplication;
+ default:
+ return assertUnreachable(operation);
+ }
+};
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.ts
new file mode 100644
index 00000000000..b23881d7382
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/is-twenty-standard-application.util.ts
@@ -0,0 +1,9 @@
+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/application/utils/is-workspace-custom-application.util.ts b/packages/twenty-server/src/engine/core-modules/application/utils/is-workspace-custom-application.util.ts
new file mode 100644
index 00000000000..3d9cb8df2e6
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/is-workspace-custom-application.util.ts
@@ -0,0 +1,9 @@
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+
+export const isWorkspaceCustomApplication = ({
+ application,
+ workspaceCustomApplicationId,
+}: {
+ application: Pick<FlatApplication, 'id'>;
+ workspaceCustomApplicationId: string | undefined;
+}): boolean => application.id === workspaceCustomApplicationId;
diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/event-logs-live.resolver.ts b/packages/twenty-server/src/engine/core-modules/event-logs/event-logs-live.resolver.ts
index d05359adccf..4dbdb275d00 100644
--- a/packages/twenty-server/src/engine/core-modules/event-logs/event-logs-live.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/event-logs/event-logs-live.resolver.ts
@@ -148,6 +148,9 @@ export class EventLogsLiveResolver {
applicationId: isString(row.applicationId)
? row.applicationId
: undefined,
+ operation: 'read',
+ workspaceCustomApplicationId:
+ workspace.workspaceCustomApplicationId,
}),
);
diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.resolver.ts b/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.resolver.ts
index a5ff5384894..7010b5a4b97 100644
--- a/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.resolver.ts
@@ -12,7 +12,7 @@ import { ForbiddenExceptionGraphqlFilter } from 'src/engine/core-modules/event-l
import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';
import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
-import { getScopedCallingApplication } from 'src/engine/core-modules/application/utils/get-scoped-calling-application.util';
+import { getReachableApplications } from 'src/engine/core-modules/application/utils/get-reachable-applications.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
@@ -59,7 +59,11 @@ export class EventLogsResolver {
callingApplication: FlatApplication | undefined,
): Promise<EventLogQueryResult> {
return this.eventLogsService.queryEventLogs(workspace, input, {
- callingApplicationId: getScopedCallingApplication(callingApplication)?.id,
+ reachableApplications: getReachableApplications({
+ callingApplication,
+ operation: 'read',
+ workspaceCustomApplicationId: workspace.workspaceCustomApplicationId,
+ }),
});
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.service.ts b/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.service.ts
index 44a69e9d1ff..406a0108f2e 100644
--- a/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.service.ts
@@ -9,6 +9,7 @@ import { Repository } from 'typeorm';
import { ClickHouseService } from 'src/database/clickhouse/clickhouse.service';
import { formatDateTimeForClickHouse } from 'src/database/clickhouse/utils/format-date-time-for-clickhouse.util';
+import { type ReachableApplications } from 'src/engine/core-modules/application/types/reachable-applications.type';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
import { EventLogRetentionService } from 'src/engine/core-modules/event-logs/retention/services/event-log-retention.service';
@@ -47,7 +48,7 @@ export class EventLogsService {
async queryEventLogs(
workspace: Pick<WorkspaceEntity, 'id' | 'eventLogRetentionDays'>,
input: EventLogQueryInput,
- { callingApplicationId }: { callingApplicationId?: string } = {},
+ { reachableApplications }: { reachableApplications: ReachableApplications },
): Promise<EventLogQueryResult> {
const workspaceId = workspace.id;
@@ -74,10 +75,10 @@ export class EventLogsService {
if (
input.table === EventLogTable.APPLICATION_LOG &&
- isDefined(callingApplicationId)
+ reachableApplications.type === 'own'
) {
- whereClauses.push('"applicationId" = {callingApplicationId:String}');
- params.callingApplicationId = callingApplicationId;
+ whereClauses.push('"applicationId" = {reachableApplicationId:String}');
+ params.reachableApplicationId = reachableApplications.applicationId;
}
await this.applyFilters(
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/logic-function-tool.provider.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/logic-function-tool.provider.spec.ts
index 0ad192f0a19..1e0314a7e7b 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/logic-function-tool.provider.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/logic-function-tool.provider.spec.ts
@@ -1,5 +1,6 @@
import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
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 { LogicFunctionToolProvider } from 'src/engine/core-modules/tool-provider/providers/logic-function-tool.provider';
import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';
import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
@@ -29,6 +30,7 @@ const createFlatLogicFunction = (
const generateDescriptors = async (
logicFunctions: FlatLogicFunction[],
application?: FlatApplication,
+ authContext?: WorkspaceAuthContext,
) => {
const flatLogicFunctionMaps =
createEmptyFlatEntityMaps() as FlatEntityMaps<FlatLogicFunction>;
@@ -67,6 +69,7 @@ const generateDescriptors = async (
{
workspaceId,
rolePermissionConfig: { intersectionOf: { userWorkspaceRoleId: roleId } },
+ authContext,
application,
},
{ includeSchemas: false },
@@ -170,4 +173,34 @@ describe('LogicFunctionToolProvider', () => {
'app_second_tool',
]);
});
+
+ it('should expose every application tool to the workspace custom application', async () => {
+ const descriptors = await generateDescriptors(
+ [
+ createFlatLogicFunction({
+ name: 'own-tool',
+ applicationId: 'workspace-custom-application-id',
+ }),
+ createFlatLogicFunction({
+ name: 'installed-tool',
+ applicationId: 'installed-application-id',
+ }),
+ ],
+ {
+ id: 'workspace-custom-application-id',
+ universalIdentifier: 'workspace-custom-application-id',
+ sourceType: ApplicationRegistrationSourceType.LOCAL,
+ } as FlatApplication,
+ {
+ workspace: {
+ workspaceCustomApplicationId: 'workspace-custom-application-id',
+ },
+ } as WorkspaceAuthContext,
+ );
+
+ expect(descriptors.map(({ name }) => name)).toEqual([
+ 'app_own_tool',
+ 'app_installed_tool',
+ ]);
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts
index 55057ac4f99..fb397ab63aa 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts
@@ -87,6 +87,9 @@ export class LogicFunctionToolProvider implements ToolProvider {
canCallerReachApplication({
callingApplication: context.application,
applicationId: fn.applicationId,
+ operation: 'trigger',
+ workspaceCustomApplicationId:
+ context.authContext?.workspace.workspaceCustomApplicationId,
}),
);
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/workflow-tool.provider.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/workflow-tool.provider.ts
index 87fa94b4346..46726d03cb2 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/workflow-tool.provider.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/workflow-tool.provider.ts
@@ -2,9 +2,8 @@ import { Inject, Injectable, Optional } from '@nestjs/common';
import { type ToolSet } from 'ai';
import { PermissionFlagType } from 'twenty-shared/constants';
-import { isDefined } from 'twenty-shared/utils';
-import { getScopedCallingApplication } from 'src/engine/core-modules/application/utils/get-scoped-calling-application.util';
+import { getReachableApplications } from 'src/engine/core-modules/application/utils/get-reachable-applications.util';
import { type GenerateDescriptorOptions } from 'src/engine/core-modules/tool-provider/interfaces/generate-descriptor-options.type';
import { type ToolProvider } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider.interface';
import { type ToolProviderContext } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type';
@@ -35,10 +34,15 @@ export class WorkflowToolProvider implements ToolProvider {
) {}
async isAvailable(context: ToolProviderContext): Promise<boolean> {
- if (
- !this.workflowToolService ||
- isDefined(getScopedCallingApplication(context.application))
- ) {
+ // Workspace workflows can call any application, so only callers reaching them all get these tools
+ const reachableApplications = getReachableApplications({
+ callingApplication: context.application,
+ operation: 'trigger',
+ workspaceCustomApplicationId:
+ context.authContext?.workspace.workspaceCustomApplicationId,
+ });
+
+ if (!this.workflowToolService || reachableApplications.type !== 'all') {
return false;
}
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/resolvers/tool-index.resolver.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/resolvers/tool-index.resolver.ts
index 9d9613b8fd1..5a4ee7c3654 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/resolvers/tool-index.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/resolvers/tool-index.resolver.ts
@@ -6,6 +6,7 @@ import { type APP_LOCALES } from 'twenty-shared/translations';
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { getWorkspaceAuthContext } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -91,6 +92,7 @@ export class ToolIndexResolver {
userId: user?.id,
userWorkspaceId,
locale,
+ authContext: getWorkspaceAuthContext(),
application,
});
}
@@ -119,6 +121,7 @@ export class ToolIndexResolver {
rolePermissionConfig,
userId: user?.id,
userWorkspaceId,
+ authContext: getWorkspaceAuthContext(),
application,
},
});
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
index 14814551e93..8977351398c 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
@@ -7,6 +7,7 @@ import { type APP_LOCALES } from 'twenty-shared/translations';
import { isDefined } from 'twenty-shared/utils';
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 ToolProviderContext } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type';
import { type GenerateDescriptorOptions } from 'src/engine/core-modules/tool-provider/interfaces/generate-descriptor-options.type';
import { type ToolProvider } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider.interface';
@@ -201,6 +202,7 @@ export class ToolRegistryService {
rolePermissionConfig: RolePermissionConfig;
categories?: ToolCategory[];
excludeTools?: Set<string>;
+ authContext?: WorkspaceAuthContext;
application?: FlatApplication;
},
): Promise<ToolIndexEntry[]> {
@@ -210,6 +212,7 @@ export class ToolRegistryService {
userId: options.userId,
userWorkspaceId: options.userWorkspaceId,
locale: options.locale,
+ authContext: options.authContext,
application: options.application,
});
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/tools/get-tool-catalog.tool.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/tools/get-tool-catalog.tool.ts
index 6ab6cb721be..e5af1302da6 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/tools/get-tool-catalog.tool.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/tools/get-tool-catalog.tool.ts
@@ -3,6 +3,7 @@ import { z } from 'zod';
import { ToolCategory } from 'twenty-shared/ai';
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 ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';
import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config.type';
@@ -37,6 +38,7 @@ export const createGetToolCatalogTool = (
userId?: string;
userWorkspaceId?: string;
excludeTools?: Set<string>;
+ authContext?: WorkspaceAuthContext;
application?: FlatApplication;
},
) => ({
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-run.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-run.resolver.ts
index 94adbd3788b..317d14b41bb 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-run.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow-run.resolver.ts
@@ -65,7 +65,8 @@ export class CoreWorkflowRunResolver {
@Mutation(() => RunWorkflowVersionDTO)
async runCoreWorkflowVersion(
@AuthUser() user: AuthContextUser,
- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
+ @AuthWorkspace()
+ { id: workspaceId, workspaceCustomApplicationId }: WorkspaceEntity,
@AuthUserWorkspaceId({ allowUndefined: true })
userWorkspaceId: string | undefined,
@AuthApplication({ allowUndefined: true })
@@ -101,7 +102,8 @@ export class CoreWorkflowRunResolver {
await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreStartableByApplicationOrThrow(
{
workspaceId,
- callerApplicationId: callerApplication?.id,
+ workspaceCustomApplicationId,
+ callerApplication,
coreWorkflowVersionIds: [coreWorkflowVersionId],
},
);
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts
index 00864f3a0ac..c7194dbd442 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts
@@ -4,11 +4,12 @@ import { Injectable } from '@nestjs/common';
import { msg } from '@lingui/core/macro';
import { WorkflowVisibility } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-import { In } from 'typeorm';
+import { In, Not } from 'typeorm';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { getReachableApplications } from 'src/engine/core-modules/application/utils/get-reachable-applications.util';
import { WorkflowVersionEntity } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
-import { canApplicationStartCoreWorkflow } from 'src/engine/core-modules/workflow/utils/can-application-start-core-workflow.util';
import { canChangeCoreWorkflowVisibility } from 'src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
@@ -66,15 +67,23 @@ export class CoreWorkflowAccessService {
async assertCoreWorkflowVersionsAreStartableByApplicationOrThrow({
workspaceId,
- callerApplicationId,
+ workspaceCustomApplicationId,
+ callerApplication,
coreWorkflowVersionIds,
}: {
workspaceId: string;
- callerApplicationId: string | undefined;
+ workspaceCustomApplicationId: string;
+ callerApplication: FlatApplication | undefined;
coreWorkflowVersionIds: string[];
}): Promise<void> {
+ const reachableApplications = getReachableApplications({
+ callingApplication: callerApplication,
+ operation: 'trigger',
+ workspaceCustomApplicationId,
+ });
+
if (
- !isDefined(callerApplicationId) ||
+ reachableApplications.type === 'all' ||
coreWorkflowVersionIds.length === 0
) {
return;
@@ -100,21 +109,17 @@ export class CoreWorkflowAccessService {
return;
}
- const workflows = await this.coreWorkflowRepository.find(workspaceId, {
- where: { id: In(coreWorkflowIds) },
- select: { id: true, applicationId: true },
- });
-
- const isStartable = workflows.every((workflow) =>
- canApplicationStartCoreWorkflow({
- callerApplicationId,
- workflowApplicationId: workflow.applicationId,
- }),
- );
+ const hasWorkflowOfAnotherApplication =
+ await this.coreWorkflowRepository.exists(workspaceId, {
+ where: {
+ id: In(coreWorkflowIds),
+ applicationId: Not(reachableApplications.applicationId),
+ },
+ });
- if (!isStartable) {
+ if (hasWorkflowOfAnotherApplication) {
throw new WorkflowQueryValidationException(
- `Application '${callerApplicationId}' cannot start a workflow owned by another application`,
+ `Application '${reachableApplications.applicationId}' cannot start a workflow owned by another application`,
WorkflowQueryValidationExceptionCode.FORBIDDEN,
{
userFriendlyMessage: msg`An application can only start its own workflows.`,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/can-application-start-core-workflow.util.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/can-application-start-core-workflow.util.spec.ts
deleted file mode 100644
index f69649a4622..00000000000
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/can-application-start-core-workflow.util.spec.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { canApplicationStartCoreWorkflow } from 'src/engine/core-modules/workflow/utils/can-application-start-core-workflow.util';
-
-describe('canApplicationStartCoreWorkflow', () => {
- it('lets a request without an application start any workflow it can reach', () => {
- expect(
- canApplicationStartCoreWorkflow({
- callerApplicationId: undefined,
- workflowApplicationId: 'installed-app-id',
- }),
- ).toBe(true);
- });
-
- it('lets an application start its own workflows', () => {
- expect(
- canApplicationStartCoreWorkflow({
- callerApplicationId: 'installed-app-id',
- workflowApplicationId: 'installed-app-id',
- }),
- ).toBe(true);
- });
-
- it('refuses an application starting a workspace workflow', () => {
- expect(
- canApplicationStartCoreWorkflow({
- callerApplicationId: 'installed-app-id',
- workflowApplicationId: 'custom-app-id',
- }),
- ).toBe(false);
- });
-
- it('refuses an application starting the workflow of another application', () => {
- expect(
- canApplicationStartCoreWorkflow({
- callerApplicationId: 'other-app-id',
- workflowApplicationId: 'installed-app-id',
- }),
- ).toBe(false);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-application-start-core-workflow.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-application-start-core-workflow.util.ts
deleted file mode 100644
index 18da97a2727..00000000000
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-application-start-core-workflow.util.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { isDefined } from 'twenty-shared/utils';
-
-export const canApplicationStartCoreWorkflow = ({
- callerApplicationId,
- workflowApplicationId,
-}: {
- callerApplicationId: string | undefined;
- workflowApplicationId: string;
-}): boolean =>
- !isDefined(callerApplicationId) ||
- workflowApplicationId === callerApplicationId;
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.ts
index 7a91ea49de7..a4aeae1b96d 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
@@ -28,6 +28,7 @@ import { type FlatApiKey } from 'src/engine/core-modules/api-key/types/flat-api-
import { fromApiKeyEntityToFlat } from 'src/engine/core-modules/api-key/utils/from-api-key-entity-to-flat.util';
import { ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.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 { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
import { workspaceAuthContextStorage } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
import {
@@ -196,8 +197,12 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
}
if (
- isDefined(callerApplication) &&
- agent.applicationId !== callerApplication.id
+ !canCallerReachApplication({
+ callingApplication: callerApplication,
+ applicationId: agent.applicationId,
+ operation: 'trigger',
+ workspaceCustomApplicationId: workspace.workspaceCustomApplicationId,
+ })
) {
throw new AiException(
`Agent ${input.agentUniversalIdentifier} belongs to another application`,
@@ -225,9 +230,10 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
application,
});
+ // keyed by the caller, so an application never continues another one's conversation with a shared agent
const threadId = isDefined(thread)
? buildAgentRunThreadId({
- applicationId: application.id,
+ applicationId: callerApplication?.id ?? application.id,
agentId: agent.id,
threadKey: thread.key,
})
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts
index e717da84e92..ddcc6585b2e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts
@@ -184,6 +184,7 @@ export class AgentToolsetService {
locale,
excludeTools: new Set(excludedToolNames),
rolePermissionConfig: toolContext.rolePermissionConfig,
+ authContext: toolContext.authContext,
application: toolContext.application,
},
);
@@ -221,6 +222,7 @@ export class AgentToolsetService {
userId,
userWorkspaceId,
rolePermissionConfig: toolContext.rolePermissionConfig,
+ authContext: toolContext.authContext,
application: toolContext.application,
categories: [...registryAccess.categories],
excludeTools: new Set(registryAccess.excludedToolNames),
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.ts
new file mode 100644
index 00000000000..1c0a98cbe16
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/resolve-agent-run-calling-application.util.spec.ts
@@ -0,0 +1,70 @@
+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-execution/utils/resolve-agent-run-calling-application.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-calling-application.util.ts
index 7ad6ae912b6..d8c4a93f729 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/metadata-modules/ai/ai-agent-execution/utils/resolve-agent-run-calling-application.util.ts
@@ -1,7 +1,7 @@
-import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
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';
@@ -20,6 +20,9 @@ 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 => {
@@ -29,13 +32,7 @@ export const resolveAgentRunCallingApplication = (
const application = getAuthContextApplication(authContext);
- if (
- application?.id === authContext.workspace.workspaceCustomApplicationId ||
- application?.universalIdentifier ===
- TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER
- ) {
- return undefined;
- }
-
- return application;
+ return isDefined(application) && isTwentyStandardApplication(application)
+ ? undefined
+ : application;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/agent.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/agent.resolver.ts
index cb2ea65e23b..9a2a23fd1b9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/agent.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/agent.resolver.ts
@@ -67,7 +67,8 @@ export class AgentResolver {
@Query(() => [AgentDTO])
async findManyAgents(
- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
+ @AuthWorkspace()
+ { id: workspaceId, workspaceCustomApplicationId }: WorkspaceEntity,
@AuthApplication({ allowUndefined: true })
callingApplication: FlatApplication | undefined,
): Promise<AgentDTO[]> {
@@ -79,6 +80,8 @@ export class AgentResolver {
canCallerReachApplication({
callingApplication,
applicationId: flatAgent.applicationId,
+ operation: 'read',
+ workspaceCustomApplicationId,
}),
)
.map(fromFlatAgentWithRoleIdToAgentDto);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/list-agents.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/list-agents.tool.ts
index 2d735707bc2..b3512f2584f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/list-agents.tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/list-agents.tool.ts
@@ -28,7 +28,7 @@ export class ListAgentsTool extends BaseTool<typeof listAgentsInputSchema> {
}
async execute({
- context: { workspaceId, application },
+ context: { workspaceId, application, authContext },
}: ToolExecuteArgs<typeof listAgentsInputSchema>): Promise<ToolOutput> {
const agents = await this.agentService.findManyAgents(workspaceId);
@@ -40,6 +40,9 @@ export class ListAgentsTool extends BaseTool<typeof listAgentsInputSchema> {
canCallerReachApplication({
callingApplication: application,
applicationId: agent.applicationId,
+ operation: 'read',
+ workspaceCustomApplicationId:
+ authContext?.workspace.workspaceCustomApplicationId,
}),
)
.map(toAgentSummary);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service.ts
index a254c3f2f0b..cd9066b33ce 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/tools/services/manageable-agent.service.ts
@@ -38,6 +38,7 @@ export class ManageableAgentService {
!canCallerReachApplication({
callingApplication: context.application,
applicationId: agent.applicationId,
+ operation: 'manage',
})
) {
throw new AiException('Agent not found', AiExceptionCode.AGENT_NOT_FOUND);
diff --git a/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts
index 2c078fa9d75..1988c232176 100644
--- a/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts
@@ -134,6 +134,8 @@ export class FrontComponentResolver {
canCallerReachApplication({
callingApplication,
applicationId: frontComponent.applicationId,
+ operation: 'read',
+ workspaceCustomApplicationId: workspace.workspaceCustomApplicationId,
}),
);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts
index 74ad2f6601c..4f1820fb410 100644
--- a/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/logic-function.resolver.ts
@@ -126,7 +126,8 @@ export class LogicFunctionResolver {
@Query(() => [LogicFunctionDTO])
@AllowSuspendedWorkspace()
async findManyLogicFunctions(
- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
+ @AuthWorkspace()
+ { id: workspaceId, workspaceCustomApplicationId }: WorkspaceEntity,
@AuthApplication({ allowUndefined: true })
callingApplication: FlatApplication | undefined,
): Promise<LogicFunctionDTO[]> {
@@ -147,6 +148,8 @@ export class LogicFunctionResolver {
canCallerReachApplication({
callingApplication,
applicationId: flatLogicFunction.applicationId,
+ operation: 'read',
+ workspaceCustomApplicationId,
}),
)
.map((flatLogicFunction) =>
@@ -410,6 +413,8 @@ export class LogicFunctionResolver {
canCallerReachApplication({
callingApplication,
applicationId: payload.logicFunctionLogs.applicationId,
+ operation: 'read',
+ workspaceCustomApplicationId: workspace.workspaceCustomApplicationId,
})
? payload
: undefined,
diff --git a/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts
index 257bdd5a2eb..f66c9c10128 100644
--- a/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts
@@ -117,6 +117,8 @@ export class SkillResolver {
canCallerReachApplication({
callingApplication,
applicationId: skill.applicationId,
+ operation: 'read',
+ workspaceCustomApplicationId: workspace.workspaceCustomApplicationId,
}),
);
}
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.ts
new file mode 100644
index 00000000000..394143370c9
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/services/__tests__/workflow-execution-context.service.spec.ts
@@ -0,0 +1,117 @@
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import { type Repository } from 'typeorm';
+
+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 WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+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_CUSTOM_APPLICATION_ID = 'workspace-custom-app-id';
+
+const authContext = {
+ workspace: { workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID },
+} as WorkspaceAuthContext;
+
+const installedApplication = {
+ id: 'installed-app-id',
+ name: 'Installed app',
+ universalIdentifier: 'installed-app-universal-identifier',
+ sourceType: ApplicationRegistrationSourceType.NPM,
+} as FlatApplication;
+
+const workspaceCustomApplication = {
+ id: WORKSPACE_CUSTOM_APPLICATION_ID,
+ name: 'Workspace',
+ universalIdentifier: WORKSPACE_CUSTOM_APPLICATION_ID,
+ sourceType: ApplicationRegistrationSourceType.LOCAL,
+} as FlatApplication;
+
+const standardApplication = {
+ id: 'twenty-standard-app-id',
+ name: 'Standard',
+ universalIdentifier: TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ sourceType: ApplicationRegistrationSourceType.LOCAL,
+} as FlatApplication;
+
+describe('WorkflowExecutionContextService', () => {
+ const workflowExecutionContextService = new WorkflowExecutionContextService(
+ {} as WorkflowRunWorkspaceService,
+ {} as UserWorkspaceService,
+ {} as ApplicationService,
+ {} as RoleService,
+ {} as WorkspaceCacheService,
+ {} as Repository<WorkspaceEntity>,
+ );
+
+ describe('assertRunApplicationCanTriggerStepTargetOrThrow', () => {
+ const assertTarget = ({
+ application,
+ targetApplicationId,
+ }: {
+ application: FlatApplication | null;
+ 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();
+ });
+
+ it('lets a run use the functions and agents of its application', () => {
+ expect(() =>
+ assertTarget({
+ application: installedApplication,
+ targetApplicationId: 'installed-app-id',
+ }),
+ ).not.toThrow();
+ });
+
+ it('refuses an installed application run crossing into another application', () => {
+ expect(() =>
+ assertTarget({
+ application: installedApplication,
+ targetApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ }),
+ ).toThrow(
+ 'Logic function "greet" belongs to another application than "Installed app"',
+ );
+ });
+
+ it('lets a run of the workspace custom application use the functions and agents of another application', () => {
+ expect(() =>
+ assertTarget({
+ application: workspaceCustomApplication,
+ targetApplicationId: 'installed-app-id',
+ }),
+ ).not.toThrow();
+ });
+
+ it('refuses a run of the standard application using the functions and agents of another application', () => {
+ expect(() =>
+ assertTarget({
+ application: standardApplication,
+ targetApplicationId: 'installed-app-id',
+ }),
+ ).toThrow(
+ 'Logic function "greet" belongs to another application than "Standard"',
+ );
+ });
+ });
+});
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.ts
index 3494b1b7ff6..52db9807e56 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
@@ -7,6 +7,7 @@ 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';
@@ -25,7 +26,6 @@ import {
} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
import { type WorkflowRunInfo } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
import { type WorkflowExecutionContext } from 'src/modules/workflow/workflow-executor/types/workflow-execution-context.type';
-import { assertStepTargetBelongsToRunApplication } from 'src/modules/workflow/workflow-executor/utils/assert-step-target-belongs-to-run-application.util';
import { resolveWorkflowRunApplicationOrThrow } from 'src/modules/workflow/workflow-executor/utils/resolve-workflow-run-application-or-throw.util';
import { WorkflowRunWorkspaceService as WorkflowRunService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
@@ -67,24 +67,35 @@ export class WorkflowExecutionContextService {
return this.buildExecutionContext(workflowRun, workspaceId);
}
- assertStepTargetBelongsToRunApplicationOrThrow({
- application,
+ assertRunApplicationCanTriggerStepTargetOrThrow({
+ executionContext: { application, authContext },
targetApplicationId,
targetLabel,
}: {
- application: FlatApplication | null;
+ executionContext: Pick<
+ WorkflowExecutionContext,
+ 'application' | 'authContext'
+ >;
targetApplicationId: string;
targetLabel: string;
}): void {
- if (!isDefined(application)) {
+ if (
+ !isDefined(application) ||
+ canCallerReachApplication({
+ callingApplication: application,
+ applicationId: targetApplicationId,
+ operation: 'trigger',
+ workspaceCustomApplicationId:
+ authContext.workspace.workspaceCustomApplicationId,
+ })
+ ) {
return;
}
- assertStepTargetBelongsToRunApplication({
- application,
- targetApplicationId,
- targetLabel,
- });
+ throw new WorkflowStepExecutorException(
+ `${targetLabel} belongs to another application than "${application.name}", so this run cannot use it`,
+ WorkflowStepExecutorExceptionCode.FORBIDDEN,
+ );
}
private async buildExecutionContext(
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/assert-step-target-belongs-to-run-application.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/assert-step-target-belongs-to-run-application.util.spec.ts
deleted file mode 100644
index a54ce24e18a..00000000000
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/assert-step-target-belongs-to-run-application.util.spec.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { assertStepTargetBelongsToRunApplication } from 'src/modules/workflow/workflow-executor/utils/assert-step-target-belongs-to-run-application.util';
-
-const RUN_APPLICATION = { id: 'installed-app-id', name: 'Installed app' };
-
-const assertTarget = (targetApplicationId: string) =>
- assertStepTargetBelongsToRunApplication({
- application: RUN_APPLICATION,
- targetApplicationId,
- targetLabel: 'Logic function "greet"',
- });
-
-describe('assertStepTargetBelongsToRunApplication', () => {
- it('lets a run use the functions and agents of its application', () => {
- expect(() => assertTarget('installed-app-id')).not.toThrow();
- });
-
- it('refuses a run using the functions and agents of the workspace', () => {
- expect(() => assertTarget('workspace-custom-app-id')).toThrow(
- 'Logic function "greet" belongs to another application than "Installed app"',
- );
- });
-
- it('refuses a run crossing into another application', () => {
- expect(() => assertTarget('twenty-standard-app-id')).toThrow(
- 'Logic function "greet" belongs to another application than "Installed app"',
- );
- expect(() => assertTarget('other-app-id')).toThrow(
- 'Logic function "greet" belongs to another application than "Installed app"',
- );
- });
-});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/assert-step-target-belongs-to-run-application.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/assert-step-target-belongs-to-run-application.util.ts
deleted file mode 100644
index 80e609c1eb7..00000000000
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/assert-step-target-belongs-to-run-application.util.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
-import {
- WorkflowStepExecutorException,
- WorkflowStepExecutorExceptionCode,
-} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
-
-export const assertStepTargetBelongsToRunApplication = ({
- application,
- targetApplicationId,
- targetLabel,
-}: {
- application: Pick<FlatApplication, 'id' | 'name'>;
- targetApplicationId: string;
- targetLabel: string;
-}): void => {
- if (targetApplicationId === application.id) {
- return;
- }
-
- throw new WorkflowStepExecutorException(
- `${targetLabel} belongs to another application than "${application.name}", so this run cannot use it`,
- WorkflowStepExecutorExceptionCode.FORBIDDEN,
- );
-};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
index add2a80814f..df34842c13f 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,6 +6,7 @@ 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';
@@ -116,11 +117,9 @@ export class AiAgentWorkflowAction implements WorkflowAction {
const executionContext =
await this.workflowExecutionContextService.getExecutionContext(runInfo);
- const { application } = executionContext;
-
- this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow(
+ this.workflowExecutionContextService.assertRunApplicationCanTriggerStepTargetOrThrow(
{
- application,
+ executionContext,
targetApplicationId: agent.applicationId,
targetLabel: `Agent "${agent.name}"`,
},
@@ -166,7 +165,14 @@ export class AiAgentWorkflowAction implements WorkflowAction {
}),
spec: buildWorkflowAgentRunSpec({
step,
- isApplicationBound: isDefined(application),
+ isApplicationBound:
+ isDefined(executionContext.application) &&
+ !isWorkspaceCustomApplication({
+ application: executionContext.application,
+ workspaceCustomApplicationId:
+ executionContext.authContext.workspace
+ .workspaceCustomApplicationId,
+ }),
}),
prompt: isDefined(resolvedPrompt)
? {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts
index 6fa0e128ec6..6a26c2122a3 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/code/code.workflow-action.ts
@@ -68,9 +68,9 @@ export class CodeWorkflowAction implements WorkflowAction {
const { authContext, application } =
await this.workflowExecutionContextService.getExecutionContext(runInfo);
- this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow(
+ this.workflowExecutionContextService.assertRunApplicationCanTriggerStepTargetOrThrow(
{
- application,
+ executionContext: { authContext, application },
targetApplicationId: flatLogicFunction.applicationId,
targetLabel: `Logic function "${flatLogicFunction.name}"`,
},
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts
index d4087f6b221..9d903fbcc2b 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action.ts
@@ -82,9 +82,9 @@ export class LogicFunctionWorkflowAction implements WorkflowAction {
const { authContext, application } =
await this.workflowExecutionContextService.getExecutionContext(runInfo);
- this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow(
+ this.workflowExecutionContextService.assertRunApplicationCanTriggerStepTargetOrThrow(
{
- application,
+ executionContext: { authContext, application },
targetApplicationId: logicFunction.applicationId,
targetLabel: `Logic function "${logicFunction.name}"`,
},
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-workspace-custom-application-reach.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-workspace-custom-application-reach.integration-spec.ts
new file mode 100644
index 00000000000..0c73447fe9b
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-workspace-custom-application-reach.integration-spec.ts
@@ -0,0 +1,210 @@
+import { captureAgentRunExecution } from 'test/integration/graphql/suites/user-session/utils/capture-agent-run-execution.util';
+import { getMcpToolCatalog } from 'test/integration/graphql/suites/application-role-intersection/utils/get-mcp-tool-catalog.util';
+import { runAgentQueryFactory } from 'test/integration/graphql/suites/user-session/utils/run-agent-query-factory.util';
+import { findWorkspaceCustomApplicationId } from 'test/integration/metadata/suites/application-default-role/utils/find-application-default-role.util';
+import { findAgents } from 'test/integration/metadata/suites/agent/utils/find-agents.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithResources,
+ setupApplicationWithResources,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-resources.util';
+import { findFrontComponents } from 'test/integration/metadata/suites/front-component/utils/find-front-components.util';
+import { findManyLogicFunctions } from 'test/integration/metadata/suites/logic-function/utils/find-many-logic-functions.util';
+import { findSkills } from 'test/integration/metadata/suites/skill/utils/find-skills.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+import { ToolCategory } from 'twenty-shared/ai';
+import {
+ type EachTestingContext,
+ eachTestingContextFilter,
+} from 'twenty-shared/testing';
+
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const WORKSPACE_SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+type ListEndpointTestContext = {
+ listApplicationIds: (token: string) => Promise<(string | undefined)[]>;
+};
+
+const listEndpointTestCases: EachTestingContext<ListEndpointTestContext>[] = [
+ {
+ title: 'findManyLogicFunctions',
+ context: {
+ listApplicationIds: async (token) => {
+ const { data } = await findManyLogicFunctions({
+ token,
+ expectToFail: false,
+ });
+
+ return data.findManyLogicFunctions.map(
+ ({ applicationId }) => applicationId,
+ );
+ },
+ },
+ },
+ {
+ title: 'frontComponents',
+ context: {
+ listApplicationIds: async (token) => {
+ const { data } = await findFrontComponents({
+ token,
+ expectToFail: false,
+ });
+
+ return data.frontComponents.map(({ applicationId }) => applicationId);
+ },
+ },
+ },
+ {
+ title: 'findManyAgents',
+ context: {
+ listApplicationIds: async (token) => {
+ const { data } = await findAgents({
+ input: undefined,
+ token,
+ expectToFail: false,
+ });
+
+ return data.findManyAgents.map(({ applicationId }) => applicationId);
+ },
+ },
+ },
+ {
+ title: 'skills',
+ context: {
+ listApplicationIds: async (token) => {
+ const { data } = await findSkills({
+ input: undefined,
+ token,
+ expectToFail: false,
+ });
+
+ return data.skills.map(({ applicationId }) => applicationId);
+ },
+ },
+ },
+];
+
+describe('The workspace custom application reads and triggers every application', () => {
+ let agentApplication: ApplicationWithResources;
+ let otherApplication: ApplicationWithResources;
+ let agentUniversalIdentifier: string;
+ let customApplicationToken: string;
+ let agentApplicationToken: string;
+ let otherApplicationToken: string;
+ const threadIds: string[] = [];
+
+ beforeAll(async () => {
+ [agentApplication, otherApplication] = await Promise.all([
+ setupApplicationWithResources({ name: 'Composer Reach Agent Owner' }),
+ setupApplicationWithResources({ name: 'Composer Reach Other' }),
+ ]);
+
+ const [{ universalIdentifier }] = await globalThis.testDataSource.query(
+ `SELECT "universalIdentifier" FROM core."agent" WHERE id = $1`,
+ [agentApplication.agentId],
+ );
+
+ agentUniversalIdentifier = universalIdentifier;
+
+ const [customTokenPair, agentApplicationTokenPair, otherTokenPair] =
+ await Promise.all([
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: await findWorkspaceCustomApplicationId(),
+ }),
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: agentApplication.id,
+ }),
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: otherApplication.id,
+ }),
+ ]);
+
+ customApplicationToken = customTokenPair.applicationAccessToken.token;
+ agentApplicationToken =
+ agentApplicationTokenPair.applicationAccessToken.token;
+ otherApplicationToken = otherTokenPair.applicationAccessToken.token;
+ }, 120000);
+
+ afterAll(async () => {
+ // the applications' own threads have no member who could destroy them through the API
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."recordShare" WHERE "recordId" = ANY($1)`,
+ [threadIds],
+ );
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."agentChatThread" WHERE id = ANY($1)`,
+ [threadIds],
+ );
+
+ await Promise.all(
+ [agentApplication, otherApplication].map((application) =>
+ cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ }),
+ ),
+ );
+ });
+
+ it.each(eachTestingContextFilter(listEndpointTestCases))(
+ 'should list the items of installed applications from $title',
+ async ({ context }) => {
+ const applicationIds = await context.listApplicationIds(
+ customApplicationToken,
+ );
+
+ expect(applicationIds).toEqual(
+ expect.arrayContaining([agentApplication.id, otherApplication.id]),
+ );
+ },
+ );
+
+ it('should offer the workflow tools and the function tools of installed applications over MCP', async () => {
+ const catalog = await getMcpToolCatalog({ token: customApplicationToken });
+
+ expect(catalog[ToolCategory.WORKFLOW]?.length).toBeGreaterThan(0);
+ expect(
+ catalog[ToolCategory.LOGIC_FUNCTION]?.map(({ name }) => name),
+ ).toEqual(
+ expect.arrayContaining([
+ 'app_composer_reach_agent_owner_handler',
+ 'app_composer_reach_other_handler',
+ ]),
+ );
+ });
+
+ it('should run the agent of an installed application in a conversation of its own', async () => {
+ const thread = { key: 'composer-reach' };
+
+ const composerExecution = await captureAgentRunExecution({
+ agentUniversalIdentifier,
+ token: customApplicationToken,
+ thread,
+ });
+ const ownerExecution = await captureAgentRunExecution({
+ agentUniversalIdentifier,
+ token: agentApplicationToken,
+ thread,
+ });
+
+ threadIds.push(composerExecution.threadId, ownerExecution.threadId);
+
+ expect(composerExecution.threadId).not.toEqual(ownerExecution.threadId);
+ });
+
+ it('should keep an installed application from running the agent of another application', async () => {
+ const response = await makeMetadataApiRequest(
+ runAgentQueryFactory({ agentUniversalIdentifier, prompt: 'Run' }),
+ otherApplicationToken,
+ );
+
+ expect(response.body.errors?.[0]?.message).toBe(
+ `Agent ${agentUniversalIdentifier} belongs to another application`,
+ );
+ });
+});