The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Move AI provider admin operations to their own resolver (#25023)
Félix Malfaitc0a813b6b077
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.tsindex 9880ce3e647..cdcd3c57d33 100644--- a/packages/twenty-front/src/generated-admin/graphql.ts+++ b/packages/twenty-front/src/generated-admin/graphql.ts@@ -379,6 +379,13 @@ export type ConfigVariablesGroupData = {variables: Array<ConfigVariable>;};+export type CustomAiProviderAccessDto = {+ __typename?: 'CustomAiProviderAccessDTO';+ hasAccess: Scalars['Boolean']['output'];+ seatCount: Scalars['Int']['output'];+ seatThreshold: Scalars['Int']['output'];+};+export type DeleteJobsResponse = {__typename?: 'DeleteJobsResponse';deletedCount: Scalars['Int']['output'];@@ -703,6 +710,7 @@ export type Query = {getAdminWorkspaceChatThreads: Array<AdminWorkspaceChatThread>;getAiProviders: Scalars['JSON']['output'];getConfigVariablesGrouped: ConfigVariables;+ getCustomAiProviderAccess: CustomAiProviderAccessDto;getDatabaseConfigVariable: ConfigVariable;getIndicatorHealthStatus: AdminPanelHealthServiceData;getInstanceAndAllWorkspacesUpgradeStatus: InstanceAndAllWorkspacesUpgradeStatus;@@ -1178,6 +1186,11 @@ export type GetAiProvidersQueryVariables = Exact<{ [key: string]: never; }>;export type GetAiProvidersQuery = { __typename?: 'Query', getAiProviders: any };+export type GetCustomAiProviderAccessQueryVariables = Exact<{ [key: string]: never; }>;+++export type GetCustomAiProviderAccessQuery = { __typename?: 'Query', getCustomAiProviderAccess: { __typename?: 'CustomAiProviderAccessDTO', hasAccess: boolean, seatCount: number, seatThreshold: number } };+export type GetModelsDevProvidersQueryVariables = Exact<{ [key: string]: never; }>;@@ -1515,6 +1528,7 @@ export const SetAdminDefaultAiModelDocument = {"kind":"Document","definitions":[export const GetAdminAiModelsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAdminAiModels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAdminAiModels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"defaultSmartModelId"}},{"kind":"Field","name":{"kind":"Name","value":"defaultFastModelId"}},{"kind":"Field","name":{"kind":"Name","value":"models"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"modelId"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"modelFamily"}},{"kind":"Field","name":{"kind":"Name","value":"sdkPackage"}},{"kind":"Field","name":{"kind":"Name","value":"isAvailable"}},{"kind":"Field","name":{"kind":"Name","value":"isAdminEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isDeprecated"}},{"kind":"Field","name":{"kind":"Name","value":"isRecommended"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"maxOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"inputCostPerMillionTokens"}},{"kind":"Field","name":{"kind":"Name","value":"outputCostPerMillionTokens"}},{"kind":"Field","name":{"kind":"Name","value":"providerName"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabel"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"dataResidency"}}]}}]}}]}}]} as unknown as DocumentNode<GetAdminAiModelsQuery, GetAdminAiModelsQueryVariables>;export const GetAdminAiUsageByWorkspaceDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAdminAiUsageByWorkspace"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"periodStart"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"DateTime"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"periodEnd"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"DateTime"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAdminAiUsageByWorkspace"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"periodStart"},"value":{"kind":"Variable","name":{"kind":"Name","value":"periodStart"}}},{"kind":"Argument","name":{"kind":"Name","value":"periodEnd"},"value":{"kind":"Variable","name":{"kind":"Name","value":"periodEnd"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}}]}}]} as unknown as DocumentNode<GetAdminAiUsageByWorkspaceQuery, GetAdminAiUsageByWorkspaceQueryVariables>;export const GetAiProvidersDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAiProviders"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAiProviders"}}]}}]} as unknown as DocumentNode<GetAiProvidersQuery, GetAiProvidersQueryVariables>;+export const GetCustomAiProviderAccessDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCustomAiProviderAccess"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getCustomAiProviderAccess"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasAccess"}},{"kind":"Field","name":{"kind":"Name","value":"seatCount"}},{"kind":"Field","name":{"kind":"Name","value":"seatThreshold"}}]}}]}}]} as unknown as DocumentNode<GetCustomAiProviderAccessQuery, GetCustomAiProviderAccessQueryVariables>;export const GetModelsDevProvidersDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetModelsDevProviders"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getModelsDevProviders"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"modelCount"}},{"kind":"Field","name":{"kind":"Name","value":"npm"}}]}}]}}]} as unknown as DocumentNode<GetModelsDevProvidersQuery, GetModelsDevProvidersQueryVariables>;export const GetModelsDevSuggestionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetModelsDevSuggestions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"providerType"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getModelsDevSuggestions"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"providerType"},"value":{"kind":"Variable","name":{"kind":"Name","value":"providerType"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"modelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"inputCostPerMillionTokens"}},{"kind":"Field","name":{"kind":"Name","value":"outputCostPerMillionTokens"}},{"kind":"Field","name":{"kind":"Name","value":"cachedInputCostPerMillionTokens"}},{"kind":"Field","name":{"kind":"Name","value":"cacheCreationCostPerMillionTokens"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"maxOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"modalities"}},{"kind":"Field","name":{"kind":"Name","value":"supportsReasoning"}}]}}]}}]} as unknown as DocumentNode<GetModelsDevSuggestionsQuery, GetModelsDevSuggestionsQueryVariables>;export const SyncMarketplaceCatalogDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SyncMarketplaceCatalog"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"syncMarketplaceCatalog"}}]}}]} as unknown as DocumentNode<SyncMarketplaceCatalogMutation, SyncMarketplaceCatalogMutationVariables>;diff --git a/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsx b/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsxindex 09658b35d5b..0131a957322 100644--- a/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsx+++ b/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsx@@ -18,6 +18,7 @@ import { useClientConfig } from '@/client-config/hooks/useClientConfig';import { SettingsAiModelsTable } from '@/settings/ai/components/SettingsAiModelsTable';import { useApolloAdminClient } from '@/settings/admin-panel/apollo/hooks/useApolloAdminClient';import { SettingsAdminAiProviderListCard } from '@/settings/admin-panel/ai/components/SettingsAdminAiProviderListCard';+import { useCustomAiProviderAccess } from '@/settings/admin-panel/ai/hooks/useCustomAiProviderAccess';import { AI_PROVIDER_SOURCE } from '@/settings/admin-panel/ai/constants/AiProviderSource';import { SET_ADMIN_AI_MODEL_RECOMMENDED } from '@/settings/admin-panel/ai/graphql/mutations/setAdminAiModelRecommended';import { SET_ADMIN_AI_MODELS_RECOMMENDED } from '@/settings/admin-panel/ai/graphql/mutations/setAdminAiModelsRecommended';@@ -68,6 +69,11 @@ export const SettingsAdminAI = () => {const hasEnterpriseAccess =isBillingEnabled ||currentWorkspace?.hasValidEnterpriseValidityToken === true;+ const {+ hasAccess: hasCustomAiProviderAccess,+ gateDescription: customAiProviderGateDescription,+ tooltipContent: customAiProviderTooltipContent,+ } = useCustomAiProviderAccess();const [usagePeriod, setUsagePeriod] = useState<PeriodPreset>('30d');const periodOptions = getPeriodOptions();const usageDates = getPeriodDates(usagePeriod);@@ -201,13 +207,25 @@ export const SettingsAdminAI = () => {<H2Titletitle={t`Custom Providers`}description={t`Add custom endpoints, private gateways, or additional regions.`}- adornment={<OrganizationAdornment />}+ adornment={+ <OrganizationAdornment+ tooltipContent={customAiProviderTooltipContent}+ />+ }/><SettingsAdminAiProviderListCardproviders={customProviders}- showAddButton+ showAddButton={hasCustomAiProviderAccess}/>++ {!hasCustomAiProviderAccess && (+ <SettingsEnterpriseFeatureGateCard+ title={t`Organization feature`}+ description={customAiProviderGateDescription}+ buttonTitle={t`Activate`}+ />+ )}</Section>{availableModelOptions.length > 0 && (diff --git a/packages/twenty-front/src/modules/settings/admin-panel/ai/graphql/queries/getCustomAiProviderAccess.ts b/packages/twenty-front/src/modules/settings/admin-panel/ai/graphql/queries/getCustomAiProviderAccess.tsnew file mode 100644index 00000000000..684b0bd5ae9--- /dev/null+++ b/packages/twenty-front/src/modules/settings/admin-panel/ai/graphql/queries/getCustomAiProviderAccess.ts@@ -0,0 +1,11 @@+import { gql } from '@apollo/client';++export const GET_CUSTOM_AI_PROVIDER_ACCESS = gql`+ query GetCustomAiProviderAccess {+ getCustomAiProviderAccess {+ hasAccess+ seatCount+ seatThreshold+ }+ }+`;diff --git a/packages/twenty-front/src/modules/settings/admin-panel/ai/hooks/useCustomAiProviderAccess.ts b/packages/twenty-front/src/modules/settings/admin-panel/ai/hooks/useCustomAiProviderAccess.tsnew file mode 100644index 00000000000..660264e72ec--- /dev/null+++ b/packages/twenty-front/src/modules/settings/admin-panel/ai/hooks/useCustomAiProviderAccess.ts@@ -0,0 +1,42 @@+import { useQuery } from '@apollo/client/react';+import { useLingui } from '@lingui/react/macro';+import { isDefined } from 'twenty-shared/utils';++import { useApolloAdminClient } from '@/settings/admin-panel/apollo/hooks/useApolloAdminClient';+import { GET_CUSTOM_AI_PROVIDER_ACCESS } from '@/settings/admin-panel/ai/graphql/queries/getCustomAiProviderAccess';+import { type GetCustomAiProviderAccessResult } from '@/settings/admin-panel/ai/types/GetCustomAiProviderAccessResult';++export const useCustomAiProviderAccess = () => {+ const { t } = useLingui();+ const apolloAdminClient = useApolloAdminClient();++ const { data, loading } = useQuery<GetCustomAiProviderAccessResult>(+ GET_CUSTOM_AI_PROVIDER_ACCESS,+ { client: apolloAdminClient },+ );++ const access = data?.getCustomAiProviderAccess;++ // Only assume access while the query is in flight, so the section never+ // flashes its locked state; once it settles without an answer the creation+ // paths stay closed rather than failing at the mutation.+ const hasAccess = access?.hasAccess ?? loading;++ const tooltipContent = !isDefined(access)+ ? undefined+ : access.hasAccess+ ? t`Custom providers are complimentary for organizations of up to ${access.seatThreshold} seats. Above that, an Organization plan is required.`+ : t`Custom providers are complimentary for organizations of up to ${access.seatThreshold} seats. This instance has ${access.seatCount} seats, so an Organization plan is required.`;++ const gateDescription = isDefined(access)+ ? t`Custom providers are complimentary up to ${access.seatThreshold} seats. This instance has ${access.seatCount}. Upgrade to add more.`+ : t`This instance's plan could not be verified. Reload the page to try again.`;++ // The seat count and threshold stay internal: every caller wants the copy+ // built from them, not the numbers.+ return {+ hasAccess,+ tooltipContent,+ gateDescription,+ };+};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/ai/types/GetCustomAiProviderAccessResult.ts b/packages/twenty-front/src/modules/settings/admin-panel/ai/types/GetCustomAiProviderAccessResult.tsnew file mode 100644index 00000000000..e3eb902f407--- /dev/null+++ b/packages/twenty-front/src/modules/settings/admin-panel/ai/types/GetCustomAiProviderAccessResult.ts@@ -0,0 +1,9 @@+export type CustomAiProviderAccess = {+ hasAccess: boolean;+ seatCount: number;+ seatThreshold: number;+};++export type GetCustomAiProviderAccessResult = {+ getCustomAiProviderAccess: CustomAiProviderAccess;+};diff --git a/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiModel.tsx b/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiModel.tsxindex 7353b4af216..8ad64587df8 100644--- a/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiModel.tsx+++ b/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiModel.tsx@@ -10,6 +10,7 @@ import { SettingsPath } from 'twenty-shared/types';import { getSettingsPath, isDefined } from 'twenty-shared/utils';import { IconPlus } from 'twenty-ui/icon';import { H2Title } from 'twenty-ui/typography';+import { Info } from 'twenty-ui/feedback';import { Section } from 'twenty-ui/layout';import { themeCssVariables } from 'twenty-ui/theme-constants';@@ -25,6 +26,8 @@ import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';import { Select } from '@/ui/input/components/Select';import { TextInput } from '@/ui/input/components/TextInput';import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';+import { useCustomAiProviderAccess } from '@/settings/admin-panel/ai/hooks/useCustomAiProviderAccess';+import { OrganizationAdornment } from '~/pages/settings/enterprise/components/OrganizationAdornment';import { Checkbox, Toggle } from 'twenty-ui/input';const StyledComboInputContainer = styled.div`@@ -97,6 +100,11 @@ export const SettingsAdminNewAiModel = () => {const { enqueueSuccessSnackBar, enqueueErrorSnackBar } = useSnackBar();const [isSubmitting, setIsSubmitting] = useState(false);const [isCustomModelId, setIsCustomModelId] = useState(false);+ const {+ hasAccess: hasCustomAiProviderAccess,+ gateDescription: customAiProviderGateDescription,+ tooltipContent: customAiProviderTooltipContent,+ } = useCustomAiProviderAccess();const { data: providersData } = useQuery<GetAiProvidersResult>(GET_AI_PROVIDERS,@@ -333,12 +341,21 @@ export const SettingsAdminNewAiModel = () => {actionButton={<SaveAndCancelButtonsonCancel={() => navigate(providerDetailPath)}- isSaveDisabled={isSubmitting}+ isSaveDisabled={isSubmitting || !hasCustomAiProviderAccess}onSave={handleSave}/>}><SettingsPageContainer>+ {!hasCustomAiProviderAccess && (+ <Info+ accent="danger"+ text={customAiProviderGateDescription}+ buttonTitle={t`Activate`}+ to={getSettingsPath(SettingsPath.AdminPanelEnterprise)}+ />+ )}+<Section><H2Titletitle={t`Model ID`}@@ -347,6 +364,11 @@ export const SettingsAdminNewAiModel = () => {? t`Select a known model or add a custom one`: t`The model identifier used by the provider API`}+ adornment={+ <OrganizationAdornment+ tooltipContent={customAiProviderTooltipContent}+ />+ }/>{showModelSelect ? (<Controllerdiff --git a/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiProvider.tsx b/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiProvider.tsxindex 41740497931..8703341b9ef 100644--- a/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiProvider.tsx+++ b/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiProvider.tsx@@ -28,6 +28,8 @@ import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';import { Select } from '@/ui/input/components/Select';import { TextInput } from '@/ui/input/components/TextInput';import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';+import { useCustomAiProviderAccess } from '@/settings/admin-panel/ai/hooks/useCustomAiProviderAccess';+import { OrganizationAdornment } from '~/pages/settings/enterprise/components/OrganizationAdornment';type ModelsDevProvider = { id: string; modelCount: number; npm: AiSdkPackage };@@ -52,6 +54,11 @@ export const SettingsAdminNewAiProvider = () => {null,);const [isCustomMode, setIsCustomMode] = useState(false);+ const {+ hasAccess: hasCustomAiProviderAccess,+ gateDescription: customAiProviderGateDescription,+ tooltipContent: customAiProviderTooltipContent,+ } = useCustomAiProviderAccess();const [addAiProvider] = useMutation(ADD_AI_PROVIDER, {client: apolloAdminClient,@@ -243,16 +250,32 @@ export const SettingsAdminNewAiProvider = () => {actionButton={<SaveAndCancelButtonsonCancel={() => navigate(AI_ADMIN_PATH)}- isSaveDisabled={isSubmitting || !hasSelected}+ isSaveDisabled={+ isSubmitting || !hasSelected || !hasCustomAiProviderAccess+ }onSave={handleSave}/>}><SettingsPageContainer>+ {!hasCustomAiProviderAccess && (+ <Info+ accent="danger"+ text={customAiProviderGateDescription}+ buttonTitle={t`Activate`}+ to={getSettingsPath(SettingsPath.AdminPanelEnterprise)}+ />+ )}+<Section><H2Titletitle={t`Provider`}description={t`Select a known provider or create a custom one`}+ adornment={+ <OrganizationAdornment+ tooltipContent={customAiProviderTooltipContent}+ />+ }/><SelectdropdownId="ai-provider-models-dev-select"diff --git a/packages/twenty-front/src/pages/settings/enterprise/components/OrganizationAdornment.tsx b/packages/twenty-front/src/pages/settings/enterprise/components/OrganizationAdornment.tsxindex 8535195fcbd..ebf871ab240 100644--- a/packages/twenty-front/src/pages/settings/enterprise/components/OrganizationAdornment.tsx+++ b/packages/twenty-front/src/pages/settings/enterprise/components/OrganizationAdornment.tsx@@ -1,9 +1,12 @@import { t } from '@lingui/core/macro';import { css, cx } from '@linaria/core';+import { isNonEmptyString } from '@sniptt/guards';+import { useId } from 'react';import { Link } from 'react-router-dom';import { SettingsPath } from 'twenty-shared/types';import { getSettingsPath } from 'twenty-shared/utils';import { IconLock } from 'twenty-ui/icon';+import { AppTooltip, TooltipDelay } from 'twenty-ui/surfaces';import { themeCssVariables } from 'twenty-ui/theme-constants';import { billingState } from '@/client-config/states/billingState';@@ -38,24 +41,47 @@ const OrganizationAdornmentContent = () => (</>);-export const OrganizationAdornment = () => {+type OrganizationAdornmentProps = {+ tooltipContent?: string;+};++export const OrganizationAdornment = ({+ tooltipContent,+}: OrganizationAdornmentProps) => {const billing = useAtomStateValue(billingState);const isBillingEnabled = billing?.isBillingEnabled ?? false;+ // useId returns a colon-wrapped value that is not a valid CSS selector+ const anchorId = `organization-adornment-${useId().replace(/:/g, '')}`;- if (isBillingEnabled) {- return (- <Link- className={cx(pillClassName, pillLinkClassName)}- to={getSettingsPath(SettingsPath.BillingPlans)}- >- <OrganizationAdornmentContent />- </Link>- );+ const adornment = isBillingEnabled ? (+ <Link+ id={anchorId}+ className={cx(pillClassName, pillLinkClassName)}+ to={getSettingsPath(SettingsPath.BillingPlans)}+ >+ <OrganizationAdornmentContent />+ </Link>+ ) : (+ <span id={anchorId} className={pillClassName}>+ <OrganizationAdornmentContent />+ </span>+ );++ if (!isNonEmptyString(tooltipContent)) {+ return adornment;}return (- <span className={pillClassName}>- <OrganizationAdornmentContent />- </span>+ <>+ {adornment}+ <AppTooltip+ anchorSelect={`#${anchorId}`}+ content={tooltipContent}+ delay={TooltipDelay.shortDelay}+ place="top"+ width="260px"+ clickable+ />+ </>);};diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel-ai-provider.resolver.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel-ai-provider.resolver.tsnew file mode 100644index 00000000000..f9a8de91fb5--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel-ai-provider.resolver.ts@@ -0,0 +1,116 @@+/* @license Enterprise */++import { UseFilters, UseGuards, UsePipes } from '@nestjs/common';+import { Args, Mutation, Query } from '@nestjs/graphql';++import GraphQLJSON from 'graphql-type-json';+import { PermissionFlagType } from 'twenty-shared/constants';++import { AdminResolver } from 'src/engine/api/graphql/graphql-config/decorators/admin-resolver.decorator';+import { CustomAiProviderAccessDTO } from 'src/engine/core-modules/admin-panel/dtos/custom-ai-provider-access.dto';+import { AdminPanelAiProviderService } from 'src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service';+import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';+import { EnterpriseExceptionFilter } from 'src/engine/core-modules/enterprise/enterprise-exception.filter';+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 { ConfigVariableGraphqlApiExceptionFilter } from 'src/engine/core-modules/twenty-config/filters/config-variable-graphql-api-exception.filter';+import { AdminPanelGuard } from 'src/engine/guards/admin-panel-guard';+import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';+import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';+import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';+import { ModelsDevModelSuggestionDTO } from 'src/engine/core-modules/admin-panel/dtos/models-dev-model-suggestion.dto';+import { ModelsDevProviderSuggestionDTO } from 'src/engine/core-modules/admin-panel/dtos/models-dev-provider-suggestion.dto';+import { ModelsDevCatalogService } from 'src/engine/metadata-modules/ai/ai-models/services/models-dev-catalog.service';++@UsePipes(ResolverValidationPipe)+@AdminResolver()+@UseFilters(+ AuthGraphqlApiExceptionFilter,+ EnterpriseExceptionFilter,+ PreventNestToAutoLogGraphqlErrorsFilter,+ ConfigVariableGraphqlApiExceptionFilter,+)+@UseGuards(+ WorkspaceAuthGuard,+ UserAuthGuard,+ SettingsPermissionGuard(PermissionFlagType.SECURITY),+)+export class AdminPanelAiProviderResolver {+ constructor(+ private readonly adminPanelAiProviderService: AdminPanelAiProviderService,+ private readonly modelsDevCatalogService: ModelsDevCatalogService,+ ) {}++ @UseGuards(AdminPanelGuard)+ @Query(() => CustomAiProviderAccessDTO)+ async getCustomAiProviderAccess(): Promise<CustomAiProviderAccessDTO> {+ return this.adminPanelAiProviderService.getCustomAiProviderAccess();+ }++ @UseGuards(AdminPanelGuard)+ @Query(() => GraphQLJSON)+ async getAiProviders(): Promise<Record<string, unknown>> {+ return this.adminPanelAiProviderService.getMaskedProviders();+ }++ @UseGuards(AdminPanelGuard)+ @Mutation(() => Boolean)+ async addAiProvider(+ @Args('providerName', { type: () => String }) providerName: string,+ @Args('providerConfig', { type: () => GraphQLJSON })+ providerConfig: unknown,+ ): Promise<boolean> {+ return this.adminPanelAiProviderService.addProvider({+ providerName,+ providerConfig,+ });+ }++ @UseGuards(AdminPanelGuard)+ @Mutation(() => Boolean)+ async removeAiProvider(+ @Args('providerName', { type: () => String })+ providerName: string,+ ): Promise<boolean> {+ return this.adminPanelAiProviderService.removeProvider(providerName);+ }++ @UseGuards(AdminPanelGuard)+ @Query(() => [ModelsDevProviderSuggestionDTO])+ async getModelsDevProviders(): Promise<ModelsDevProviderSuggestionDTO[]> {+ return this.modelsDevCatalogService.getProviderSuggestions();+ }++ @UseGuards(AdminPanelGuard)+ @Query(() => [ModelsDevModelSuggestionDTO])+ async getModelsDevSuggestions(+ @Args('providerType', { type: () => String }) providerType: string,+ ): Promise<ModelsDevModelSuggestionDTO[]> {+ return this.modelsDevCatalogService.getModelSuggestions(providerType);+ }++ @UseGuards(AdminPanelGuard)+ @Mutation(() => Boolean)+ async addModelToProvider(+ @Args('providerName', { type: () => String }) providerName: string,+ @Args('modelConfig', { type: () => GraphQLJSON })+ modelConfig: unknown,+ ): Promise<boolean> {+ return this.adminPanelAiProviderService.addModelToProvider({+ providerName,+ modelConfig,+ });+ }++ @UseGuards(AdminPanelGuard)+ @Mutation(() => Boolean)+ async removeModelFromProvider(+ @Args('providerName', { type: () => String }) providerName: string,+ @Args('modelName', { type: () => String }) modelName: string,+ ): Promise<boolean> {+ return this.adminPanelAiProviderService.removeModelFromProvider({+ providerName,+ modelName,+ });+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.module.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.module.tsindex 826f85ee4cd..71cc72ee320 100644--- a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.module.ts+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.module.ts@@ -3,6 +3,7 @@ import { TerminusModule } from '@nestjs/terminus';import { TypeOrmModule } from '@nestjs/typeorm';import { CoreEntityCacheModule } from 'src/engine/core-entity-cache/core-entity-cache.module';+import { AdminPanelAiProviderResolver } from 'src/engine/core-modules/admin-panel/admin-panel-ai-provider.resolver';import { AdminPanelApplicationRegistrationResolver } from 'src/engine/core-modules/admin-panel/admin-panel-application-registration.resolver';import { AdminPanelHealthService } from 'src/engine/core-modules/admin-panel/admin-panel-health.service';import { AdminPanelQueueService } from 'src/engine/core-modules/admin-panel/admin-panel-queue.service';@@ -13,6 +14,7 @@ import { DatabaseHealthIndicator } from 'src/engine/core-modules/admin-panel/indimport { RedisHealthIndicator } from 'src/engine/core-modules/admin-panel/indicators/redis.health';import { WorkerHealthIndicator } from 'src/engine/core-modules/admin-panel/indicators/worker.health';import { MaintenanceModeService } from 'src/engine/core-modules/admin-panel/maintenance-mode.service';+import { AdminPanelAiProviderService } from 'src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service';import { AdminPanelBillingService } from 'src/engine/core-modules/admin-panel/services/admin-panel-billing.service';import { AdminPanelChatService } from 'src/engine/core-modules/admin-panel/services/admin-panel-chat.service';import { AdminPanelGlobalChatThreadsService } from 'src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service';@@ -28,6 +30,7 @@ import { BillingModule } from 'src/engine/core-modules/billing/billing.module';import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';import { EventLogEmitterModule } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.module';import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';@@ -84,11 +87,14 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspacJwtModule,CoreEntityCacheModule,EventLogEmitterModule,+ EnterpriseModule,TwoFactorAuthenticationModule,],providers: [AdminPanelResolver,+ AdminPanelAiProviderResolver,AdminPanelApplicationRegistrationResolver,+ AdminPanelAiProviderService,AdminPanelUserLookupService,AdminPanelServerAdminService,AdminPanelStatisticsService,diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.tsindex 79859b469cf..bb34e055b31 100644--- a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts@@ -99,18 +99,10 @@ import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';import { MODEL_FAMILY_LABELS } from 'src/engine/metadata-modules/ai/ai-models/constants/model-family-labels.const';import { AiModelPreferencesService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-preferences.service';import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';-import { DefaultAiCatalogService } from 'src/engine/metadata-modules/ai/ai-models/services/default-ai-catalog.service';-import { ModelsDevCatalogService } from 'src/engine/metadata-modules/ai/ai-models/services/models-dev-catalog.service';import { AiModelRole } from 'src/engine/metadata-modules/ai/ai-models/types/ai-model-role.enum';-import { type AiProviderConfig } from 'src/engine/metadata-modules/ai/ai-models/types/ai-provider-config.type';-import { aiProviderModelConfigSchema } from 'src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema';-import { type AiProviderModelConfig } from 'src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.type';-import { extractConfigVariableName } from 'src/engine/metadata-modules/ai/ai-models/utils/extract-config-variable-name.util';import { AdminPanelHealthServiceDataDTO } from './dtos/admin-panel-health-service-data.dto';import { MaintenanceModeDTO } from './dtos/maintenance-mode.dto';-import { ModelsDevModelSuggestionDTO } from './dtos/models-dev-model-suggestion.dto';-import { ModelsDevProviderSuggestionDTO } from './dtos/models-dev-provider-suggestion.dto';import { QueueMetricsDataDTO } from './dtos/queue-metrics-data.dto';import { SetMaintenanceModeInput } from './dtos/set-maintenance-mode.input';@@ -147,8 +139,6 @@ export class AdminPanelResolver {private readonly twentyConfigService: TwentyConfigService,private readonly aiModelRegistryService: AiModelRegistryService,private readonly aiModelPreferencesService: AiModelPreferencesService,- private readonly defaultAiCatalogService: DefaultAiCatalogService,- private readonly modelsDevCatalogService: ModelsDevCatalogService,private readonly usageAnalyticsService: UsageAnalyticsService,private readonly maintenanceModeService: MaintenanceModeService,private readonly upgradeStatusService: UpgradeStatusService,@@ -548,180 +538,6 @@ export class AdminPanelResolver {return this.applicationRegistrationService.updateGlobal(input);}- @UseGuards(AdminPanelGuard)- @Query(() => GraphQLJSON)- async getAiProviders(): Promise<Record<string, unknown>> {- const providers =- this.aiModelRegistryService.getResolvedProvidersForAdmin();- const catalogNames = this.aiModelRegistryService.getCatalogProviderNames();- const rawCatalog = this.defaultAiCatalogService.getDefaultAiCatalog();- const masked: Record<string, Record<string, unknown>> = {};-- for (const [key, config] of Object.entries(providers)) {- const isCatalog = catalogNames.has(key);- const rawConfig = isCatalog ? rawCatalog[key] : undefined;- const apiKeyConfigVariable = rawConfig- ? extractConfigVariableName(rawConfig.apiKey)- : undefined;-- masked[key] = {- npm: config.npm,- label: config.label ?? key,- source: isCatalog ? 'catalog' : 'custom',- ...(config.authType && { authType: config.authType }),- ...(config.name && { name: config.name }),- ...(config.baseUrl && { baseUrl: config.baseUrl }),- ...(config.region && { region: config.region }),- ...(config.dataResidency && { dataResidency: config.dataResidency }),- ...(config.apiKey && {- apiKey: `${config.apiKey.substring(0, 8)}...`,- }),- ...(apiKeyConfigVariable && { apiKeyConfigVariable }),- hasAccessKey: !!(config.accessKeyId && config.secretAccessKey),- };- }-- return masked;- }-- @UseGuards(AdminPanelGuard)- @Mutation(() => Boolean)- async addAiProvider(- @Args('providerName', { type: () => String }) providerName: string,- @Args('providerConfig', { type: () => GraphQLJSON })- providerConfig: AiProviderConfig,- ): Promise<boolean> {- if (!/^[a-zA-Z0-9_-]+$/.test(providerName)) {- throw new UserInputError('Invalid provider name');- }-- const customProviders = {- ...this.twentyConfigService.get('AI_PROVIDERS'),- };-- customProviders[providerName] = providerConfig;- await this.twentyConfigService.set('AI_PROVIDERS', customProviders);-- return true;- }-- @UseGuards(AdminPanelGuard)- @Mutation(() => Boolean)- async removeAiProvider(- @Args('providerName', { type: () => String })- providerName: string,- ): Promise<boolean> {- const customProviders = {- ...this.twentyConfigService.get('AI_PROVIDERS'),- };-- delete customProviders[providerName];- await this.twentyConfigService.set('AI_PROVIDERS', customProviders);-- return true;- }-- @UseGuards(AdminPanelGuard)- @Query(() => [ModelsDevProviderSuggestionDTO])- async getModelsDevProviders(): Promise<ModelsDevProviderSuggestionDTO[]> {- return this.modelsDevCatalogService.getProviderSuggestions();- }-- @UseGuards(AdminPanelGuard)- @Query(() => [ModelsDevModelSuggestionDTO])- async getModelsDevSuggestions(- @Args('providerType', { type: () => String }) providerType: string,- ): Promise<ModelsDevModelSuggestionDTO[]> {- return this.modelsDevCatalogService.getModelSuggestions(providerType);- }-- @UseGuards(AdminPanelGuard)- @Mutation(() => Boolean)- async addModelToProvider(- @Args('providerName', { type: () => String }) providerName: string,- @Args('modelConfig', { type: () => GraphQLJSON })- modelConfig: AiProviderModelConfig,- ): Promise<boolean> {- const validatedModelConfig =- aiProviderModelConfigSchema.safeParse(modelConfig);-- if (!validatedModelConfig.success) {- throw new UserInputError(- `Invalid model configuration: ${validatedModelConfig.error.issues- .map((issue) => `${issue.path.join('.')} ${issue.message}`)- .join(', ')}`,- );- }-- const customProviders = {- ...this.twentyConfigService.get('AI_PROVIDERS'),- };-- const existing = customProviders[providerName];-- if (!existing) {- throw new UserInputError(- `Provider "${providerName}" not found in custom providers`,- );- }-- const existingModels = existing.models ?? [];- const alreadyExists = existingModels.some(- (model: AiProviderModelConfig) =>- model.name === validatedModelConfig.data.name,- );-- if (alreadyExists) {- throw new UserInputError(- `Model "${validatedModelConfig.data.name}" already exists on provider "${providerName}"`,- );- }-- customProviders[providerName] = {- ...existing,- models: [- ...existingModels,- { ...validatedModelConfig.data, source: 'manual' },- ],- };-- await this.twentyConfigService.set('AI_PROVIDERS', customProviders);-- return true;- }-- @UseGuards(AdminPanelGuard)- @Mutation(() => Boolean)- async removeModelFromProvider(- @Args('providerName', { type: () => String }) providerName: string,- @Args('modelName', { type: () => String }) modelName: string,- ): Promise<boolean> {- const customProviders = {- ...this.twentyConfigService.get('AI_PROVIDERS'),- };-- const existing = customProviders[providerName];-- if (!existing) {- throw new UserInputError(- `Provider "${providerName}" not found in custom providers`,- );- }-- const existingModels = existing.models ?? [];-- customProviders[providerName] = {- ...existing,- models: existingModels.filter(- (model: AiProviderModelConfig) => model.name !== modelName,- ),- };-- await this.twentyConfigService.set('AI_PROVIDERS', customProviders);-- return true;- }-@UseGuards(AdminPanelGuard)@Query(() => [UsageBreakdownItemDTO])async getAdminAiUsageByWorkspace(diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/custom-ai-provider-access.dto.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/custom-ai-provider-access.dto.tsnew file mode 100644index 00000000000..6e26c28d606--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/custom-ai-provider-access.dto.ts@@ -0,0 +1,15 @@+/* @license Enterprise */++import { Field, Int, ObjectType } from '@nestjs/graphql';++@ObjectType()+export class CustomAiProviderAccessDTO {+ @Field(() => Boolean)+ hasAccess: boolean;++ @Field(() => Int)+ seatCount: number;++ @Field(() => Int)+ seatThreshold: number;+}diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/__tests__/admin-panel-ai-provider.service.spec.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/__tests__/admin-panel-ai-provider.service.spec.tsnew file mode 100644index 00000000000..2596076cb19--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/__tests__/admin-panel-ai-provider.service.spec.ts@@ -0,0 +1,171 @@+/* @license Enterprise */++import { Test, type TestingModule } from '@nestjs/testing';++import { AdminPanelAiProviderService } from 'src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service';+import { MAX_SEATS_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant';+import { EnterpriseExceptionCode } from 'src/engine/core-modules/enterprise/enterprise.exception';+import { CustomAiProviderAccessService } from 'src/engine/core-modules/enterprise/services/custom-ai-provider-access.service';+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';+import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';+import { DefaultAiCatalogService } from 'src/engine/metadata-modules/ai/ai-models/services/default-ai-catalog.service';++describe('AdminPanelAiProviderService', () => {+ let service: AdminPanelAiProviderService;+ let providers: Record<string, unknown>;++ const twentyConfigService = {+ get: jest.fn(),+ set: jest.fn(),+ };++ const enterprisePlanService = {+ isValid: jest.fn(),+ getBillableSeatCount: jest.fn(),+ };++ const givenInstance = ({+ seatCount,+ isBillingEnabled = false,+ isEnterpriseValid = false,+ }: {+ seatCount: number;+ isBillingEnabled?: boolean;+ isEnterpriseValid?: boolean;+ }) => {+ twentyConfigService.get.mockImplementation((key: string) =>+ key === 'IS_BILLING_ENABLED' ? isBillingEnabled : providers,+ );+ enterprisePlanService.isValid.mockReturnValue(isEnterpriseValid);+ enterprisePlanService.getBillableSeatCount.mockResolvedValue(seatCount);+ };++ const addProvider = () =>+ service.addProvider({+ providerName: 'my-gateway',+ providerConfig: {+ npm: '@ai-sdk/openai-compatible',+ baseUrl: 'https://gateway.internal',+ },+ });++ beforeEach(async () => {+ jest.clearAllMocks();+ providers = {};++ twentyConfigService.set.mockImplementation(+ async (_key: string, value: Record<string, unknown>) => {+ providers = value;+ },+ );++ const module: TestingModule = await Test.createTestingModule({+ providers: [+ AdminPanelAiProviderService,+ // The real gate is registered so these cover the seat rules end to end+ // rather than a stub of the very logic under test.+ CustomAiProviderAccessService,+ { provide: TwentyConfigService, useValue: twentyConfigService },+ { provide: EnterprisePlanService, useValue: enterprisePlanService },+ { provide: AiModelRegistryService, useValue: {} },+ { provide: DefaultAiCatalogService, useValue: {} },+ ],+ }).compile();++ service = module.get<AdminPanelAiProviderService>(+ AdminPanelAiProviderService,+ );+ });++ describe('addProvider', () => {+ it('persists the provider when the instance is under the seat threshold', async () => {+ givenInstance({ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY - 1 });++ await expect(addProvider()).resolves.toBe(true);+ expect(providers).toHaveProperty('my-gateway');+ });++ it('refuses and persists nothing above the threshold without an enterprise key', async () => {+ givenInstance({ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1 });++ await expect(addProvider()).rejects.toMatchObject({+ code: EnterpriseExceptionCode.ENTERPRISE_SEAT_THRESHOLD_EXCEEDED,+ });+ expect(twentyConfigService.set).not.toHaveBeenCalled();+ });++ it('persists the provider above the threshold with a valid enterprise key', async () => {+ givenInstance({+ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 100,+ isEnterpriseValid: true,+ });++ await expect(addProvider()).resolves.toBe(true);+ expect(providers).toHaveProperty('my-gateway');+ });++ it('rejects a config whose npm package is not a supported SDK', async () => {+ givenInstance({ seatCount: 1 });++ await expect(+ service.addProvider({+ providerName: 'my-gateway',+ providerConfig: { npm: 'not-an-ai-sdk-package' },+ }),+ ).rejects.toThrow('Invalid provider configuration');+ expect(twentyConfigService.set).not.toHaveBeenCalled();+ });++ it('rejects a provider name that is not slug-safe', async () => {+ givenInstance({ seatCount: 1 });++ await expect(+ service.addProvider({+ providerName: 'not a slug',+ providerConfig: {+ npm: '@ai-sdk/openai-compatible',+ baseUrl: 'https://gateway.internal',+ },+ }),+ ).rejects.toThrow('Invalid provider name');+ });+ });++ describe('addModelToProvider', () => {+ it('refuses above the threshold without an enterprise key', async () => {+ givenInstance({ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1 });++ await expect(+ service.addModelToProvider({+ providerName: 'my-gateway',+ modelConfig: { name: 'gpt-4o', label: 'GPT-4o' },+ }),+ ).rejects.toMatchObject({+ code: EnterpriseExceptionCode.ENTERPRISE_SEAT_THRESHOLD_EXCEEDED,+ });+ });+ });++ describe('removeProvider', () => {+ it('stays available above the threshold so providers can be cleaned up', async () => {+ givenInstance({ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1 });+ providers = { 'my-gateway': { npm: '@ai-sdk/openai-compatible' } };++ await expect(service.removeProvider('my-gateway')).resolves.toBe(true);+ expect(providers).not.toHaveProperty('my-gateway');+ });+ });++ describe('getCustomAiProviderAccess', () => {+ it('reports the threshold alongside the current seat count', async () => {+ givenInstance({ seatCount: 42 });++ await expect(service.getCustomAiProviderAccess()).resolves.toEqual({+ hasAccess: false,+ seatCount: 42,+ seatThreshold: MAX_SEATS_WITHOUT_ENTERPRISE_KEY,+ });+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service.tsnew file mode 100644index 00000000000..0e98d0437a7--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service.ts@@ -0,0 +1,228 @@+/* @license Enterprise */++import { Injectable } from '@nestjs/common';++import { MAX_SEATS_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant';+import {+ EnterpriseException,+ EnterpriseExceptionCode,+} from 'src/engine/core-modules/enterprise/enterprise.exception';+import {+ type CustomAiProviderAccess,+ CustomAiProviderAccessService,+} from 'src/engine/core-modules/enterprise/services/custom-ai-provider-access.service';+import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';+import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';+import { DefaultAiCatalogService } from 'src/engine/metadata-modules/ai/ai-models/services/default-ai-catalog.service';+import { aiProviderConfigSchema } from 'src/engine/metadata-modules/ai/ai-models/types/ai-provider-config.schema';+import { aiProviderModelConfigSchema } from 'src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema';+import { type AiProviderModelConfig } from 'src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.type';+import { extractConfigVariableName } from 'src/engine/metadata-modules/ai/ai-models/utils/extract-config-variable-name.util';++const PROVIDER_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;++@Injectable()+export class AdminPanelAiProviderService {+ constructor(+ private readonly twentyConfigService: TwentyConfigService,+ private readonly customAiProviderAccessService: CustomAiProviderAccessService,+ private readonly aiModelRegistryService: AiModelRegistryService,+ private readonly defaultAiCatalogService: DefaultAiCatalogService,+ ) {}++ // Counting here rather than reading the cached verdict keeps the admin panel+ // exact, and refreshes what model resolution will use on its next read.+ async getCustomAiProviderAccess(): Promise<CustomAiProviderAccess> {+ return this.customAiProviderAccessService.computeAccess();+ }++ private async assertCustomAiProviderAccess(): Promise<void> {+ const { hasAccess, seatCount } = await this.getCustomAiProviderAccess();++ if (hasAccess) {+ return;+ }++ throw new EnterpriseException(+ `Custom AI providers require a valid enterprise key above ${MAX_SEATS_WITHOUT_ENTERPRISE_KEY} seats (this instance has ${seatCount})`,+ EnterpriseExceptionCode.ENTERPRISE_SEAT_THRESHOLD_EXCEEDED,+ );+ }++ getMaskedProviders(): Record<string, unknown> {+ const providers =+ this.aiModelRegistryService.getResolvedProvidersForAdmin();+ const catalogNames = this.aiModelRegistryService.getCatalogProviderNames();+ const rawCatalog = this.defaultAiCatalogService.getDefaultAiCatalog();+ const masked: Record<string, Record<string, unknown>> = {};++ for (const [key, config] of Object.entries(providers)) {+ const isCatalog = catalogNames.has(key);+ const rawConfig = isCatalog ? rawCatalog[key] : undefined;+ const apiKeyConfigVariable = rawConfig+ ? extractConfigVariableName(rawConfig.apiKey)+ : undefined;++ masked[key] = {+ npm: config.npm,+ label: config.label ?? key,+ source: isCatalog ? 'catalog' : 'custom',+ ...(config.authType && { authType: config.authType }),+ ...(config.name && { name: config.name }),+ ...(config.baseUrl && { baseUrl: config.baseUrl }),+ ...(config.region && { region: config.region }),+ ...(config.dataResidency && { dataResidency: config.dataResidency }),+ ...(config.apiKey && {+ apiKey: `${config.apiKey.substring(0, 8)}...`,+ }),+ ...(apiKeyConfigVariable && { apiKeyConfigVariable }),+ hasAccessKey: !!(config.accessKeyId && config.secretAccessKey),+ };+ }++ return masked;+ }++ // Both configs arrive as untyped JSON from the GraphQL layer, so they are+ // taken as unknown and given their shape by the schemas below.+ async addProvider({+ providerName,+ providerConfig,+ }: {+ providerName: string;+ providerConfig: unknown;+ }): Promise<boolean> {+ await this.assertCustomAiProviderAccess();++ if (!PROVIDER_NAME_PATTERN.test(providerName)) {+ throw new UserInputError('Invalid provider name');+ }++ // The GraphQL arg is untyped JSON, so an unsupported npm package would only+ // surface later when the registry builds the provider, taking down model+ // resolution for every provider on the instance.+ const validatedProviderConfig =+ aiProviderConfigSchema.safeParse(providerConfig);++ if (!validatedProviderConfig.success) {+ throw new UserInputError(+ `Invalid provider configuration: ${validatedProviderConfig.error.issues+ .map((issue) => `${issue.path.join('.')} ${issue.message}`)+ .join(', ')}`,+ );+ }++ const customProviders = {+ ...this.twentyConfigService.get('AI_PROVIDERS'),+ };++ customProviders[providerName] = validatedProviderConfig.data;+ await this.twentyConfigService.set('AI_PROVIDERS', customProviders);++ return true;+ }++ // Removal stays open so an instance that grows past the threshold can still+ // clean up the providers it configured while it was under it.+ async removeProvider(providerName: string): Promise<boolean> {+ const customProviders = {+ ...this.twentyConfigService.get('AI_PROVIDERS'),+ };++ delete customProviders[providerName];+ await this.twentyConfigService.set('AI_PROVIDERS', customProviders);++ return true;+ }++ async addModelToProvider({+ providerName,+ modelConfig,+ }: {+ providerName: string;+ modelConfig: unknown;+ }): Promise<boolean> {+ await this.assertCustomAiProviderAccess();++ const validatedModelConfig =+ aiProviderModelConfigSchema.safeParse(modelConfig);++ if (!validatedModelConfig.success) {+ throw new UserInputError(+ `Invalid model configuration: ${validatedModelConfig.error.issues+ .map((issue) => `${issue.path.join('.')} ${issue.message}`)+ .join(', ')}`,+ );+ }++ const customProviders = {+ ...this.twentyConfigService.get('AI_PROVIDERS'),+ };++ const existing = customProviders[providerName];++ if (!existing) {+ throw new UserInputError(+ `Provider "${providerName}" not found in custom providers`,+ );+ }++ const existingModels = existing.models ?? [];+ const alreadyExists = existingModels.some(+ (model: AiProviderModelConfig) =>+ model.name === validatedModelConfig.data.name,+ );++ if (alreadyExists) {+ throw new UserInputError(+ `Model "${validatedModelConfig.data.name}" already exists on provider "${providerName}"`,+ );+ }++ customProviders[providerName] = {+ ...existing,+ models: [+ ...existingModels,+ { ...validatedModelConfig.data, source: 'manual' },+ ],+ };++ await this.twentyConfigService.set('AI_PROVIDERS', customProviders);++ return true;+ }++ async removeModelFromProvider({+ providerName,+ modelName,+ }: {+ providerName: string;+ modelName: string;+ }): Promise<boolean> {+ const customProviders = {+ ...this.twentyConfigService.get('AI_PROVIDERS'),+ };++ const existing = customProviders[providerName];++ if (!existing) {+ throw new UserInputError(+ `Provider "${providerName}" not found in custom providers`,+ );+ }++ const existingModels = existing.models ?? [];++ customProviders[providerName] = {+ ...existing,+ models: existingModels.filter(+ (model: AiProviderModelConfig) => model.name !== modelName,+ ),+ };++ await this.twentyConfigService.set('AI_PROVIDERS', customProviders);++ return true;+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-refresh-interval.constant.ts b/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-refresh-interval.constant.tsnew file mode 100644index 00000000000..77f4c5fe59c--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-refresh-interval.constant.ts@@ -0,0 +1,7 @@+/* @license Enterprise */++// Model resolution reads the entitlement synchronously, so seats are counted on+// this cadence instead: an instance that crosses the threshold keeps resolving+// its custom models for at most this long. Well under the daily seat report,+// and one COUNT per hour per process is far cheaper than one per inference.+export const CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS = 60 * 60 * 1000;diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-retry-interval.constant.ts b/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-retry-interval.constant.tsnew file mode 100644index 00000000000..f442f99f179--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-retry-interval.constant.ts@@ -0,0 +1,7 @@+/* @license Enterprise */++// A count that failed leaves a verdict that may be wrong in either direction, so+// it is retried far sooner than a successful one is refreshed. Still an interval+// rather than an immediate retry: a database that stays down would otherwise put+// a count back on the path of every single model resolution.+export const CUSTOM_AI_PROVIDER_ACCESS_RETRY_INTERVAL_MS = 60 * 1000;diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant.ts b/packages/twenty-server/src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant.tsnew file mode 100644index 00000000000..ad9037af3c4--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant.ts@@ -0,0 +1,6 @@+/* @license Enterprise */++// Custom AI providers stay complimentary for small organizations: an instance+// is only asked for an enterprise key once it grows past this many distinct+// users, so self-hosters and small teams are never gated.+export const MAX_SEATS_WITHOUT_ENTERPRISE_KEY = 25;diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise-exception.filter.tsindex 3fecf1162b6..e35ee838887 100644--- a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise-exception.filter.ts+++ b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise-exception.filter.ts@@ -26,6 +26,7 @@ export class EnterpriseExceptionFilter implements ExceptionFilter {case EnterpriseExceptionCode.ENTERPRISE_DEV_SLOT_IN_USE:case EnterpriseExceptionCode.ENTERPRISE_RELEASE_RATE_LIMITED:case EnterpriseExceptionCode.ENTERPRISE_VALIDITY_TOKEN_RATE_LIMITED:+ case EnterpriseExceptionCode.ENTERPRISE_SEAT_THRESHOLD_EXCEEDED:throw new ForbiddenError(exception);default: {assertUnreachable(exception.code);diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.exception.ts b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.exception.tsindex 375b2128b0a..b50ecb2b43f 100644--- a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.exception.ts+++ b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.exception.ts@@ -4,6 +4,7 @@ import { type MessageDescriptor } from '@lingui/core';import { msg } from '@lingui/core/macro';import { assertUnreachable } from 'twenty-shared/utils';+import { MAX_SEATS_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant';import { CustomException } from 'src/utils/custom-exception';export enum EnterpriseExceptionCode {@@ -15,6 +16,7 @@ export enum EnterpriseExceptionCode {ENTERPRISE_DEV_SLOT_IN_USE = 'ENTERPRISE_DEV_SLOT_IN_USE',ENTERPRISE_RELEASE_RATE_LIMITED = 'ENTERPRISE_RELEASE_RATE_LIMITED',ENTERPRISE_VALIDITY_TOKEN_RATE_LIMITED = 'ENTERPRISE_VALIDITY_TOKEN_RATE_LIMITED',+ ENTERPRISE_SEAT_THRESHOLD_EXCEEDED = 'ENTERPRISE_SEAT_THRESHOLD_EXCEEDED',}const getEnterpriseExceptionUserFriendlyMessage = (@@ -37,6 +39,8 @@ const getEnterpriseExceptionUserFriendlyMessage = (return msg`You have reached the maximum number of server transfers allowed in the last 30 days for this enterprise key. Please try again later.`;case EnterpriseExceptionCode.ENTERPRISE_VALIDITY_TOKEN_RATE_LIMITED:return msg`You have reached the maximum number of license refreshes allowed today for this enterprise key. Please try again later.`;+ case EnterpriseExceptionCode.ENTERPRISE_SEAT_THRESHOLD_EXCEEDED:+ return msg`This feature is complimentary up to ${MAX_SEATS_WITHOUT_ENTERPRISE_KEY} seats. Your instance is above that, so an enterprise key is required.`;default:assertUnreachable(code);}diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.module.ts b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.module.tsindex feb6e440917..2feb9496660 100644--- a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.module.ts+++ b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.module.ts@@ -6,6 +6,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';import { AppTokenEntity } from 'src/engine/core-modules/app-token/app-token.entity';import { EnterpriseKeyValidationCronJob } from 'src/engine/core-modules/enterprise/cron/jobs/enterprise-key-validation.cron.job';import { EnterpriseResolver } from 'src/engine/core-modules/enterprise/enterprise.resolver';+import { CustomAiProviderAccessService } from 'src/engine/core-modules/enterprise/services/custom-ai-provider-access.service';import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';@@ -24,9 +25,14 @@ import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.ent],providers: [EnterprisePlanService,+ CustomAiProviderAccessService,EnterpriseKeyValidationCronJob,EnterpriseResolver,],- exports: [EnterprisePlanService, EnterpriseKeyValidationCronJob],+ exports: [+ EnterprisePlanService,+ CustomAiProviderAccessService,+ EnterpriseKeyValidationCronJob,+ ],})export class EnterpriseModule {}diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/services/__tests__/custom-ai-provider-access.service.spec.ts b/packages/twenty-server/src/engine/core-modules/enterprise/services/__tests__/custom-ai-provider-access.service.spec.tsnew file mode 100644index 00000000000..4b62b4fe2c1--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/enterprise/services/__tests__/custom-ai-provider-access.service.spec.ts@@ -0,0 +1,159 @@+/* @license Enterprise */++import { Test, type TestingModule } from '@nestjs/testing';++import { CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS } from 'src/engine/core-modules/enterprise/constants/custom-ai-provider-access-refresh-interval.constant';+import { CUSTOM_AI_PROVIDER_ACCESS_RETRY_INTERVAL_MS } from 'src/engine/core-modules/enterprise/constants/custom-ai-provider-access-retry-interval.constant';+import { MAX_SEATS_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant';+import { CustomAiProviderAccessService } from 'src/engine/core-modules/enterprise/services/custom-ai-provider-access.service';+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';++describe('CustomAiProviderAccessService', () => {+ let service: CustomAiProviderAccessService;++ const twentyConfigService = { get: jest.fn() };+ const enterprisePlanService = {+ isValid: jest.fn(),+ getBillableSeatCount: jest.fn(),+ };++ const givenSeatCount = (seatCount: number) =>+ enterprisePlanService.getBillableSeatCount.mockResolvedValue(seatCount);++ // The refresh is deliberately not awaited by its caller, so the assertions+ // that follow one have to let the microtask queue drain first.+ const flushPendingRefresh = () => Promise.resolve();++ // The staleness rules are the point of these cases, so the clock is driven+ // rather than mocked per case — reading the real Date.now to build the next+ // value compounds against the previous mock and silently overshoots.+ const START_TIME = 1_700_000_000_000;+ let currentTime = START_TIME;++ const advanceClockTo = (millisecondsFromStart: number) => {+ currentTime = START_TIME + millisecondsFromStart;+ };++ beforeEach(async () => {+ jest.clearAllMocks();+ currentTime = START_TIME;+ jest.spyOn(Date, 'now').mockImplementation(() => currentTime);+ twentyConfigService.get.mockReturnValue(false);+ enterprisePlanService.isValid.mockReturnValue(false);+ givenSeatCount(1);++ const module: TestingModule = await Test.createTestingModule({+ providers: [+ CustomAiProviderAccessService,+ { provide: TwentyConfigService, useValue: twentyConfigService },+ { provide: EnterprisePlanService, useValue: enterprisePlanService },+ ],+ }).compile();++ service = module.get<CustomAiProviderAccessService>(+ CustomAiProviderAccessService,+ );+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ describe('computeAccess', () => {+ it('reports the threshold alongside the seat count it counted', async () => {+ givenSeatCount(MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1);++ await expect(service.computeAccess()).resolves.toEqual({+ hasAccess: false,+ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1,+ seatThreshold: MAX_SEATS_WITHOUT_ENTERPRISE_KEY,+ });+ });+ });++ describe('getCachedHasAccess', () => {+ it('grants access before any count has come back', () => {+ givenSeatCount(MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1);++ expect(service.getCachedHasAccess()).toBe(true);+ });++ it('serves the verdict of the refresh it triggered to later callers', async () => {+ givenSeatCount(MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1);++ service.getCachedHasAccess();+ await flushPendingRefresh();++ expect(service.getCachedHasAccess()).toBe(false);+ });++ it('counts seats once per refresh interval however often it is read', async () => {+ service.getCachedHasAccess();+ await flushPendingRefresh();+ service.getCachedHasAccess();+ service.getCachedHasAccess();++ expect(enterprisePlanService.getBillableSeatCount).toHaveBeenCalledTimes(+ 1,+ );+ });++ it('counts again once the interval has elapsed', async () => {+ service.getCachedHasAccess();+ await flushPendingRefresh();++ advanceClockTo(CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS);+ service.getCachedHasAccess();+ await flushPendingRefresh();++ expect(enterprisePlanService.getBillableSeatCount).toHaveBeenCalledTimes(+ 2,+ );+ });++ it('retries a failed count on the short interval instead of waiting a full refresh', async () => {+ service.getCachedHasAccess();+ await flushPendingRefresh();++ enterprisePlanService.getBillableSeatCount.mockRejectedValue(+ new Error('connection terminated'),+ );+ advanceClockTo(CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS);+ service.getCachedHasAccess();+ await flushPendingRefresh();++ expect(enterprisePlanService.getBillableSeatCount).toHaveBeenCalledTimes(+ 2,+ );++ // One retry interval past the failed count, and nowhere near another full+ // refresh interval: the stamp taken before that count would otherwise hold+ // the stale verdict for an hour.+ advanceClockTo(+ CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS ++ CUSTOM_AI_PROVIDER_ACCESS_RETRY_INTERVAL_MS,+ );+ service.getCachedHasAccess();+ await flushPendingRefresh();++ expect(enterprisePlanService.getBillableSeatCount).toHaveBeenCalledTimes(+ 3,+ );+ });++ it('keeps the previous verdict when the count fails, rather than disabling AI', async () => {+ service.getCachedHasAccess();+ await flushPendingRefresh();++ enterprisePlanService.getBillableSeatCount.mockRejectedValue(+ new Error('connection terminated'),+ );+ advanceClockTo(CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS);+ service.getCachedHasAccess();+ await flushPendingRefresh();++ expect(service.getCachedHasAccess()).toBe(true);+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/services/custom-ai-provider-access.service.ts b/packages/twenty-server/src/engine/core-modules/enterprise/services/custom-ai-provider-access.service.tsnew file mode 100644index 00000000000..53800775136--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/enterprise/services/custom-ai-provider-access.service.ts@@ -0,0 +1,94 @@+/* @license Enterprise */++import { Injectable, Logger } from '@nestjs/common';++import { isDefined } from 'twenty-shared/utils';++import { CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS } from 'src/engine/core-modules/enterprise/constants/custom-ai-provider-access-refresh-interval.constant';+import { CUSTOM_AI_PROVIDER_ACCESS_RETRY_INTERVAL_MS } from 'src/engine/core-modules/enterprise/constants/custom-ai-provider-access-retry-interval.constant';+import { MAX_SEATS_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant';+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';+import { hasCustomAiProviderAccess } from 'src/engine/core-modules/enterprise/utils/has-custom-ai-provider-access.util';+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';++export type CustomAiProviderAccess = {+ hasAccess: boolean;+ seatCount: number;+ seatThreshold: number;+};++@Injectable()+export class CustomAiProviderAccessService {+ private readonly logger = new Logger(CustomAiProviderAccessService.name);++ // Assumed granted until the first count returns, so a cold process never drops+ // an entitled instance's custom models while the query is still in flight.+ private hasAccess = true;+ private lastRefreshStartedAt: number | null = null;+ private didLastRefreshFail = false;++ constructor(+ private readonly twentyConfigService: TwentyConfigService,+ private readonly enterprisePlanService: EnterprisePlanService,+ ) {}++ async computeAccess(): Promise<CustomAiProviderAccess> {+ // Stamped before the first await so concurrent synchronous readers cannot+ // each start their own count.+ this.lastRefreshStartedAt = Date.now();++ try {+ const seatCount = await this.enterprisePlanService.getBillableSeatCount();++ this.hasAccess = hasCustomAiProviderAccess({+ isBillingEnabled: this.twentyConfigService.get('IS_BILLING_ENABLED'),+ hasValidEnterprisePlan: this.enterprisePlanService.isValid(),+ seatCount,+ });+ this.didLastRefreshFail = false;++ return {+ hasAccess: this.hasAccess,+ seatCount,+ seatThreshold: MAX_SEATS_WITHOUT_ENTERPRISE_KEY,+ };+ } catch (error) {+ this.didLastRefreshFail = true;++ throw error;+ }+ }++ // Callers on the inference path resolve models synchronously and must not wait+ // on a seat count, so they get the last verdict and only start a refresh once+ // it has aged out — whoever reads next picks the new one up.+ getCachedHasAccess(): boolean {+ if (this.isVerdictStale()) {+ // computeAccess stamps the clock before its first await, so a second+ // synchronous caller cannot start a competing count.+ this.computeAccess().catch((error) => {+ // A count that fails must never disable AI: the previous verdict stands+ // until a later refresh succeeds.+ this.logger.warn(+ `Could not refresh custom AI provider access: ${+ error instanceof Error ? error.message : 'Unknown error'+ }. Keeping the previous verdict.`,+ );+ });+ }++ return this.hasAccess;+ }++ private isVerdictStale(): boolean {+ if (!isDefined(this.lastRefreshStartedAt)) {+ return true;+ }++ const refreshInterval = this.didLastRefreshFail+ ? CUSTOM_AI_PROVIDER_ACCESS_RETRY_INTERVAL_MS+ : CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS;++ return Date.now() - this.lastRefreshStartedAt >= refreshInterval;+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/utils/__tests__/has-custom-ai-provider-access.util.spec.ts b/packages/twenty-server/src/engine/core-modules/enterprise/utils/__tests__/has-custom-ai-provider-access.util.spec.tsnew file mode 100644index 00000000000..2199ec57706--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/enterprise/utils/__tests__/has-custom-ai-provider-access.util.spec.ts@@ -0,0 +1,58 @@+/* @license Enterprise */++import { MAX_SEATS_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant';+import { hasCustomAiProviderAccess } from 'src/engine/core-modules/enterprise/utils/has-custom-ai-provider-access.util';++describe('hasCustomAiProviderAccess', () => {+ const selfHosted = {+ isBillingEnabled: false,+ hasValidEnterprisePlan: false,+ };++ it('grants access below the seat threshold', () => {+ expect(+ hasCustomAiProviderAccess({+ ...selfHosted,+ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY - 1,+ }),+ ).toBe(true);+ });++ it('grants access exactly at the seat threshold', () => {+ expect(+ hasCustomAiProviderAccess({+ ...selfHosted,+ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY,+ }),+ ).toBe(true);+ });++ it('denies access one seat above the threshold', () => {+ expect(+ hasCustomAiProviderAccess({+ ...selfHosted,+ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1,+ }),+ ).toBe(false);+ });++ it('grants access above the threshold with a valid enterprise plan', () => {+ expect(+ hasCustomAiProviderAccess({+ isBillingEnabled: false,+ hasValidEnterprisePlan: true,+ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 100,+ }),+ ).toBe(true);+ });++ it('grants access on a billing-enabled instance whatever its seat count', () => {+ expect(+ hasCustomAiProviderAccess({+ isBillingEnabled: true,+ hasValidEnterprisePlan: false,+ seatCount: 10_000,+ }),+ ).toBe(true);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/utils/has-custom-ai-provider-access.util.ts b/packages/twenty-server/src/engine/core-modules/enterprise/utils/has-custom-ai-provider-access.util.tsnew file mode 100644index 00000000000..daa1b7f8b6d--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/enterprise/utils/has-custom-ai-provider-access.util.ts@@ -0,0 +1,21 @@+/* @license Enterprise */++import { MAX_SEATS_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant';++type HasCustomAiProviderAccessArgs = {+ isBillingEnabled: boolean;+ hasValidEnterprisePlan: boolean;+ seatCount: number;+};++// Cloud runs a single instance whose seat count spans every customer, so the+// threshold would always trip; there the plan is enforced per workspace by+// billing entitlements instead.+export const hasCustomAiProviderAccess = ({+ isBillingEnabled,+ hasValidEnterprisePlan,+ seatCount,+}: HasCustomAiProviderAccessArgs): boolean =>+ isBillingEnabled ||+ hasValidEnterprisePlan ||+ seatCount <= MAX_SEATS_WITHOUT_ENTERPRISE_KEY;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/ai-models.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/ai-models.module.tsindex 3fe9362e2fb..a12ee10b2a8 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/ai-models.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/ai-models.module.ts@@ -1,5 +1,6 @@import { Global, Module } from '@nestjs/common';+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';import { AiModelConfigService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-config.service';import { AiModelPreferencesService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-preferences.service';import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';@@ -11,6 +12,7 @@ import { SdkProviderFactoryService } from 'src/engine/metadata-modules/ai/ai-mod@Global()@Module({+ imports: [EnterpriseModule],providers: [DefaultAiCatalogService,ProviderConfigService,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.tsindex 1f112317e17..8fb309edc5f 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts@@ -1,8 +1,11 @@import { Injectable, Logger } from '@nestjs/common';import { type LanguageModel } from 'ai';+import { isNonEmptyString } from '@sniptt/guards';import { type AiSdkPackage } from 'twenty-shared/ai';+import { MAX_SEATS_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/enterprise/constants/max-seats-without-enterprise-key.constant';+import { CustomAiProviderAccessService } from 'src/engine/core-modules/enterprise/services/custom-ai-provider-access.service';import { ConfigVariablesGroup } from 'src/engine/core-modules/twenty-config/enums/config-variables-group.enum';import { ConfigGroupHashService } from 'src/engine/core-modules/twenty-config/services/config-group-hash.service';import { AiModelRole } from 'src/engine/metadata-modules/ai/ai-models/types/ai-model-role.enum';@@ -55,37 +58,50 @@ export class AiModelRegistryService {{ providerName: string; modelDef: AiProviderModelConfig }> = new Map();private currentConfigHash: string | null = null;+ private areCustomProvidersRegistered = true;constructor(private readonly providerConfigService: ProviderConfigService,private readonly sdkProviderFactory: SdkProviderFactoryService,private readonly preferencesService: AiModelPreferencesService,private readonly configGroupHashService: ConfigGroupHashService,+ private readonly customAiProviderAccessService: CustomAiProviderAccessService,) {}// The registry is rebuilt lazily whenever the LLM-group config hash changes,// so any mutation to an LLM-tagged config variable is picked up automatically- // on the next read — no explicit refresh from callers needed.+ // on the next read — no explicit refresh from callers needed. Seats are not+ // part of that hash, so the custom-provider entitlement is compared alongside+ // it: an instance that grows past the threshold loses its custom models on the+ // next read rather than waiting for an unrelated config change.private ensureFresh(): void {const configHash = this.configGroupHashService.computeHash(ConfigVariablesGroup.LLM,);+ const areCustomProvidersAllowed =+ this.customAiProviderAccessService.getCachedHasAccess();- if (configHash === this.currentConfigHash) {+ if (+ configHash === this.currentConfigHash &&+ areCustomProvidersAllowed === this.areCustomProvidersRegistered+ ) {return;}- this.buildModelRegistry();+ this.buildModelRegistry(areCustomProvidersAllowed);this.currentConfigHash = configHash;+ this.areCustomProvidersRegistered = areCustomProvidersAllowed;}- private buildModelRegistry(): void {+ private buildModelRegistry(areCustomProvidersAllowed: boolean): void {this.modelRegistry.clear();this.sdkProviderFactory.clearCache();this.modelConfigCache.clear();this.providerModelDefCache.clear();- const providers = this.providerConfigService.getResolvedProviders();+ const providers = this.providerConfigService.getResolvedProviders({+ includeCustomProviders: areCustomProvidersAllowed,+ });this.registerModelsFromProviders(providers);}@@ -263,11 +279,33 @@ export class AiModelRegistryService {}throw new AiException(- `Model with ID ${modelId} not found`,+ this.buildModelNotFoundMessage(modelId),AiExceptionCode.AGENT_EXECUTION_FAILED,);}+ // A model that disappeared because the instance outgrew the complimentary+ // threshold looks exactly like a typo from the caller's side, so the reason is+ // spelled out rather than leaving an operator to guess at a missing model.+ private buildModelNotFoundMessage(modelId: string): string {+ const message = `Model with ID ${modelId} not found`;++ if (this.areCustomProvidersRegistered) {+ return message;+ }++ const [providerName] = modelId.split('/');+ const isCustomProviderModel =+ isNonEmptyString(providerName) &&+ !this.providerConfigService.getCatalogProviderNames().has(providerName);++ if (!isCustomProviderModel) {+ return message;+ }++ return `${message}. Custom AI providers require a valid enterprise key above ${MAX_SEATS_WITHOUT_ENTERPRISE_KEY} seats.`;+ }+private createDefaultConfigForCustomModel(registeredModel: RegisteredAiModel,): AiModelConfig {diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/provider-config.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/provider-config.service.tsindex 83569a1d68a..ba383b15868 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/provider-config.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/provider-config.service.ts@@ -21,11 +21,20 @@ export class ProviderConfigService {);}- getResolvedProviders(): AiProvidersConfig {+ getResolvedProviders({+ includeCustomProviders = true,+ }: { includeCustomProviders?: boolean } = {}): AiProvidersConfig {const rawCatalog = this.defaultAiCatalogService.getDefaultAiCatalog();// Only resolve {{VAR}} templates in the committed catalog — never in// user-supplied custom providers, to prevent config variable exfiltration.const catalog = this.resolveTemplates(rawCatalog);++ // Dropping the custom entries rather than filtering the merged map also+ // restores a catalog provider that a custom entry of the same name shadows.+ if (!includeCustomProviders) {+ return catalog;+ }+const custom = this.twentyConfigService.get('AI_PROVIDERS');return { ...catalog, ...custom };diff --git a/packages/twenty-server/test/integration/ai/suites/workflow-agent-role-assignment-persistence.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/workflow-agent-role-assignment-persistence.integration-spec.tsindex d8ab0949d5d..d70dab3cc42 100644--- a/packages/twenty-server/test/integration/ai/suites/workflow-agent-role-assignment-persistence.integration-spec.ts+++ b/packages/twenty-server/test/integration/ai/suites/workflow-agent-role-assignment-persistence.integration-spec.ts@@ -1,3 +1,4 @@+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';import { getRepositoryToken } from '@nestjs/typeorm';import { type Repository } from 'typeorm';@@ -41,7 +42,7 @@ describe('Workflow agent role assignment persistence (integration)', () => {input: {label: 'Role-Assigned Workflow Agent',prompt: 'Test prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,roleId,},});@@ -53,7 +54,7 @@ describe('Workflow agent role assignment persistence (integration)', () => {input: {label: 'Roleless Workflow Agent',prompt: 'Test prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},});diff --git a/packages/twenty-server/test/integration/constants/test-ai-model-ids.constants.ts b/packages/twenty-server/test/integration/constants/test-ai-model-ids.constants.tsnew file mode 100644index 00000000000..e7e66e17e78--- /dev/null+++ b/packages/twenty-server/test/integration/constants/test-ai-model-ids.constants.ts@@ -0,0 +1,22 @@+import { DEFAULT_RECOMMENDED_MODELS } from 'src/engine/metadata-modules/ai/ai-models/utils/load-default-model-preferences.util';++// Workspaces default to useRecommendedModels, so an agent can only be created+// with a model from this list. Reading the ids from it rather than naming them+// keeps these suites working when the list is refreshed against the models.dev+// catalog — that refresh lands on a daily automerge, and the previous+// hardcoded openai/gpt-4.1 broke every agent suite when it dropped out.+export const [TEST_AI_MODEL_ID, TEST_AI_OTHER_MODEL_ID] =+ DEFAULT_RECOMMENDED_MODELS;++// Two distinct ids are load-bearing: the update suites assert a transition from+// one model to another, and would pass without testing anything if both were+// the same. Fail at import rather than let a future list shape silently empty+// those assertions out.+if (+ DEFAULT_RECOMMENDED_MODELS.length < 2 ||+ TEST_AI_MODEL_ID === TEST_AI_OTHER_MODEL_ID+) {+ throw new Error(+ 'The agent integration suites need two distinct recommended models: one to create an agent with and one to update it to. DEFAULT_RECOMMENDED_MODELS no longer provides two different ids.',+ );+}diff --git a/packages/twenty-server/test/integration/metadata/suites/agent/failing-agent-creation.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/agent/failing-agent-creation.integration-spec.tsindex 1905266ffae..18b05c5d5bb 100644--- a/packages/twenty-server/test/integration/metadata/suites/agent/failing-agent-creation.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/agent/failing-agent-creation.integration-spec.ts@@ -1,3 +1,4 @@+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';@@ -32,7 +33,7 @@ describe('Agent creation should fail', () => {input: {label: globalTestContext.existingAgentLabel,prompt: 'Existing agent for testing',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},});@@ -54,7 +55,7 @@ describe('Agent creation should fail', () => {context: {input: {prompt: 'Test prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,} as CreateAgentInput,},},@@ -63,7 +64,7 @@ describe('Agent creation should fail', () => {context: {input: {label: 'Test Agent Missing Prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,} as CreateAgentInput,},},@@ -82,7 +83,7 @@ describe('Agent creation should fail', () => {input: {label: '',prompt: 'Test prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},},},@@ -92,7 +93,7 @@ describe('Agent creation should fail', () => {input: {label: 'Empty Prompt Agent',prompt: '',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},},},@@ -112,7 +113,7 @@ describe('Agent creation should fail', () => {input: {label: globalTestContext.existingAgentLabel,prompt: 'Duplicate agent',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},},},@@ -122,7 +123,7 @@ describe('Agent creation should fail', () => {input: {label: 'Invalid Response Format Agent',prompt: 'Test prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,responseFormat: {type: 'invalid',} as any,@@ -135,7 +136,7 @@ describe('Agent creation should fail', () => {input: {label: 'JSON Without Schema Agent',prompt: 'Test prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,responseFormat: {type: 'json',} as any,@@ -148,7 +149,7 @@ describe('Agent creation should fail', () => {input: {label: 'Text With Schema Agent',prompt: 'Test prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,responseFormat: {type: 'text',schema: { type: 'object' },diff --git a/packages/twenty-server/test/integration/metadata/suites/agent/failing-agent-update.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/agent/failing-agent-update.integration-spec.tsindex e21c5a8a185..68a031a8cc7 100644--- a/packages/twenty-server/test/integration/metadata/suites/agent/failing-agent-update.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/agent/failing-agent-update.integration-spec.ts@@ -1,3 +1,4 @@+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';import { faker } from '@faker-js/faker';import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';@@ -40,7 +41,7 @@ describe('Agent update should fail', () => {input: {label: globalTestContext.existingAgentLabelForDuplicate,prompt: 'Existing agent for duplicate test',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},});@@ -55,7 +56,7 @@ describe('Agent update should fail', () => {description: 'Original description',icon: 'IconRobot',prompt: 'Original prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},});diff --git a/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-creation.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-creation.integration-spec.tsindex c2a8978e55b..0adcae3d4b0 100644--- a/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-creation.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-creation.integration-spec.ts@@ -1,3 +1,7 @@+import {+ TEST_AI_MODEL_ID,+ TEST_AI_OTHER_MODEL_ID,+} from 'test/integration/constants/test-ai-model-ids.constants';import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';@@ -23,7 +27,7 @@ describe('Agent creation should succeed', () => {input: {label: 'Test Agent',prompt: 'You are a helpful test assistant',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},});@@ -36,7 +40,7 @@ describe('Agent creation should succeed', () => {icon: null,description: null,prompt: 'You are a helpful test assistant',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,responseFormat: { type: 'text' },roleId: null,isCustom: true,@@ -52,7 +56,7 @@ describe('Agent creation should succeed', () => {icon: 'IconRobot',description: 'A custom agent with all fields specified',prompt: 'You are a specialized assistant for testing',- modelId: 'openai/gpt-5.2',+ modelId: TEST_AI_OTHER_MODEL_ID,responseFormat: { type: 'text' },modelConfiguration: {webSearch: {@@ -88,7 +92,7 @@ describe('Agent creation should succeed', () => {input: {label: 'JSON Response Agent',prompt: 'Return structured JSON data',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,responseFormat: {type: 'json',schema: {@@ -127,7 +131,7 @@ describe('Agent creation should succeed', () => {input: {label: 'My Test Agent With Spaces',prompt: 'Testing name computation',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},});@@ -149,7 +153,7 @@ describe('Agent creation should succeed', () => {icon: ' IconRobot ',description: ' Description with spaces ',prompt: ' Prompt with spaces ',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},});@@ -190,7 +194,7 @@ describe('Agent creation should succeed', () => {input: {label: 'Agent With Role',prompt: 'Agent with role assignment',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,roleId: createdRoleId,},});@@ -201,7 +205,7 @@ describe('Agent creation should succeed', () => {id: expect.any(String),label: 'Agent With Role',prompt: 'Agent with role assignment',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,roleId: createdRoleId,isCustom: true,});diff --git a/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-deletion.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-deletion.integration-spec.tsindex 54f22b71557..3e4a96816fb 100644--- a/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-deletion.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-deletion.integration-spec.ts@@ -1,3 +1,4 @@+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';import { findOneAgent } from 'test/integration/metadata/suites/agent/utils/find-one-agent.util';@@ -9,7 +10,7 @@ describe('Agent deletion should succeed', () => {input: {label: 'Agent To Delete',prompt: 'This agent will be deleted',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},});diff --git a/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-role-update.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-role-update.integration-spec.tsindex be85b4d8d1b..af5c92c6946 100644--- a/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-role-update.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-role-update.integration-spec.ts@@ -1,3 +1,4 @@+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';import { updateOneAgent } from 'test/integration/metadata/suites/agent/utils/update-one-agent.util';@@ -74,7 +75,7 @@ describe('Agent role update should succeed', () => {input: {label: 'Agent Without Role',prompt: 'Test prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,},});@@ -103,7 +104,7 @@ describe('Agent role update should succeed', () => {input: {label: 'Agent With Initial Role',prompt: 'Test prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,roleId: testRoleId,},});@@ -133,7 +134,7 @@ describe('Agent role update should succeed', () => {input: {label: 'Agent With Role To Remove',prompt: 'Test prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,roleId: testRoleId,},});diff --git a/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-update.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-update.integration-spec.tsindex a652774113b..f21a6929524 100644--- a/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-update.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-update.integration-spec.ts@@ -1,3 +1,7 @@+import {+ TEST_AI_MODEL_ID,+ TEST_AI_OTHER_MODEL_ID,+} from 'test/integration/constants/test-ai-model-ids.constants';import { DEFAULT_TOOL_INPUT_SCHEMA } from 'twenty-shared/logic-function';import { type AgentResponseSchema } from 'twenty-shared/ai';import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';@@ -15,7 +19,7 @@ describe('Agent update should succeed', () => {description: 'Original description',icon: 'IconRobot',prompt: 'Original prompt',- modelId: 'openai/gpt-4.1',+ modelId: TEST_AI_MODEL_ID,responseFormat: { type: 'text' },evaluationInputs: ['input 1'],},@@ -100,13 +104,13 @@ describe('Agent update should succeed', () => {expectToFail: false,input: {id: testAgentId,- modelId: 'openai/gpt-5.2',+ modelId: TEST_AI_OTHER_MODEL_ID,},});expect(data.updateOneAgent).toMatchObject({id: testAgentId,- modelId: 'openai/gpt-5.2',+ modelId: TEST_AI_OTHER_MODEL_ID,});});@@ -226,7 +230,7 @@ describe('Agent update should succeed', () => {description: 'Updated multiple fields',icon: 'IconBrain',prompt: 'New comprehensive prompt',- modelId: 'openai/gpt-5.2',+ modelId: TEST_AI_OTHER_MODEL_ID,responseFormat: {type: 'json',schema: DEFAULT_TOOL_INPUT_SCHEMA as AgentResponseSchema,@@ -241,7 +245,7 @@ describe('Agent update should succeed', () => {description: 'Updated multiple fields',icon: 'IconBrain',prompt: 'New comprehensive prompt',- modelId: 'openai/gpt-5.2',+ modelId: TEST_AI_OTHER_MODEL_ID,responseFormat: {type: 'json',schema: { type: 'object' },