The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(front-components): share one application token pair per application (#26525)
Paul Rastoin89138e61827a
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex fe3b5ef6ed6..2696d32401b 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -97,7 +97,7 @@ type FrontComponent {updatedAt: DateTime!isHeadless: Boolean!usesSdkClient: Boolean!- applicationTokenPair: ApplicationTokenPair+ applicationTokenPair: ApplicationTokenPair @deprecated(reason: "Use generateFrontComponentApplicationTokenPair")applicationVariables: JSONfrontComponentSharedDependenciesChecksum: StringapplicationName: String@@ -4165,6 +4165,7 @@ type Mutation {updateCommandMenuItem(input: UpdateCommandMenuItemInput!): CommandMenuItem!resetCommandMenuItem(id: UUID!): CommandMenuItem!deleteCommandMenuItem(id: UUID!): CommandMenuItem!+ generateFrontComponentApplicationTokenPair(applicationId: UUID!): ApplicationTokenPair!createFrontComponent(input: CreateFrontComponentInput!): FrontComponent!updateFrontComponent(input: UpdateFrontComponentInput!): FrontComponent!deleteFrontComponent(id: UUID!): FrontComponent!diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex e63720ced2f..6d8fb0422ee 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -96,6 +96,7 @@ export interface FrontComponent {updatedAt: Scalars['DateTime']isHeadless: Scalars['Boolean']usesSdkClient: Scalars['Boolean']+ /** @deprecated Use generateFrontComponentApplicationTokenPair */applicationTokenPair?: ApplicationTokenPairapplicationVariables?: Scalars['JSON']frontComponentSharedDependenciesChecksum?: Scalars['String']@@ -3571,6 +3572,7 @@ export interface Mutation {updateCommandMenuItem: CommandMenuItemresetCommandMenuItem: CommandMenuItemdeleteCommandMenuItem: CommandMenuItem+ generateFrontComponentApplicationTokenPair: ApplicationTokenPaircreateFrontComponent: FrontComponentupdateFrontComponent: FrontComponentdeleteFrontComponent: FrontComponent@@ -3846,6 +3848,7 @@ export interface FrontComponentGenqlSelection{updatedAt?: boolean | numberisHeadless?: boolean | numberusesSdkClient?: boolean | number+ /** @deprecated Use generateFrontComponentApplicationTokenPair */applicationTokenPair?: ApplicationTokenPairGenqlSelectionapplicationVariables?: boolean | numberfrontComponentSharedDependenciesChecksum?: boolean | number@@ -7513,6 +7516,7 @@ export interface MutationGenqlSelection{updateCommandMenuItem?: (CommandMenuItemGenqlSelection & { __args: {input: UpdateCommandMenuItemInput} })resetCommandMenuItem?: (CommandMenuItemGenqlSelection & { __args: {id: Scalars['UUID']} })deleteCommandMenuItem?: (CommandMenuItemGenqlSelection & { __args: {id: Scalars['UUID']} })+ generateFrontComponentApplicationTokenPair?: (ApplicationTokenPairGenqlSelection & { __args: {applicationId: Scalars['UUID']} })createFrontComponent?: (FrontComponentGenqlSelection & { __args: {input: CreateFrontComponentInput} })updateFrontComponent?: (FrontComponentGenqlSelection & { __args: {input: UpdateFrontComponentInput} })deleteFrontComponent?: (FrontComponentGenqlSelection & { __args: {id: Scalars['UUID']} })diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex a5ced6f14df..4b8677dbdfc 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -9686,6 +9686,15 @@ export default {]}],+ "generateFrontComponentApplicationTokenPair": [+ 12,+ {+ "applicationId": [+ 3,+ "UUID!"+ ]+ }+ ],"createFrontComponent": [13,{diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 07bcbad0550..0868861fbd2 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -2346,6 +2346,7 @@ export type FrontComponent = {applicationGrantedCapabilities?: Maybe<Array<Scalars['String']['output']>>;applicationId: Scalars['UUID']['output'];applicationName?: Maybe<Scalars['String']['output']>;+ /** @deprecated Use generateFrontComponentApplicationTokenPair */applicationTokenPair?: Maybe<ApplicationTokenPair>;applicationVariables?: Maybe<Scalars['JSON']['output']>;builtComponentChecksum: Scalars['String']['output'];@@ -3156,6 +3157,7 @@ export type Mutation = {evaluateAgentTurn: AgentTurnEvaluation;executeOneLogicFunction: LogicFunctionExecutionResult;generateApiKeyToken: ApiKeyToken;+ generateFrontComponentApplicationTokenPair: ApplicationTokenPair;generatePlaygroundToken: AuthToken;generateTransientToken: TransientToken;getAuthTokensFromLoginToken: AuthTokens;@@ -3947,6 +3949,11 @@ export type MutationGenerateApiKeyTokenArgs = {};+export type MutationGenerateFrontComponentApplicationTokenPairArgs = {+ applicationId: Scalars['UUID']['input'];+};++export type MutationGetAuthTokensFromLoginTokenArgs = {loginToken: Scalars['String']['input'];origin: Scalars['String']['input'];@@ -8606,6 +8613,13 @@ export type CreateFileUploadMutationVariables = Exact<{export type CreateFileUploadMutation = { __typename?: 'Mutation', createFileUpload: { __typename?: 'FileUploadTarget', fileId: string, uploadUrl: string, contentType: string, expiresAt: string } };+export type GenerateFrontComponentApplicationTokenPairMutationVariables = Exact<{+ applicationId: Scalars['UUID']['input'];+}>;+++export type GenerateFrontComponentApplicationTokenPairMutation = { __typename?: 'Mutation', generateFrontComponentApplicationTokenPair: { __typename?: 'ApplicationTokenPair', applicationAccessToken: { __typename?: 'AuthToken', token: string, expiresAt: string }, applicationRefreshToken: { __typename?: 'AuthToken', token: string, expiresAt: string } } };+export type GrantApplicationCapabilitiesMutationVariables = Exact<{input: GrantApplicationCapabilitiesInput;}>;@@ -8637,7 +8651,7 @@ export type FindOneFrontComponentQueryVariables = Exact<{}>;-export type FindOneFrontComponentQuery = { __typename?: 'Query', frontComponent?: { __typename?: 'FrontComponent', id: string, name: string, applicationId: string, applicationName?: string | null, applicationGrantedCapabilities?: Array<string> | null, builtComponentChecksum: string, isHeadless: boolean, usesSdkClient: boolean, frontComponentSharedDependenciesChecksum?: string | null, applicationVariables?: any | null, applicationTokenPair?: { __typename?: 'ApplicationTokenPair', applicationAccessToken: { __typename?: 'AuthToken', token: string, expiresAt: string }, applicationRefreshToken: { __typename?: 'AuthToken', token: string, expiresAt: string } } | null } | null };+export type FindOneFrontComponentQuery = { __typename?: 'Query', frontComponent?: { __typename?: 'FrontComponent', id: string, name: string, applicationId: string, applicationName?: string | null, applicationGrantedCapabilities?: Array<string> | null, builtComponentChecksum: string, isHeadless: boolean, usesSdkClient: boolean, frontComponentSharedDependenciesChecksum?: string | null, applicationVariables?: any | null } | null };export type GetApplicationSdkClientChecksumsQueryVariables = Exact<{applicationId: Scalars['UUID']['input'];@@ -10546,11 +10560,12 @@ export const FindOnePageLayoutDocument = {"kind":"Document","definitions":[{"kinexport const FindOnePageLayoutTypeDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOnePageLayoutType"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getPageLayout"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}}]}}]} as unknown as DocumentNode<FindOnePageLayoutTypeQuery, FindOnePageLayoutTypeQueryVariables>;export const CompleteFileUploadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CompleteFileUpload"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"fileId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"completeFileUpload"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"fileId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"fileId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"path"}},{"kind":"Field","name":{"kind":"Name","value":"size"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"url"}}]}}]}}]} as unknown as DocumentNode<CompleteFileUploadMutation, CompleteFileUploadMutationVariables>;export const CreateFileUploadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateFileUpload"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"filename"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"size"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Float"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"fileFolder"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"FileFolder"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"fieldMetadataId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createFileUpload"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"filename"},"value":{"kind":"Variable","name":{"kind":"Name","value":"filename"}}},{"kind":"Argument","name":{"kind":"Name","value":"size"},"value":{"kind":"Variable","name":{"kind":"Name","value":"size"}}},{"kind":"Argument","name":{"kind":"Name","value":"fileFolder"},"value":{"kind":"Variable","name":{"kind":"Name","value":"fileFolder"}}},{"kind":"Argument","name":{"kind":"Name","value":"fieldMetadataId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"fieldMetadataId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"fileId"}},{"kind":"Field","name":{"kind":"Name","value":"uploadUrl"}},{"kind":"Field","name":{"kind":"Name","value":"contentType"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}}]}}]} as unknown as DocumentNode<CreateFileUploadMutation, CreateFileUploadMutationVariables>;+export const GenerateFrontComponentApplicationTokenPairDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GenerateFrontComponentApplicationTokenPair"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"applicationId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"generateFrontComponentApplicationTokenPair"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"applicationId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"applicationId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"applicationAccessToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"applicationRefreshToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}}]}}]}}]} as unknown as DocumentNode<GenerateFrontComponentApplicationTokenPairMutation, GenerateFrontComponentApplicationTokenPairMutationVariables>;export const GrantApplicationCapabilitiesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GrantApplicationCapabilities"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"GrantApplicationCapabilitiesInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"grantApplicationCapabilities"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"grantedCapabilities"}}]}}]}}]} as unknown as DocumentNode<GrantApplicationCapabilitiesMutation, GrantApplicationCapabilitiesMutationVariables>;export const RenewApplicationTokenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RenewApplicationToken"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"applicationRefreshToken"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"renewApplicationToken"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"applicationRefreshToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"applicationRefreshToken"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"applicationAccessToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"applicationRefreshToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}}]}}]}}]} as unknown as DocumentNode<RenewApplicationTokenMutation, RenewApplicationTokenMutationVariables>;export const FindFrontComponentApplicationCapabilitiesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindFrontComponentApplicationCapabilities"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"frontComponent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationGrantedCapabilities"}}]}}]}}]} as unknown as DocumentNode<FindFrontComponentApplicationCapabilitiesQuery, FindFrontComponentApplicationCapabilitiesQueryVariables>;export const FindManyFrontComponentsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyFrontComponents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"frontComponents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"builtComponentChecksum"}},{"kind":"Field","name":{"kind":"Name","value":"builtComponentPath"}},{"kind":"Field","name":{"kind":"Name","value":"componentName"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"isHeadless"}},{"kind":"Field","name":{"kind":"Name","value":"sourceComponentPath"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"usesSdkClient"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentSharedDependenciesChecksum"}}]}}]}}]} as unknown as DocumentNode<FindManyFrontComponentsQuery, FindManyFrontComponentsQueryVariables>;-export const FindOneFrontComponentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneFrontComponent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"frontComponent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationName"}},{"kind":"Field","name":{"kind":"Name","value":"applicationGrantedCapabilities"}},{"kind":"Field","name":{"kind":"Name","value":"builtComponentChecksum"}},{"kind":"Field","name":{"kind":"Name","value":"isHeadless"}},{"kind":"Field","name":{"kind":"Name","value":"usesSdkClient"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentSharedDependenciesChecksum"}},{"kind":"Field","name":{"kind":"Name","value":"applicationVariables"}},{"kind":"Field","name":{"kind":"Name","value":"applicationTokenPair"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"applicationAccessToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"applicationRefreshToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}}]}}]}}]}}]} as unknown as DocumentNode<FindOneFrontComponentQuery, FindOneFrontComponentQueryVariables>;+export const FindOneFrontComponentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneFrontComponent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"frontComponent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationName"}},{"kind":"Field","name":{"kind":"Name","value":"applicationGrantedCapabilities"}},{"kind":"Field","name":{"kind":"Name","value":"builtComponentChecksum"}},{"kind":"Field","name":{"kind":"Name","value":"isHeadless"}},{"kind":"Field","name":{"kind":"Name","value":"usesSdkClient"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentSharedDependenciesChecksum"}},{"kind":"Field","name":{"kind":"Name","value":"applicationVariables"}}]}}]}}]} as unknown as DocumentNode<FindOneFrontComponentQuery, FindOneFrontComponentQueryVariables>;export const GetApplicationSdkClientChecksumsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetApplicationSdkClientChecksums"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"applicationId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"applicationSdkClientChecksums"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"applicationId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"applicationId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"core"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}}]}}]} as unknown as DocumentNode<GetApplicationSdkClientChecksumsQuery, GetApplicationSdkClientChecksumsQueryVariables>;export const GetAutoCompleteAddressDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAutoCompleteAddress"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"address"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"token"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"country"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"isFieldCity"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAutoCompleteAddress"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"address"},"value":{"kind":"Variable","name":{"kind":"Name","value":"address"}}},{"kind":"Argument","name":{"kind":"Name","value":"token"},"value":{"kind":"Variable","name":{"kind":"Name","value":"token"}}},{"kind":"Argument","name":{"kind":"Name","value":"country"},"value":{"kind":"Variable","name":{"kind":"Name","value":"country"}}},{"kind":"Argument","name":{"kind":"Name","value":"isFieldCity"},"value":{"kind":"Variable","name":{"kind":"Name","value":"isFieldCity"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"text"}},{"kind":"Field","name":{"kind":"Name","value":"placeId"}}]}}]}}]} as unknown as DocumentNode<GetAutoCompleteAddressQuery, GetAutoCompleteAddressQueryVariables>;export const GetAddressDetailsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAddressDetails"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"placeId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"token"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAddressDetails"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"placeId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"placeId"}}},{"kind":"Argument","name":{"kind":"Name","value":"token"},"value":{"kind":"Variable","name":{"kind":"Name","value":"token"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"street"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"postcode"}},{"kind":"Field","name":{"kind":"Name","value":"city"}},{"kind":"Field","name":{"kind":"Name","value":"country"}},{"kind":"Field","name":{"kind":"Name","value":"location"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"lat"}},{"kind":"Field","name":{"kind":"Name","value":"lng"}}]}}]}}]}}]} as unknown as DocumentNode<GetAddressDetailsQuery, GetAddressDetailsQueryVariables>;diff --git a/packages/twenty-front/src/modules/front-components/components/FrontComponentApplicationTokenPairEffect.tsx b/packages/twenty-front/src/modules/front-components/components/FrontComponentApplicationTokenPairEffect.tsxindex 68539da1d3d..c80c716c2c8 100644--- a/packages/twenty-front/src/modules/front-components/components/FrontComponentApplicationTokenPairEffect.tsx+++ b/packages/twenty-front/src/modules/front-components/components/FrontComponentApplicationTokenPairEffect.tsx@@ -1,25 +1,50 @@-import { frontComponentApplicationTokenPairComponentState } from '@/front-components/states/frontComponentApplicationTokenPairComponentState';-import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';import { useEffect } from 'react';-import { type ApplicationTokenPair } from '~/generated-metadata/graphql';++import { useFrontComponentApplicationTokenPair } from '@/front-components/hooks/useFrontComponentApplicationTokenPair';+import { type FrontComponentApplicationTokenPair } from '@/front-components/types/FrontComponentApplicationTokenPair';type FrontComponentApplicationTokenPairEffectProps = {- frontComponentId: string;- applicationTokenPair: ApplicationTokenPair | null;+ applicationId: string;+ onApplicationTokenPairLoaded: (+ applicationTokenPair: FrontComponentApplicationTokenPair,+ ) => void;+ onApplicationTokenPairLoadFailed: (error: Error) => void;};export const FrontComponentApplicationTokenPairEffect = ({- frontComponentId,- applicationTokenPair,+ applicationId,+ onApplicationTokenPairLoaded,+ onApplicationTokenPairLoadFailed,}: FrontComponentApplicationTokenPairEffectProps) => {- const setFrontComponentApplicationTokenPair = useSetAtomComponentState(- frontComponentApplicationTokenPairComponentState,- frontComponentId,- );+ const { loadFrontComponentApplicationTokenPair } =+ useFrontComponentApplicationTokenPair();useEffect(() => {- setFrontComponentApplicationTokenPair(applicationTokenPair);- }, [applicationTokenPair, setFrontComponentApplicationTokenPair]);+ let isCancelled = false;++ loadFrontComponentApplicationTokenPair(applicationId)+ .then((applicationTokenPair) => {+ if (!isCancelled) {+ onApplicationTokenPairLoaded(applicationTokenPair);+ }+ })+ .catch((error: unknown) => {+ if (!isCancelled) {+ onApplicationTokenPairLoadFailed(+ error instanceof Error ? error : new Error(String(error)),+ );+ }+ });++ return () => {+ isCancelled = true;+ };+ }, [+ applicationId,+ loadFrontComponentApplicationTokenPair,+ onApplicationTokenPairLoaded,+ onApplicationTokenPairLoadFailed,+ ]);return null;};diff --git a/packages/twenty-front/src/modules/front-components/components/FrontComponentRenderer.tsx b/packages/twenty-front/src/modules/front-components/components/FrontComponentRenderer.tsxindex d643d0b7b10..41687c20534 100644--- a/packages/twenty-front/src/modules/front-components/components/FrontComponentRenderer.tsx+++ b/packages/twenty-front/src/modules/front-components/components/FrontComponentRenderer.tsx@@ -4,6 +4,7 @@ import { FrontComponentRendererProvider } from '@/front-components/components/Frimport { useFrontComponentExecutionContext } from '@/front-components/hooks/useFrontComponentExecutionContext';import { useOnApplicationSdkClientChecksumsUpdated } from '@/front-components/hooks/useOnApplicationSdkClientChecksumsUpdated';import { useOnFrontComponentUpdated } from '@/front-components/hooks/useOnFrontComponentUpdated';+import { type FrontComponentApplicationTokenPair } from '@/front-components/types/FrontComponentApplicationTokenPair';import { FrontComponentMediaSessionRegistrationEffect } from '@/front-components/media-session/components/FrontComponentMediaSessionRegistrationEffect';import { FrontComponentMediaPermissionModal } from '@/front-components/media-session/components/FrontComponentMediaPermissionModal';import { useFrontComponentMediaSession } from '@/front-components/media-session/hooks/useFrontComponentMediaSession';@@ -12,7 +13,7 @@ import { getSdkClientUrls } from '@/front-components/utils/getSdkClientUrls';import { useGetLogicFunctionHttpUrl } from '@/settings/logic-functions/hooks/useGetLogicFunctionHttpUrl';import { useQuery } from '@apollo/client/react';import { t } from '@lingui/core/macro';-import { type ReactNode, useCallback, useMemo } from 'react';+import { type ReactNode, useCallback, useMemo, useState } from 'react';import { FrontComponentRenderer as SharedFrontComponentRenderer } from 'twenty-front-component-renderer';import { type FrontComponentToolCall } from 'twenty-sdk/front-component';import { isDefined } from 'twenty-shared/utils';@@ -48,6 +49,7 @@ type FrontComponentRendererContentProps = {timelineActivityId?: string;toolCall?: FrontComponentToolCall;loadingFallback?: ReactNode;+ unavailableFallback?: ReactNode;};export const FrontComponentRenderer = ({@@ -87,6 +89,7 @@ export const FrontComponentRenderer = ({timelineActivityId={timelineActivityId}toolCall={toolCall}loadingFallback={loadingFallback}+ unavailableFallback={unavailableFallback}/>)}</>@@ -101,6 +104,7 @@ const FrontComponentRendererContent = ({timelineActivityId,toolCall,loadingFallback,+ unavailableFallback,}: FrontComponentRendererContentProps) => {const colorScheme = useThemeColorScheme();const { enqueueToast } = useToast();@@ -155,7 +159,23 @@ const FrontComponentRendererContent = ({[enqueueToast],);- const applicationTokenPair = frontComponent.applicationTokenPair ?? null;+ const [initialApplicationVariables] = useState(+ () => frontComponent.applicationVariables ?? undefined,+ );+ const [initialApplicationTokenPair, setInitialApplicationTokenPair] =+ useState<FrontComponentApplicationTokenPair | null>(null);+ const [applicationTokenPairLoadError, setApplicationTokenPairLoadError] =+ useState<Error | null>(null);++ const handleApplicationTokenPairLoaded = useCallback(+ (loadedApplicationTokenPair: FrontComponentApplicationTokenPair) => {+ setInitialApplicationTokenPair(+ (currentApplicationTokenPair) =>+ currentApplicationTokenPair ?? loadedApplicationTokenPair,+ );+ },+ [],+ );const { data: sdkClientChecksumsData, loading: sdkClientChecksumsLoading } =useQuery(GetApplicationSdkClientChecksumsDocument, {@@ -188,10 +208,9 @@ const FrontComponentRendererContent = ({checksum: frontComponent.builtComponentChecksum,});- const applicationVariables = frontComponent.applicationVariables ?? undefined;-const isSdkClientReady = !usesSdkClient || !sdkClientChecksumsLoading;- const isReadyToRender = isDefined(applicationTokenPair) && isSdkClientReady;+ const isReadyToRender =+ isDefined(initialApplicationTokenPair) && isSdkClientReady;return (<>@@ -211,17 +230,24 @@ const FrontComponentRendererContent = ({onStop={stopMediaSession}/><FrontComponentApplicationTokenPairEffect- frontComponentId={frontComponentId}- applicationTokenPair={applicationTokenPair}+ applicationId={applicationId}+ onApplicationTokenPairLoaded={handleApplicationTokenPairLoaded}+ onApplicationTokenPairLoadFailed={setApplicationTokenPairLoadError}+ />+ <FrontComponentLoadErrorToastEffect+ errorMessage={applicationTokenPairLoadError?.message}/>- {!isReadyToRender && loadingFallback}+ {isDefined(applicationTokenPairLoadError) && unavailableFallback}+ {!isDefined(applicationTokenPairLoadError) &&+ !isReadyToRender &&+ loadingFallback}{isReadyToRender && (<FrontComponentRendererProvider frontComponentId={frontComponentId}><SharedFrontComponentRenderercolorScheme={colorScheme}componentUrl={componentUrl}applicationAccessToken={- applicationTokenPair.applicationAccessToken.token+ initialApplicationTokenPair.applicationAccessToken.token}apiUrl={REACT_APP_SERVER_BASE_URL}functionsBaseUrl={functionsBaseUrl}@@ -232,7 +258,7 @@ const FrontComponentRendererContent = ({frontComponentHostCommunicationApi}mediaSessionHost={mediaSessionHost}- applicationVariables={applicationVariables}+ applicationVariables={initialApplicationVariables}storageNamespace={storageNamespace}onError={handleError}loadingFallback={loadingFallback}diff --git a/packages/twenty-front/src/modules/front-components/graphql/mutations/generateFrontComponentApplicationTokenPair.ts b/packages/twenty-front/src/modules/front-components/graphql/mutations/generateFrontComponentApplicationTokenPair.tsnew file mode 100644index 00000000000..7d3f3dbf2ed--- /dev/null+++ b/packages/twenty-front/src/modules/front-components/graphql/mutations/generateFrontComponentApplicationTokenPair.ts@@ -0,0 +1,16 @@+import gql from 'graphql-tag';++export const GENERATE_FRONT_COMPONENT_APPLICATION_TOKEN_PAIR = gql`+ mutation GenerateFrontComponentApplicationTokenPair($applicationId: UUID!) {+ generateFrontComponentApplicationTokenPair(applicationId: $applicationId) {+ applicationAccessToken {+ token+ expiresAt+ }+ applicationRefreshToken {+ token+ expiresAt+ }+ }+ }+`;diff --git a/packages/twenty-front/src/modules/front-components/graphql/queries/findOneFrontComponent.ts b/packages/twenty-front/src/modules/front-components/graphql/queries/findOneFrontComponent.tsindex c3b018c8d43..462ad9049e3 100644--- a/packages/twenty-front/src/modules/front-components/graphql/queries/findOneFrontComponent.ts+++ b/packages/twenty-front/src/modules/front-components/graphql/queries/findOneFrontComponent.ts@@ -13,16 +13,6 @@ export const FIND_ONE_FRONT_COMPONENT = gql`usesSdkClientfrontComponentSharedDependenciesChecksumapplicationVariables- applicationTokenPair {- applicationAccessToken {- token- expiresAt- }- applicationRefreshToken {- token- expiresAt- }- }}}`;diff --git a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentApplicationTokenPair.test.tsx b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentApplicationTokenPair.test.tsxnew file mode 100644index 00000000000..6778a8ce2e5--- /dev/null+++ b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentApplicationTokenPair.test.tsx@@ -0,0 +1,345 @@+import { CombinedGraphQLErrors } from '@apollo/client/errors';+import { act, renderHook } from '@testing-library/react';+import { createStore, Provider as JotaiProvider } from 'jotai';+import { type ReactNode } from 'react';++import { useFrontComponentApplicationTokenPair } from '@/front-components/hooks/useFrontComponentApplicationTokenPair';+import { frontComponentApplicationTokenPairFamilyState } from '@/front-components/states/frontComponentApplicationTokenPairFamilyState';+import { type FrontComponentApplicationTokenPair } from '@/front-components/types/FrontComponentApplicationTokenPair';+import {+ type ApplicationTokenPair,+ GenerateFrontComponentApplicationTokenPairDocument,+ RenewApplicationTokenDocument,+} from '~/generated-metadata/graphql';++const mockMutate = jest.fn();++jest.mock('@apollo/client/react', () => ({+ ...jest.requireActual('@apollo/client/react'),+ useApolloClient: () => ({+ mutate: mockMutate,+ }),+}));++const APPLICATION_ID = 'application-test-id';+const OTHER_APPLICATION_ID = 'other-application-test-id';++const getDateInOneHour = () =>+ new Date(Date.now() + 60 * 60 * 1000).toISOString();+const getDateInOneMinute = () => new Date(Date.now() + 60 * 1000).toISOString();+const getTimestampOneMinuteAgo = () => Date.now() - 60 * 1000;++const buildTokenPair = ({+ accessToken,+ refreshToken,+ accessTokenExpiresAt = getDateInOneHour(),+}: {+ accessToken: string;+ refreshToken: string;+ accessTokenExpiresAt?: string;+}): ApplicationTokenPair => ({+ __typename: 'ApplicationTokenPair',+ applicationAccessToken: {+ __typename: 'AuthToken',+ token: accessToken,+ expiresAt: accessTokenExpiresAt,+ },+ applicationRefreshToken: {+ __typename: 'AuthToken',+ token: refreshToken,+ expiresAt: getDateInOneHour(),+ },+});++const buildStoredTokenPair = ({+ accessTokenExpiresAt,+ obtainedAt = getTimestampOneMinuteAgo(),+}: {+ accessTokenExpiresAt?: string;+ obtainedAt?: number;+} = {}): FrontComponentApplicationTokenPair => ({+ ...buildTokenPair({+ accessToken: 'stored-access',+ refreshToken: 'stored-refresh',+ accessTokenExpiresAt,+ }),+ obtainedAt,+});++const mockGeneratedTokenPair = (accessToken = 'generated-access') => ({+ data: {+ generateFrontComponentApplicationTokenPair: buildTokenPair({+ accessToken,+ refreshToken: 'generated-refresh',+ }),+ },+});++const mockRenewedTokenPair = () => ({+ data: {+ renewApplicationToken: buildTokenPair({+ accessToken: 'renewed-access',+ refreshToken: 'renewed-refresh',+ }),+ },+});++const getMutationCalls = (mutation: unknown) =>+ mockMutate.mock.calls.filter(([options]) => options.mutation === mutation);++const renderUseFrontComponentApplicationTokenPair = (+ store: ReturnType<typeof createStore>,+) =>+ renderHook(() => useFrontComponentApplicationTokenPair(), {+ wrapper: ({ children }: { children: ReactNode }) => (+ <JotaiProvider store={store}>{children}</JotaiProvider>+ ),+ });++const getStoredTokenPair = (store: ReturnType<typeof createStore>) =>+ store.get(+ frontComponentApplicationTokenPairFamilyState.atomFamily(APPLICATION_ID),+ );++const setStoredTokenPair = (+ store: ReturnType<typeof createStore>,+ applicationTokenPair: FrontComponentApplicationTokenPair,+) =>+ store.set(+ frontComponentApplicationTokenPairFamilyState.atomFamily(APPLICATION_ID),+ applicationTokenPair,+ );++describe('useFrontComponentApplicationTokenPair', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe('loadFrontComponentApplicationTokenPair', () => {+ it('should generate a single token pair for concurrent loads of the same application', async () => {+ const store = createStore();+ mockMutate.mockResolvedValue(mockGeneratedTokenPair());++ const { result } = renderUseFrontComponentApplicationTokenPair(store);++ let applicationTokenPairs: FrontComponentApplicationTokenPair[] = [];++ await act(async () => {+ applicationTokenPairs = await Promise.all([+ result.current.loadFrontComponentApplicationTokenPair(APPLICATION_ID),+ result.current.loadFrontComponentApplicationTokenPair(APPLICATION_ID),+ result.current.loadFrontComponentApplicationTokenPair(APPLICATION_ID),+ ]);+ });++ expect(mockMutate).toHaveBeenCalledTimes(1);+ expect(mockMutate).toHaveBeenCalledWith(+ expect.objectContaining({+ mutation: GenerateFrontComponentApplicationTokenPairDocument,+ variables: { applicationId: APPLICATION_ID },+ }),+ );+ expect(+ applicationTokenPairs.map(+ (applicationTokenPair) =>+ applicationTokenPair.applicationAccessToken.token,+ ),+ ).toEqual(['generated-access', 'generated-access', 'generated-access']);+ expect(getStoredTokenPair(store)?.applicationAccessToken.token).toBe(+ 'generated-access',+ );+ });++ it('should generate one token pair per application', async () => {+ const store = createStore();+ mockMutate.mockResolvedValue(mockGeneratedTokenPair());++ const { result } = renderUseFrontComponentApplicationTokenPair(store);++ await act(async () => {+ await Promise.all([+ result.current.loadFrontComponentApplicationTokenPair(APPLICATION_ID),+ result.current.loadFrontComponentApplicationTokenPair(+ OTHER_APPLICATION_ID,+ ),+ ]);+ });++ expect(+ getMutationCalls(+ GenerateFrontComponentApplicationTokenPairDocument,+ ).map(([options]) => options.variables.applicationId),+ ).toEqual([APPLICATION_ID, OTHER_APPLICATION_ID]);+ });++ it('should reuse the stored token pair when its access token is still valid', async () => {+ const store = createStore();+ const storedTokenPair = buildStoredTokenPair();+ setStoredTokenPair(store, storedTokenPair);++ const { result } = renderUseFrontComponentApplicationTokenPair(store);++ let applicationTokenPair: FrontComponentApplicationTokenPair | undefined;++ await act(async () => {+ applicationTokenPair =+ await result.current.loadFrontComponentApplicationTokenPair(+ APPLICATION_ID,+ );+ });++ expect(applicationTokenPair).toBe(storedTokenPair);+ expect(mockMutate).not.toHaveBeenCalled();+ });++ it('should renew the stored token pair when its access token is about to expire', async () => {+ const store = createStore();+ setStoredTokenPair(+ store,+ buildStoredTokenPair({ accessTokenExpiresAt: getDateInOneMinute() }),+ );+ mockMutate.mockResolvedValue(mockRenewedTokenPair());++ const { result } = renderUseFrontComponentApplicationTokenPair(store);++ let applicationTokenPair: FrontComponentApplicationTokenPair | undefined;++ await act(async () => {+ applicationTokenPair =+ await result.current.loadFrontComponentApplicationTokenPair(+ APPLICATION_ID,+ );+ });++ expect(mockMutate).toHaveBeenCalledTimes(1);+ expect(mockMutate).toHaveBeenCalledWith(+ expect.objectContaining({+ mutation: RenewApplicationTokenDocument,+ variables: { applicationRefreshToken: 'stored-refresh' },+ }),+ );+ expect(applicationTokenPair?.applicationAccessToken.token).toBe(+ 'renewed-access',+ );+ });+ });++ describe('requestApplicationAccessTokenRefresh', () => {+ it('should renew once for concurrent refresh requests of the same application', async () => {+ const store = createStore();+ setStoredTokenPair(store, buildStoredTokenPair());+ mockMutate.mockResolvedValue(mockRenewedTokenPair());++ const { result } = renderUseFrontComponentApplicationTokenPair(store);++ let accessTokens: string[] = [];++ await act(async () => {+ accessTokens = await Promise.all(+ Array.from({ length: 40 }, () =>+ result.current.requestApplicationAccessTokenRefresh(APPLICATION_ID),+ ),+ );+ });++ expect(mockMutate).toHaveBeenCalledTimes(1);+ expect(new Set(accessTokens)).toEqual(new Set(['renewed-access']));+ expect(getStoredTokenPair(store)?.applicationAccessToken.token).toBe(+ 'renewed-access',+ );+ });++ it('should return the stored access token when it was just renewed', async () => {+ const store = createStore();+ setStoredTokenPair(+ store,+ buildStoredTokenPair({ obtainedAt: Date.now() }),+ );++ const { result } = renderUseFrontComponentApplicationTokenPair(store);++ let accessToken: string | undefined;++ await act(async () => {+ accessToken =+ await result.current.requestApplicationAccessTokenRefresh(+ APPLICATION_ID,+ );+ });++ expect(accessToken).toBe('stored-access');+ expect(mockMutate).not.toHaveBeenCalled();+ });++ it('should generate a new token pair when the refresh token is rejected', async () => {+ const store = createStore();+ setStoredTokenPair(store, buildStoredTokenPair());+ mockMutate.mockImplementation(async ({ mutation }) => {+ if (mutation === RenewApplicationTokenDocument) {+ throw new CombinedGraphQLErrors({+ errors: [+ {+ message: 'Refresh token expired',+ extensions: {+ subCode: 'APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED',+ },+ },+ ],+ });+ }++ return mockGeneratedTokenPair('regenerated-access');+ });++ const { result } = renderUseFrontComponentApplicationTokenPair(store);++ let accessTokens: string[] = [];++ await act(async () => {+ accessTokens = await Promise.all([+ result.current.requestApplicationAccessTokenRefresh(APPLICATION_ID),+ result.current.requestApplicationAccessTokenRefresh(APPLICATION_ID),+ ]);+ });++ expect(accessTokens).toEqual([+ 'regenerated-access',+ 'regenerated-access',+ ]);+ expect(getMutationCalls(RenewApplicationTokenDocument)).toHaveLength(1);+ expect(+ getMutationCalls(GenerateFrontComponentApplicationTokenPairDocument),+ ).toHaveLength(1);+ });++ it('should re-throw other errors and retry on the next request', async () => {+ const store = createStore();+ setStoredTokenPair(store, buildStoredTokenPair());+ mockMutate+ .mockRejectedValueOnce(new Error('Network failure'))+ .mockResolvedValueOnce(mockRenewedTokenPair());++ const { result } = renderUseFrontComponentApplicationTokenPair(store);++ await expect(+ result.current.requestApplicationAccessTokenRefresh(APPLICATION_ID),+ ).rejects.toThrow('Network failure');++ expect(+ getMutationCalls(GenerateFrontComponentApplicationTokenPairDocument),+ ).toHaveLength(0);++ let accessToken: string | undefined;++ await act(async () => {+ accessToken =+ await result.current.requestApplicationAccessTokenRefresh(+ APPLICATION_ID,+ );+ });++ expect(accessToken).toBe('renewed-access');+ expect(mockMutate).toHaveBeenCalledTimes(2);+ });+ });+});diff --git a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsxindex 210543acd2c..8b492440888 100644--- a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx+++ b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx@@ -33,7 +33,7 @@ jest.mock('@/object-metadata/utils/getFieldMetadataItemById', () => ({}));const mockNavigateApp = jest.fn();-const mockRequestAccessTokenRefresh = jest.fn();+const mockRequestApplicationAccessTokenRefresh = jest.fn();const mockOpenConfirmationModal = jest.fn();const mockNavigateSidePanel = jest.fn();const mockOpenRecordInSidePanel = jest.fn();@@ -61,11 +61,15 @@ jest.mock('~/hooks/useNavigateApp', () => ({useNavigateApp: () => mockNavigateApp,}));-jest.mock('@/front-components/hooks/useRequestApplicationTokenRefresh', () => ({- useRequestApplicationTokenRefresh: () => ({- requestAccessTokenRefresh: mockRequestAccessTokenRefresh,+jest.mock(+ '@/front-components/hooks/useFrontComponentApplicationTokenPair',+ () => ({+ useFrontComponentApplicationTokenPair: () => ({+ requestApplicationAccessTokenRefresh:+ mockRequestApplicationAccessTokenRefresh,+ }),}),-}));+);jest.mock('@/command-menu-item/confirmation-modal/hooks/useCommandMenuConfirmationModal',@@ -1000,6 +1004,30 @@ describe('useFrontComponentExecutionContext', () => {});});+ describe('requestAccessTokenRefresh', () => {+ it('should refresh the access token of the front component application', async () => {+ mockRequestApplicationAccessTokenRefresh.mockResolvedValue(+ 'renewed-access-token',+ );++ const { result } = renderUseFrontComponentExecutionContext({+ frontComponentId: FRONT_COMPONENT_ID,+ });++ let accessToken: string | undefined;++ await act(async () => {+ accessToken =+ await result.current.frontComponentHostCommunicationApi.requestAccessTokenRefresh();+ });++ expect(accessToken).toBe('renewed-access-token');+ expect(mockRequestApplicationAccessTokenRefresh).toHaveBeenCalledWith(+ APPLICATION_ID,+ );+ });+ });+describe('updateProgress', () => {it('should set clamped progress when commandMenuItemId is provided', async () => {const { result } = renderUseFrontComponentExecutionContext({diff --git a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useRequestApplicationTokenRefresh.test.tsx b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useRequestApplicationTokenRefresh.test.tsxdeleted file mode 100644index 356b769d5fa..00000000000--- a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useRequestApplicationTokenRefresh.test.tsx+++ /dev/null@@ -1,237 +0,0 @@-import { CombinedGraphQLErrors } from '@apollo/client/errors';-import { act, renderHook } from '@testing-library/react';-import { atom, createStore, Provider as JotaiProvider } from 'jotai';-import { type ReactNode } from 'react';--import { useRequestApplicationTokenRefresh } from '@/front-components/hooks/useRequestApplicationTokenRefresh';-import { type ApplicationTokenPair } from '~/generated-metadata/graphql';--const mockQuery = jest.fn();-const mockMutate = jest.fn();--jest.mock('@apollo/client/react', () => ({- ...jest.requireActual('@apollo/client/react'),- useApolloClient: () => ({- query: mockQuery,- mutate: mockMutate,- }),-}));--const tokenPairAtom = atom<ApplicationTokenPair | null>(null);--jest.mock(- '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState',- () => ({- useAtomComponentStateCallbackState: () => tokenPairAtom,- }),-);--const FRONT_COMPONENT_ID = 'fc-test-id';--const buildTokenPair = (- accessToken = 'access-token-1',- refreshToken = 'refresh-token-1',-): ApplicationTokenPair => ({- __typename: 'ApplicationTokenPair',- applicationAccessToken: {- __typename: 'AuthToken',- token: accessToken,- expiresAt: '2099-01-01T00:00:00.000Z',- },- applicationRefreshToken: {- __typename: 'AuthToken',- token: refreshToken,- expiresAt: '2099-01-01T00:00:00.000Z',- },-});--const getWrapper =- (store: ReturnType<typeof createStore>) =>- ({ children }: { children: ReactNode }) => (- <JotaiProvider store={store}>{children}</JotaiProvider>- );--describe('useRequestApplicationTokenRefresh', () => {- beforeEach(() => {- jest.clearAllMocks();- });-- it('should throw when application token pair is not initialized in the store', async () => {- const store = createStore();- const wrapper = getWrapper(store);-- const { result } = renderHook(- () =>- useRequestApplicationTokenRefresh({- frontComponentId: FRONT_COMPONENT_ID,- }),- { wrapper },- );-- await expect(- act(() => result.current.requestAccessTokenRefresh()),- ).rejects.toThrow(- 'Application token pair must be initialized before requesting a refresh',- );- });-- it('should renew token via mutation and update the store', async () => {- const store = createStore();- const wrapper = getWrapper(store);-- const initialTokenPair = buildTokenPair('old-access', 'old-refresh');- store.set(tokenPairAtom, initialTokenPair);-- const renewedTokenPair = buildTokenPair(- 'new-access-token',- 'new-refresh-token',- );-- mockMutate.mockResolvedValue({- data: { renewApplicationToken: renewedTokenPair },- });-- const { result } = renderHook(- () =>- useRequestApplicationTokenRefresh({- frontComponentId: FRONT_COMPONENT_ID,- }),- { wrapper },- );-- let accessToken: string | undefined;-- await act(async () => {- accessToken = await result.current.requestAccessTokenRefresh();- });-- expect(accessToken).toBe('new-access-token');- expect(store.get(tokenPairAtom)).toEqual(renewedTokenPair);- expect(mockMutate).toHaveBeenCalledWith(- expect.objectContaining({- variables: {- applicationRefreshToken: 'old-refresh',- },- }),- );- });-- it('should fallback to refetching front component when refresh token is expired', async () => {- const store = createStore();- const wrapper = getWrapper(store);-- const initialTokenPair = buildTokenPair('old-access', 'expired-refresh');- store.set(tokenPairAtom, initialTokenPair);-- const expiredError = new CombinedGraphQLErrors({- errors: [- {- message: 'Refresh token expired',- extensions: {- subCode: 'APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED',- },- },- ],- });-- mockMutate.mockRejectedValue(expiredError);-- const refetchedTokenPair = buildTokenPair(- 'refetched-access',- 'refetched-refresh',- );-- mockQuery.mockResolvedValue({- data: {- frontComponent: {- applicationTokenPair: refetchedTokenPair,- },- },- });-- const { result } = renderHook(- () =>- useRequestApplicationTokenRefresh({- frontComponentId: FRONT_COMPONENT_ID,- }),- { wrapper },- );-- let accessToken: string | undefined;-- await act(async () => {- accessToken = await result.current.requestAccessTokenRefresh();- });-- expect(accessToken).toBe('refetched-access');- expect(store.get(tokenPairAtom)).toEqual(refetchedTokenPair);- expect(mockQuery).toHaveBeenCalledWith(- expect.objectContaining({- variables: { id: FRONT_COMPONENT_ID },- fetchPolicy: 'network-only',- }),- );- });-- it('should re-throw non-token-expiry errors from the mutation', async () => {- const store = createStore();- const wrapper = getWrapper(store);-- const initialTokenPair = buildTokenPair();- store.set(tokenPairAtom, initialTokenPair);-- const networkError = new Error('Network failure');- mockMutate.mockRejectedValue(networkError);-- const { result } = renderHook(- () =>- useRequestApplicationTokenRefresh({- frontComponentId: FRONT_COMPONENT_ID,- }),- { wrapper },- );-- await expect(- act(() => result.current.requestAccessTokenRefresh()),- ).rejects.toThrow('Network failure');-- expect(mockQuery).not.toHaveBeenCalled();- });-- it('should throw when refetch returns no token pair', async () => {- const store = createStore();- const wrapper = getWrapper(store);-- const initialTokenPair = buildTokenPair('old-access', 'expired-refresh');- store.set(tokenPairAtom, initialTokenPair);-- const expiredError = new CombinedGraphQLErrors({- errors: [- {- message: 'Refresh token expired',- extensions: {- subCode: 'APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED',- },- },- ],- });-- mockMutate.mockRejectedValue(expiredError);-- mockQuery.mockResolvedValue({- data: { frontComponent: { applicationTokenPair: null } },- });-- const { result } = renderHook(- () =>- useRequestApplicationTokenRefresh({- frontComponentId: FRONT_COMPONENT_ID,- }),- { wrapper },- );-- await expect(- act(() => result.current.requestAccessTokenRefresh()),- ).rejects.toThrow('Failed to refetch application token pair');- });-});diff --git a/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentApplicationTokenPair.ts b/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentApplicationTokenPair.tsnew file mode 100644index 00000000000..9cb505ba085--- /dev/null+++ b/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentApplicationTokenPair.ts@@ -0,0 +1,211 @@+import { CombinedGraphQLErrors } from '@apollo/client/errors';+import { useApolloClient } from '@apollo/client/react';+import { type GraphQLFormattedError } from 'graphql';+import { useStore } from 'jotai';+import { useCallback } from 'react';+import { isDefined } from 'twenty-shared/utils';++import { frontComponentApplicationTokenPairFamilyState } from '@/front-components/states/frontComponentApplicationTokenPairFamilyState';+import { pendingFrontComponentApplicationTokenPairPromiseFamilyState } from '@/front-components/states/pendingFrontComponentApplicationTokenPairPromiseFamilyState';+import { type FrontComponentApplicationTokenPair } from '@/front-components/types/FrontComponentApplicationTokenPair';+import {+ GenerateFrontComponentApplicationTokenPairDocument,+ RenewApplicationTokenDocument,+} from '~/generated-metadata/graphql';+import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';++const APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED_SUB_CODE =+ 'APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED';++const MINIMUM_ACCESS_TOKEN_REMAINING_VALIDITY_MS = 5 * 60 * 1000;++const RECENT_TOKEN_PAIR_RENEWAL_WINDOW_MS = 30 * 1000;++const hasApplicationRefreshTokenInvalidOrExpiredSubCode = (+ errors: ReadonlyArray<GraphQLFormattedError>,+): boolean =>+ errors.some((error) =>+ isGraphqlErrorOfType(+ error,+ APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED_SUB_CODE,+ ),+ );++const hasEnoughAccessTokenValidityLeft = (+ applicationTokenPair: FrontComponentApplicationTokenPair,+): boolean =>+ new Date(applicationTokenPair.applicationAccessToken.expiresAt).getTime() -+ Date.now() >+ MINIMUM_ACCESS_TOKEN_REMAINING_VALIDITY_MS;++const wasRecentlyObtained = (+ applicationTokenPair: FrontComponentApplicationTokenPair,+): boolean =>+ Date.now() - applicationTokenPair.obtainedAt <+ RECENT_TOKEN_PAIR_RENEWAL_WINDOW_MS;++export const useFrontComponentApplicationTokenPair = () => {+ const apolloClient = useApolloClient();+ const store = useStore();++ const generateApplicationTokenPair = useCallback(+ async (+ applicationId: string,+ ): Promise<FrontComponentApplicationTokenPair> => {+ const result = await apolloClient.mutate({+ mutation: GenerateFrontComponentApplicationTokenPairDocument,+ variables: { applicationId },+ });++ const generatedApplicationTokenPair =+ result.data?.generateFrontComponentApplicationTokenPair;++ if (!isDefined(generatedApplicationTokenPair)) {+ throw new Error(+ 'Failed to generate front component application token pair',+ );+ }++ return { ...generatedApplicationTokenPair, obtainedAt: Date.now() };+ },+ [apolloClient],+ );++ const renewApplicationTokenPair = useCallback(+ async ({+ applicationId,+ applicationTokenPair,+ }: {+ applicationId: string;+ applicationTokenPair: FrontComponentApplicationTokenPair;+ }): Promise<FrontComponentApplicationTokenPair> => {+ try {+ const result = await apolloClient.mutate({+ mutation: RenewApplicationTokenDocument,+ variables: {+ applicationRefreshToken:+ applicationTokenPair.applicationRefreshToken.token,+ },+ });++ const renewedApplicationTokenPair = result.data?.renewApplicationToken;++ if (!isDefined(renewedApplicationTokenPair)) {+ throw new Error('Failed to renew application token');+ }++ return { ...renewedApplicationTokenPair, obtainedAt: Date.now() };+ } catch (error) {+ if (+ CombinedGraphQLErrors.is(error) &&+ hasApplicationRefreshTokenInvalidOrExpiredSubCode(error.errors)+ ) {+ return await generateApplicationTokenPair(applicationId);+ }++ throw error;+ }+ },+ [apolloClient, generateApplicationTokenPair],+ );++ const renewOrGenerateApplicationTokenPairOncePerApplication = useCallback(+ (applicationId: string): Promise<FrontComponentApplicationTokenPair> => {+ const pendingApplicationTokenPairPromiseAtom =+ pendingFrontComponentApplicationTokenPairPromiseFamilyState.atomFamily(+ applicationId,+ );++ const pendingApplicationTokenPairPromise = store.get(+ pendingApplicationTokenPairPromiseAtom,+ );++ if (isDefined(pendingApplicationTokenPairPromise)) {+ return pendingApplicationTokenPairPromise;+ }++ const applicationTokenPairAtom =+ frontComponentApplicationTokenPairFamilyState.atomFamily(applicationId);++ const currentApplicationTokenPair = store.get(applicationTokenPairAtom);++ const renewOrGenerateApplicationTokenPair =+ async (): Promise<FrontComponentApplicationTokenPair> => {+ try {+ const applicationTokenPair = isDefined(currentApplicationTokenPair)+ ? await renewApplicationTokenPair({+ applicationId,+ applicationTokenPair: currentApplicationTokenPair,+ })+ : await generateApplicationTokenPair(applicationId);++ store.set(applicationTokenPairAtom, applicationTokenPair);++ return applicationTokenPair;+ } finally {+ store.set(pendingApplicationTokenPairPromiseAtom, null);+ }+ };++ const applicationTokenPairPromise = renewOrGenerateApplicationTokenPair();++ store.set(+ pendingApplicationTokenPairPromiseAtom,+ applicationTokenPairPromise,+ );++ return applicationTokenPairPromise;+ },+ [generateApplicationTokenPair, renewApplicationTokenPair, store],+ );++ const loadFrontComponentApplicationTokenPair = useCallback(+ async (+ applicationId: string,+ ): Promise<FrontComponentApplicationTokenPair> => {+ const applicationTokenPair = store.get(+ frontComponentApplicationTokenPairFamilyState.atomFamily(applicationId),+ );++ if (+ isDefined(applicationTokenPair) &&+ hasEnoughAccessTokenValidityLeft(applicationTokenPair)+ ) {+ return applicationTokenPair;+ }++ return await renewOrGenerateApplicationTokenPairOncePerApplication(+ applicationId,+ );+ },+ [renewOrGenerateApplicationTokenPairOncePerApplication, store],+ );++ const requestApplicationAccessTokenRefresh = useCallback(+ async (applicationId: string): Promise<string> => {+ const applicationTokenPair = store.get(+ frontComponentApplicationTokenPairFamilyState.atomFamily(applicationId),+ );++ if (+ isDefined(applicationTokenPair) &&+ wasRecentlyObtained(applicationTokenPair)+ ) {+ return applicationTokenPair.applicationAccessToken.token;+ }++ const refreshedApplicationTokenPair =+ await renewOrGenerateApplicationTokenPairOncePerApplication(+ applicationId,+ );++ return refreshedApplicationTokenPair.applicationAccessToken.token;+ },+ [renewOrGenerateApplicationTokenPairOncePerApplication, store],+ );++ return {+ loadFrontComponentApplicationTokenPair,+ requestApplicationAccessTokenRefresh,+ };+};diff --git a/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts b/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.tsindex 8befc8f362b..cf909cc648c 100644--- a/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts+++ b/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts@@ -33,7 +33,7 @@ import { commandMenuItemProgressFamilyState } from '@/command-menu-item/states/cimport { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';import { contextStoreRecordShowParentViewComponentState } from '@/context-store/states/contextStoreRecordShowParentViewComponentState';import { useDirectFileUpload } from '@/file/hooks/useDirectFileUpload';-import { useRequestApplicationTokenRefresh } from '@/front-components/hooks/useRequestApplicationTokenRefresh';+import { useFrontComponentApplicationTokenPair } from '@/front-components/hooks/useFrontComponentApplicationTokenPair';import { getMediaFileExtension } from '@/front-components/media-session/utils/getMediaFileExtension';import { setRecordPageActiveTabId } from '@/page-layout/utils/setRecordPageActiveTabId';import { useNavigateSidePanel } from '@/side-panel/hooks/useNavigateSidePanel';@@ -142,9 +142,8 @@ export const useFrontComponentExecutionContext = ({const currentUser = useAtomStateValue(currentUserState);const navigateApp = useNavigateApp();const store = useStore();- const { requestAccessTokenRefresh } = useRequestApplicationTokenRefresh({- frontComponentId,- });+ const { requestApplicationAccessTokenRefresh } =+ useFrontComponentApplicationTokenPair();const { openConfirmationModal } = useCommandMenuConfirmationModal();const { openAskAiPageWithPreprompt } = useOpenAskAiPageWithPreprompt();const { navigateSidePanel } = useNavigateSidePanel();@@ -598,6 +597,9 @@ export const useFrontComponentExecutionContext = ({});};+ const requestAccessTokenRefresh: FrontComponentHostCommunicationApi['requestAccessTokenRefresh'] =+ () => requestApplicationAccessTokenRefresh(applicationId);+const frontComponentHostCommunicationApi: FrontComponentHostCommunicationApi ={navigate,diff --git a/packages/twenty-front/src/modules/front-components/hooks/useRequestApplicationTokenRefresh.ts b/packages/twenty-front/src/modules/front-components/hooks/useRequestApplicationTokenRefresh.tsdeleted file mode 100644index 62611d381b2..00000000000--- a/packages/twenty-front/src/modules/front-components/hooks/useRequestApplicationTokenRefresh.ts+++ /dev/null@@ -1,117 +0,0 @@-import { useApolloClient } from '@apollo/client/react';-import { CombinedGraphQLErrors } from '@apollo/client/errors';-import { type GraphQLFormattedError } from 'graphql';-import { useCallback } from 'react';-import { useStore } from 'jotai';-import { isDefined } from 'twenty-shared/utils';--import { frontComponentApplicationTokenPairComponentState } from '@/front-components/states/frontComponentApplicationTokenPairComponentState';-import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState';-import {- FindOneFrontComponentDocument,- type FindOneFrontComponentQuery,- type FindOneFrontComponentQueryVariables,- RenewApplicationTokenDocument,- type RenewApplicationTokenMutation,- type RenewApplicationTokenMutationVariables,-} from '~/generated-metadata/graphql';-import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';--const APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED_SUB_CODE =- 'APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED';--const hasApplicationRefreshTokenInvalidOrExpiredSubCode = (- errors: ReadonlyArray<GraphQLFormattedError>,-): boolean =>- errors.some((error) =>- isGraphqlErrorOfType(- error,- APPLICATION_REFRESH_TOKEN_INVALID_OR_EXPIRED_SUB_CODE,- ),- );--type UseRequestApplicationTokenRefreshArgs = {- frontComponentId: string;-};--export const useRequestApplicationTokenRefresh = ({- frontComponentId,-}: UseRequestApplicationTokenRefreshArgs) => {- const apolloClient = useApolloClient();- const store = useStore();-- const applicationTokenPairAtom = useAtomComponentStateCallbackState(- frontComponentApplicationTokenPairComponentState,- frontComponentId,- );-- const requestAccessTokenRefresh = useCallback(async (): Promise<string> => {- const refetchFrontComponentForNewTokenPair = async (): Promise<string> => {- const result = await apolloClient.query<- FindOneFrontComponentQuery,- FindOneFrontComponentQueryVariables- >({- query: FindOneFrontComponentDocument,- variables: { id: frontComponentId },- fetchPolicy: 'network-only',- });-- const newTokenPair = result.data?.frontComponent?.applicationTokenPair;-- if (!isDefined(newTokenPair)) {- throw new Error('Failed to refetch application token pair');- }-- store.set(applicationTokenPairAtom, newTokenPair);-- return newTokenPair.applicationAccessToken.token;- };-- const applicationTokenPair = store.get(applicationTokenPairAtom);-- if (!isDefined(applicationTokenPair)) {- throw new Error(- 'Application token pair must be initialized before requesting a refresh. Ensure the front component has loaded its token pair before invoking refresh.',- );- }-- // First try renewing via the refresh token (fast path).- // If the refresh token itself is expired, fall back to refetching- // the front component which issues a fresh token pair server-side.- try {- // With the default errorPolicy ('none'), client.mutate() rejects on- // GraphQL/network errors, so error handling happens in the catch block.- const renewResult = await apolloClient.mutate<- RenewApplicationTokenMutation,- RenewApplicationTokenMutationVariables- >({- mutation: RenewApplicationTokenDocument,- variables: {- applicationRefreshToken:- applicationTokenPair.applicationRefreshToken.token,- },- });-- const renewedTokenPair = renewResult.data?.renewApplicationToken;-- if (!isDefined(renewedTokenPair)) {- throw new Error('Failed to renew application token');- }-- store.set(applicationTokenPairAtom, renewedTokenPair);-- return renewedTokenPair.applicationAccessToken.token;- } catch (error) {- if (- CombinedGraphQLErrors.is(error) &&- hasApplicationRefreshTokenInvalidOrExpiredSubCode(error.errors)- ) {- return await refetchFrontComponentForNewTokenPair();- }-- throw error;- }- }, [apolloClient, applicationTokenPairAtom, frontComponentId, store]);-- return { requestAccessTokenRefresh };-};diff --git a/packages/twenty-front/src/modules/front-components/states/frontComponentApplicationTokenPairComponentState.ts b/packages/twenty-front/src/modules/front-components/states/frontComponentApplicationTokenPairComponentState.tsdeleted file mode 100644index 4e2b8288864..00000000000--- a/packages/twenty-front/src/modules/front-components/states/frontComponentApplicationTokenPairComponentState.ts+++ /dev/null@@ -1,10 +0,0 @@-import { FrontComponentInstanceContext } from '@/front-components/states/contexts/FrontComponentInstanceContext';-import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/createAtomComponentState';-import { type ApplicationTokenPair } from '~/generated-metadata/graphql';--export const frontComponentApplicationTokenPairComponentState =- createAtomComponentState<ApplicationTokenPair | null>({- key: 'frontComponentApplicationTokenPairComponentState',- defaultValue: null,- componentInstanceContext: FrontComponentInstanceContext,- });diff --git a/packages/twenty-front/src/modules/front-components/states/frontComponentApplicationTokenPairFamilyState.ts b/packages/twenty-front/src/modules/front-components/states/frontComponentApplicationTokenPairFamilyState.tsnew file mode 100644index 00000000000..73de09e5edd--- /dev/null+++ b/packages/twenty-front/src/modules/front-components/states/frontComponentApplicationTokenPairFamilyState.ts@@ -0,0 +1,8 @@+import { type FrontComponentApplicationTokenPair } from '@/front-components/types/FrontComponentApplicationTokenPair';+import { createAtomFamilyState } from '@/ui/utilities/state/jotai/utils/createAtomFamilyState';++export const frontComponentApplicationTokenPairFamilyState =+ createAtomFamilyState<FrontComponentApplicationTokenPair | null, string>({+ key: 'frontComponentApplicationTokenPairFamilyState',+ defaultValue: null,+ });diff --git a/packages/twenty-front/src/modules/front-components/states/pendingFrontComponentApplicationTokenPairPromiseFamilyState.ts b/packages/twenty-front/src/modules/front-components/states/pendingFrontComponentApplicationTokenPairPromiseFamilyState.tsnew file mode 100644index 00000000000..82e525a19bf--- /dev/null+++ b/packages/twenty-front/src/modules/front-components/states/pendingFrontComponentApplicationTokenPairPromiseFamilyState.ts@@ -0,0 +1,11 @@+import { type FrontComponentApplicationTokenPair } from '@/front-components/types/FrontComponentApplicationTokenPair';+import { createAtomFamilyState } from '@/ui/utilities/state/jotai/utils/createAtomFamilyState';++export const pendingFrontComponentApplicationTokenPairPromiseFamilyState =+ createAtomFamilyState<+ Promise<FrontComponentApplicationTokenPair> | null,+ string+ >({+ key: 'pendingFrontComponentApplicationTokenPairPromiseFamilyState',+ defaultValue: null,+ });diff --git a/packages/twenty-front/src/modules/front-components/types/FrontComponentApplicationTokenPair.ts b/packages/twenty-front/src/modules/front-components/types/FrontComponentApplicationTokenPair.tsnew file mode 100644index 00000000000..04441327c62--- /dev/null+++ b/packages/twenty-front/src/modules/front-components/types/FrontComponentApplicationTokenPair.ts@@ -0,0 +1,5 @@+import { type ApplicationTokenPair } from '~/generated-metadata/graphql';++export type FrontComponentApplicationTokenPair = ApplicationTokenPair & {+ obtainedAt: number;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/front-component/dtos/front-component.dto.ts b/packages/twenty-server/src/engine/metadata-modules/front-component/dtos/front-component.dto.tsindex 9cc7c93f2c8..0aa5c8031a1 100644--- a/packages/twenty-server/src/engine/metadata-modules/front-component/dtos/front-component.dto.ts+++ b/packages/twenty-server/src/engine/metadata-modules/front-component/dtos/front-component.dto.ts@@ -73,7 +73,10 @@ export class FrontComponentDTO {@Field()usesSdkClient: boolean;- @Field(() => ApplicationTokenPairDTO, { nullable: true })+ @Field(() => ApplicationTokenPairDTO, {+ nullable: true,+ deprecationReason: 'Use generateFrontComponentApplicationTokenPair',+ })applicationTokenPair?: ApplicationTokenPairDTO;@Field(() => GraphQLJSON, { nullable: true })diff --git a/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.tsindex 7dc78fbf1be..1969b0c01ea 100644--- a/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts@@ -1,11 +1,23 @@import { Inject, UseGuards, UseInterceptors, UseFilters } from '@nestjs/common';-import { Args, Mutation, Parent, Query, ResolveField } from '@nestjs/graphql';-+import {+ Args,+ Info,+ Mutation,+ Parent,+ Query,+ ResolveField,+} from '@nestjs/graphql';++import { type GraphQLResolveInfo } from 'graphql';+import graphqlFields from 'graphql-fields';import { type ApplicationCapability } from 'twenty-shared/application';import { PermissionFlagType } from 'twenty-shared/constants';+import { isDefined } from 'twenty-shared/utils';import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';+import { ApplicationExceptionFilter } from 'src/engine/core-modules/application/application-exception-filter';+import { ApplicationTokenPairDTO } from 'src/engine/core-modules/application/application-oauth/dtos/application-token-pair.dto';import { ApplicationVariableEntityService } from 'src/engine/core-modules/application/application-variable/application-variable.service';import { ApplicationTokenService } from 'src/engine/core-modules/auth/token/services/application-token.service';import { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';@@ -106,6 +118,7 @@ export class FrontComponentResolver {@AuthWorkspace() workspace: WorkspaceEntity,@AuthUser() user: AuthContextUser,@AuthUserWorkspaceId() userWorkspaceId: string,+ @Info() info: GraphQLResolveInfo,): Promise<FrontComponentDTO | null> {const dto = await this.frontComponentService.findById(id, workspace.id);@@ -113,26 +126,50 @@ export class FrontComponentResolver {return null;}- const [tokenPair, applicationVariables] = await Promise.all([- this.applicationTokenService.generateApplicationTokenPair({- applicationId: dto.applicationId,- workspaceId: workspace.id,- userWorkspaceId,- userId: user.id,- }),- this.applicationVariableService.getPublicEnvVariables({- workspaceId: workspace.id,- applicationId: dto.applicationId,- }),+ const selectedFields = graphqlFields(info);++ const [applicationTokenPair, applicationVariables] = await Promise.all([+ isDefined(selectedFields.applicationTokenPair)+ ? this.applicationTokenService.generateApplicationTokenPair({+ applicationId: dto.applicationId,+ workspaceId: workspace.id,+ userWorkspaceId,+ userId: user.id,+ })+ : undefined,+ isDefined(selectedFields.applicationVariables)+ ? this.applicationVariableService.getPublicEnvVariables({+ workspaceId: workspace.id,+ applicationId: dto.applicationId,+ })+ : undefined,]);return {...dto,- applicationTokenPair: tokenPair,+ applicationTokenPair,applicationVariables,};}+ @Mutation(() => ApplicationTokenPairDTO)+ @UseGuards(RequireAccessTokenGuard, NoPermissionGuard)+ @UseFilters(ApplicationExceptionFilter)+ async generateFrontComponentApplicationTokenPair(+ @Args('applicationId', { type: () => UUIDScalarType })+ applicationId: string,+ @AuthWorkspace() workspace: WorkspaceEntity,+ @AuthUser() user: AuthContextUser,+ @AuthUserWorkspaceId() userWorkspaceId: string,+ ): Promise<ApplicationTokenPairDTO> {+ return this.applicationTokenService.generateApplicationTokenPair({+ applicationId,+ workspaceId: workspace.id,+ userWorkspaceId,+ userId: user.id,+ });+ }+@Mutation(() => FrontComponentDTO)@UseGuards(SettingsPermissionGuard(PermissionFlagType.APPLICATIONS))async createFrontComponent(diff --git a/packages/twenty-server/test/integration/metadata/suites/application/application-token-not-returned-by-graphql.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/application-token-not-returned-by-graphql.integration-spec.tsindex 0c73e78f475..f3988757683 100644--- a/packages/twenty-server/test/integration/metadata/suites/application/application-token-not-returned-by-graphql.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/application/application-token-not-returned-by-graphql.integration-spec.ts@@ -4,9 +4,9 @@ import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/mconst APPLICATION_TOKEN_TYPE_NAME = 'ApplicationTokenPair';-// These two fields are the exceptions the invariant allows: both mint under-// the caller's own session, so the token carries the intersection of that-// user's permissions and the application's role. Anything else reaching an+// These fields are the exceptions the invariant allows: all mint under the+// caller's own session, so the token carries the intersection of that user's+// permissions and the application's role. Anything else reaching an// application token would be a caller asking the API for an application's// credentials.//@@ -16,6 +16,7 @@ const APPLICATION_TOKEN_TYPE_NAME = 'ApplicationTokenPair';// rotating one.const METADATA_FIELDS_RETURNING_AN_APPLICATION_TOKEN = ['FrontComponent.applicationTokenPair',+ 'Mutation.generateFrontComponentApplicationTokenPair','Mutation.renewApplicationToken',];diff --git a/packages/twenty-server/test/integration/metadata/suites/front-component/__snapshots__/failing-front-component-application-token-pair-generation.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/front-component/__snapshots__/failing-front-component-application-token-pair-generation.integration-spec.ts.snapnew file mode 100644index 00000000000..8d9664e5d34--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/front-component/__snapshots__/failing-front-component-application-token-pair-generation.integration-spec.ts.snap@@ -0,0 +1,49 @@+// Jest Snapshot v1, https://goo.gl/fbAQLP++exports[`Front component application token pair generation should fail when called with a user-bound application token 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN_EXCEPTION",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint requires a session access token",+ "name": "ForbiddenError",+}+`;++exports[`Front component application token pair generation should fail when called with an API key token 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN_EXCEPTION",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint requires a session access token",+ "name": "ForbiddenError",+}+`;++exports[`Front component application token pair generation should fail when called with an application token without user binding 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN_EXCEPTION",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint requires a session access token",+ "name": "ForbiddenError",+}+`;++exports[`Front component application token pair generation should fail when the application does not exist 1`] = `+{+ "extensions": {+ "code": "NOT_FOUND",+ "subCode": "APPLICATION_NOT_FOUND",+ "userFriendlyMessage": "Application not found.",+ },+ "message": "Application not found",+ "name": "NotFoundError",+}+`;diff --git a/packages/twenty-server/test/integration/metadata/suites/front-component/failing-front-component-application-token-pair-generation.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/front-component/failing-front-component-application-token-pair-generation.integration-spec.tsnew file mode 100644index 00000000000..6bf446b0e69--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/front-component/failing-front-component-application-token-pair-generation.integration-spec.ts@@ -0,0 +1,103 @@+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';+import { findFrontComponents } from 'test/integration/metadata/suites/front-component/utils/find-front-components.util';+import { generateFrontComponentApplicationTokenPair } from 'test/integration/metadata/suites/front-component/utils/generate-front-component-application-token-pair.util';+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';+import {+ eachTestingContextFilter,+ type EachTestingContext,+} from 'twenty-shared/testing';++import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++const UNKNOWN_APPLICATION_ID = '20202020-0000-4000-8000-000000000000';++type GlobalTestContext = {+ applicationWithFrontComponentId: string;+ applicationUserBoundToken: string;+ applicationUnboundToken: string;+};++type TestContext = {+ applicationId: (globalContext: GlobalTestContext) => string;+ token?: (globalContext: GlobalTestContext) => string;+};++const failingFrontComponentApplicationTokenPairGenerationTestCases: EachTestingContext<TestContext>[] =+ [+ {+ title: 'when called with a user-bound application token',+ context: {+ applicationId: (globalContext) =>+ globalContext.applicationWithFrontComponentId,+ token: (globalContext) => globalContext.applicationUserBoundToken,+ },+ },+ {+ title: 'when called with an application token without user binding',+ context: {+ applicationId: (globalContext) =>+ globalContext.applicationWithFrontComponentId,+ token: (globalContext) => globalContext.applicationUnboundToken,+ },+ },+ {+ title: 'when called with an API key token',+ context: {+ applicationId: (globalContext) =>+ globalContext.applicationWithFrontComponentId,+ token: () => API_KEY_ACCESS_TOKEN,+ },+ },+ {+ title: 'when the application does not exist',+ context: {+ applicationId: () => UNKNOWN_APPLICATION_ID,+ },+ },+ ];++describe('Front component application token pair generation should fail', () => {+ let globalTestContext: GlobalTestContext;++ beforeAll(async () => {+ const { data: frontComponentsData } = await findFrontComponents({+ expectToFail: false,+ });+ const [frontComponent] = frontComponentsData.frontComponents;++ jestExpectToBeDefined(frontComponent);++ const [userBoundTokenPair, unboundTokenPair] = await Promise.all([+ generateAppleAdminApplicationTokenPair({+ applicationId: frontComponent.applicationId,+ }),+ generateApplicationTokenPair({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ applicationId: frontComponent.applicationId,+ }),+ ]);++ globalTestContext = {+ applicationWithFrontComponentId: frontComponent.applicationId,+ applicationUserBoundToken:+ userBoundTokenPair.applicationAccessToken.token,+ applicationUnboundToken: unboundTokenPair.applicationAccessToken.token,+ };+ });++ it.each(+ eachTestingContextFilter(+ failingFrontComponentApplicationTokenPairGenerationTestCases,+ ),+ )('$title', async ({ context }) => {+ const { errors } = await generateFrontComponentApplicationTokenPair({+ input: { applicationId: context.applicationId(globalTestContext) },+ token: context.token?.(globalTestContext),+ expectToFail: true,+ });++ expectOneNotInternalServerErrorSnapshot({ errors });+ });+});diff --git a/packages/twenty-server/test/integration/metadata/suites/front-component/successful-front-component-application-token-pair-generation.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/front-component/successful-front-component-application-token-pair-generation.integration-spec.tsnew file mode 100644index 00000000000..d1ebf996da9--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/front-component/successful-front-component-application-token-pair-generation.integration-spec.ts@@ -0,0 +1,56 @@+import { decodeJwtCompleteOrThrow } from 'test/integration/graphql/utils/decode-jwt-complete-or-throw.util';+import { findFrontComponents } from 'test/integration/metadata/suites/front-component/utils/find-front-components.util';+import { generateFrontComponentApplicationTokenPair } from 'test/integration/metadata/suites/front-component/utils/generate-front-component-application-token-pair.util';+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';++import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';++describe('Front component application token pair generation should be bound to the session', () => {+ let applicationId: string;++ beforeAll(async () => {+ const { data } = await findFrontComponents({ expectToFail: false });+ const [frontComponent] = data.frontComponents;++ jestExpectToBeDefined(frontComponent);++ applicationId = frontComponent.applicationId;+ });++ it('should issue a token pair bound to the session for the application', async () => {+ const { data } = await generateFrontComponentApplicationTokenPair({+ input: { applicationId },+ expectToFail: false,+ });++ const applicationTokenPair =+ data.generateFrontComponentApplicationTokenPair;++ const expectedBinding = {+ applicationId,+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ userId: USER_DATA_SEED_IDS.JANE,+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,+ };++ expect(+ decodeJwtCompleteOrThrow(+ applicationTokenPair.applicationAccessToken.token,+ ).payload,+ ).toMatchObject({+ ...expectedBinding,+ type: JwtTokenTypeEnum.APPLICATION_ACCESS,+ });+ expect(+ decodeJwtCompleteOrThrow(+ applicationTokenPair.applicationRefreshToken.token,+ ).payload,+ ).toMatchObject({+ ...expectedBinding,+ type: JwtTokenTypeEnum.APPLICATION_REFRESH,+ });+ });+});diff --git a/packages/twenty-server/test/integration/metadata/suites/front-component/utils/generate-front-component-application-token-pair-query-factory.util.ts b/packages/twenty-server/test/integration/metadata/suites/front-component/utils/generate-front-component-application-token-pair-query-factory.util.tsnew file mode 100644index 00000000000..e3cc8b5adc4--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/front-component/utils/generate-front-component-application-token-pair-query-factory.util.ts@@ -0,0 +1,33 @@+import gql from 'graphql-tag';+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';++export type GenerateFrontComponentApplicationTokenPairFactoryInput = {+ applicationId: string;+};++const DEFAULT_APPLICATION_TOKEN_PAIR_GQL_FIELDS = `+ applicationAccessToken {+ token+ expiresAt+ }+ applicationRefreshToken {+ token+ expiresAt+ }+`;++export const generateFrontComponentApplicationTokenPairQueryFactory = ({+ input,+ gqlFields = DEFAULT_APPLICATION_TOKEN_PAIR_GQL_FIELDS,+}: PerformMetadataQueryParams<GenerateFrontComponentApplicationTokenPairFactoryInput>) => ({+ query: gql`+ mutation GenerateFrontComponentApplicationTokenPair($applicationId: UUID!) {+ generateFrontComponentApplicationTokenPair(applicationId: $applicationId) {+ ${gqlFields}+ }+ }+ `,+ variables: {+ applicationId: input.applicationId,+ },+});diff --git a/packages/twenty-server/test/integration/metadata/suites/front-component/utils/generate-front-component-application-token-pair.util.ts b/packages/twenty-server/test/integration/metadata/suites/front-component/utils/generate-front-component-application-token-pair.util.tsnew file mode 100644index 00000000000..d614df435ec--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/front-component/utils/generate-front-component-application-token-pair.util.ts@@ -0,0 +1,46 @@+import {+ type GenerateFrontComponentApplicationTokenPairFactoryInput,+ generateFrontComponentApplicationTokenPairQueryFactory,+} from 'test/integration/metadata/suites/front-component/utils/generate-front-component-application-token-pair-query-factory.util';+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';+import { type CommonResponseBody } from 'test/integration/metadata/types/common-response-body.type';+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';+import { warnIfErrorButNotExpectedToFail } from 'test/integration/metadata/utils/warn-if-error-but-not-expected-to-fail.util';+import { warnIfNoErrorButExpectedToFail } from 'test/integration/metadata/utils/warn-if-no-error-but-expected-to-fail.util';++import { type ApplicationTokenPairDTO } from 'src/engine/core-modules/application/application-oauth/dtos/application-token-pair.dto';++export const generateFrontComponentApplicationTokenPair = async ({+ input,+ gqlFields,+ expectToFail = false,+ token,+}: PerformMetadataQueryParams<GenerateFrontComponentApplicationTokenPairFactoryInput>): CommonResponseBody<{+ generateFrontComponentApplicationTokenPair: ApplicationTokenPairDTO;+}> => {+ const graphqlOperation =+ generateFrontComponentApplicationTokenPairQueryFactory({+ input,+ gqlFields,+ });++ const response = await makeMetadataApiRequest(graphqlOperation, token);++ if (expectToFail === true) {+ warnIfNoErrorButExpectedToFail({+ response,+ errorMessage:+ 'Generating front component application token pair should have failed but did not',+ });+ }++ if (expectToFail === false) {+ warnIfErrorButNotExpectedToFail({+ response,+ errorMessage:+ 'Generating front component application token pair has failed but should not',+ });+ }++ return { data: response.body.data, errors: response.body.errors };+};