Skip to content

The open alternative to Salesforce, designed for AI.

Broadcast application and applicationRegistration changes over SSE (#25173)

martmull9561c8384af5
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 1b6137bdede..5faaa12c29e 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -7411,7 +7411,7 @@ export type ApplicationFieldsFragment = { __typename?: 'Application', id: string
export type FindManyApplicationsQueryVariables = Exact<{ [key: string]: never; }>;
-export type FindManyApplicationsQuery = { __typename?: 'Query', findManyApplications: Array<{ __typename?: 'Application', id: string, name: string, description?: string | null, logoUrl?: string | null, version?: string | null, universalIdentifier: string, applicationRegistrationId?: string | null, applicationRegistration?: { __typename?: 'ApplicationRegistrationSummary', id: string, latestAvailableVersion?: string | null, sourceType: ApplicationRegistrationSourceType } | null }> };
+export type FindManyApplicationsQuery = { __typename?: 'Query', findManyApplications: Array<{ __typename?: 'Application', id: string, name: string, description?: string | null, logoUrl?: string | null, version?: string | null, state: ApplicationState, universalIdentifier: string, applicationRegistrationId?: string | null, applicationRegistration?: { __typename?: 'ApplicationRegistrationSummary', id: string, latestAvailableVersion?: string | null, sourceType: ApplicationRegistrationSourceType } | null }> };
export type FindOneApplicationQueryVariables = Exact<{
id: Scalars['UUID']['input'];
@@ -9825,7 +9825,7 @@ export const GetToolIndexDocument = {"kind":"Document","definitions":[{"kind":"O
export const GetToolInputSchemaDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetToolInputSchema"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"toolName"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getToolInputSchema"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"toolName"},"value":{"kind":"Variable","name":{"kind":"Name","value":"toolName"}}}]}]}}]} as unknown as DocumentNode<GetToolInputSchemaQuery, GetToolInputSchemaQueryVariables>;
export const OnAgentChatEventDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"OnAgentChatEvent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"onAgentChatEvent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"event"}}]}}]}}]} as unknown as DocumentNode<OnAgentChatEventSubscription, OnAgentChatEventSubscriptionVariables>;
export const TrackAnalyticsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"TrackAnalytics"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"type"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AnalyticsType"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"event"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"name"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"properties"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"trackAnalytics"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"type"},"value":{"kind":"Variable","name":{"kind":"Name","value":"type"}}},{"kind":"Argument","name":{"kind":"Name","value":"event"},"value":{"kind":"Variable","name":{"kind":"Name","value":"event"}}},{"kind":"Argument","name":{"kind":"Name","value":"name"},"value":{"kind":"Variable","name":{"kind":"Name","value":"name"}}},{"kind":"Argument","name":{"kind":"Name","value":"properties"},"value":{"kind":"Variable","name":{"kind":"Name","value":"properties"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}}]}}]}}]} as unknown as DocumentNode<TrackAnalyticsMutation, TrackAnalyticsMutationVariables>;
-export const FindManyApplicationsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findManyApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"version"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"applicationRegistrationId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationRegistration"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}}]}}]}}]}}]} as unknown as DocumentNode<FindManyApplicationsQuery, FindManyApplicationsQueryVariables>;
+export const FindManyApplicationsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findManyApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"version"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"applicationRegistrationId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationRegistration"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}}]}}]}}]}}]} as unknown as DocumentNode<FindManyApplicationsQuery, FindManyApplicationsQueryVariables>;
export const FindOneApplicationDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneApplication"},"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":"findOneApplication"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ApplicationFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Agent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"prompt"}},{"kind":"Field","name":{"kind":"Name","value":"modelId"}},{"kind":"Field","name":{"kind":"Name","value":"responseFormat"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"modelConfiguration"}},{"kind":"Field","name":{"kind":"Name","value":"evaluationInputs"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ObjectMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Object"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}},{"kind":"Field","name":{"kind":"Name","value":"labelSingular"}},{"kind":"Field","name":{"kind":"Name","value":"labelPlural"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"isRemote"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}},{"kind":"Field","name":{"kind":"Name","value":"isUICreatable"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"labelIdentifierFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"imageIdentifierFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"shortcut"}},{"kind":"Field","name":{"kind":"Name","value":"isLabelSyncedWithName"}},{"kind":"Field","name":{"kind":"Name","value":"isSearchable"}},{"kind":"Field","name":{"kind":"Name","value":"openRecordIn"}},{"kind":"Field","name":{"kind":"Name","value":"duplicateCriteria"}},{"kind":"Field","name":{"kind":"Name","value":"searchFieldMetadataList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"tsVectorFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"indexMetadataList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"indexWhereClause"}},{"kind":"Field","name":{"kind":"Name","value":"indexType"}},{"kind":"Field","name":{"kind":"Name","value":"isUnique"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"indexFieldMetadataList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"subFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"order"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"fieldsList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}},{"kind":"Field","name":{"kind":"Name","value":"isNullable"}},{"kind":"Field","name":{"kind":"Name","value":"isUnique"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"defaultValue"}},{"kind":"Field","name":{"kind":"Name","value":"options"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"isLabelSyncedWithName"}},{"kind":"Field","name":{"kind":"Name","value":"morphId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"relation"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"sourceObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"sourceFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"morphRelations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"sourceObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"sourceFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"LogicFunctionFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"LogicFunction"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"runtime"}},{"kind":"Field","name":{"kind":"Name","value":"timeoutSeconds"}},{"kind":"Field","name":{"kind":"Name","value":"executionMode"}},{"kind":"Field","name":{"kind":"Name","value":"sourceHandlerPath"}},{"kind":"Field","name":{"kind":"Name","value":"handlerName"}},{"kind":"Field","name":{"kind":"Name","value":"cronTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"databaseEventTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"httpRouteTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"toolTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"workflowActionTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ApplicationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Application"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"version"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"applicationRegistrationId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationRegistration"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"canBeUninstalled"}},{"kind":"Field","name":{"kind":"Name","value":"autoUpgrade"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRoleId"}},{"kind":"Field","name":{"kind":"Name","value":"settingsCustomTabFrontComponentId"}},{"kind":"Field","name":{"kind":"Name","value":"availablePackages"}},{"kind":"Field","name":{"kind":"Name","value":"applicationVariables"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"isSecret"}},{"kind":"Field","name":{"kind":"Name","value":"isDeprecated"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"options"}}]}},{"kind":"Field","name":{"kind":"Name","value":"agents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentFields"}}]}},{"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":"description"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"componentName"}},{"kind":"Field","name":{"kind":"Name","value":"builtComponentChecksum"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"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":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"commandMenuItems"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"shortLabel"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"isPinned"}},{"kind":"Field","name":{"kind":"Name","value":"availabilityType"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalAvailabilityExpression"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"objects"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ObjectMetadataFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"logicFunctions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"LogicFunctionFields"}}]}}]}}]} as unknown as DocumentNode<FindOneApplicationQuery, FindOneApplicationQueryVariables>;
export const FindOneApplicationByUniversalIdentifierDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneApplicationByUniversalIdentifier"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findOneApplication"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"universalIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"version"}},{"kind":"Field","name":{"kind":"Name","value":"state"}}]}}]}}]} as unknown as DocumentNode<FindOneApplicationByUniversalIdentifierQuery, FindOneApplicationByUniversalIdentifierQueryVariables>;
export const FindOneApplicationNameDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneApplicationName"},"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":"findOneApplication"},"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"}}]}}]}}]} as unknown as DocumentNode<FindOneApplicationNameQuery, FindOneApplicationNameQueryVariables>;
diff --git a/packages/twenty-front/src/modules/app/components/WorkspaceAppProviders.tsx b/packages/twenty-front/src/modules/app/components/WorkspaceAppProviders.tsx
index 309a1a731e6..c74a4444bda 100644
--- a/packages/twenty-front/src/modules/app/components/WorkspaceAppProviders.tsx
+++ b/packages/twenty-front/src/modules/app/components/WorkspaceAppProviders.tsx
@@ -2,6 +2,7 @@ import { StrictMode } from 'react';
import { Outlet, useLocation } from 'react-router-dom';
import { AgentChatProvider } from '@/ai/components/AgentChatProvider';
+import { ApplicationsLoadEffect } from '@/applications/components/ApplicationsLoadEffect';
import { TrackPageViewEffect } from '@/analytics/components/TrackPageViewEffect';
import { SharedAppProviders } from '@/app/components/SharedAppProviders';
import { GotoHotkeysEffectsProvider } from '@/app/effect-components/GotoHotkeysEffectsProvider';
@@ -55,6 +56,7 @@ export const WorkspaceAppProviders = () => {
<ApolloCoreProvider>
<ApolloAdminProvider>
<SSEProvider>
+ <ApplicationsLoadEffect />
<UserThemeProviderEffect />
<UserUiScaleProviderEffect />
<ContextStoreComponentInstanceContext.Provider
diff --git a/packages/twenty-front/src/modules/applications/components/ApplicationsLoadEffect.tsx b/packages/twenty-front/src/modules/applications/components/ApplicationsLoadEffect.tsx
new file mode 100644
index 00000000000..6e6cd250d4f
--- /dev/null
+++ b/packages/twenty-front/src/modules/applications/components/ApplicationsLoadEffect.tsx
@@ -0,0 +1,125 @@
+import { applicationBroadcastEventCountState } from '@/applications/states/applicationBroadcastEventCountState';
+import { applicationsLoadSequenceState } from '@/applications/states/applicationsLoadSequenceState';
+import { useIsOnAuthOrOnboardingPage } from '@/auth/hooks/useIsOnAuthOrOnboardingPage';
+import { useListenToBrowserEvent } from '@/browser-event/hooks/useListenToBrowserEvent';
+import { useListenToMetadataOperationBrowserEvent } from '@/browser-event/hooks/useListenToMetadataOperationBrowserEvent';
+import { useUpdateMetadataStoreDraft } from '@/metadata-store/hooks/useUpdateMetadataStoreDraft';
+import { type FlatApplication } from '@/metadata-store/types/FlatApplication';
+import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';
+import { SSE_CLIENT_RECONNECTED_EVENT_NAME } from '@/sse-db-event/constants/SseClientReconnectedEventName';
+import { useApolloClient } from '@apollo/client/react';
+import { useStore } from 'jotai';
+import { useCallback, useEffect } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import {
+ FindManyApplicationsDocument,
+ PermissionFlagType,
+} from '~/generated-metadata/graphql';
+
+const APPLICATIONS_LOAD_MAX_ATTEMPTS = 3;
+
+export const ApplicationsLoadEffect = () => {
+ const client = useApolloClient();
+ const store = useStore();
+ const { replaceDraft, applyChanges } = useUpdateMetadataStoreDraft();
+
+ const hasApplicationsPermission = useHasPermissionFlag(
+ PermissionFlagType.APPLICATIONS,
+ );
+
+ const isOnAuthOrOnboardingPage = useIsOnAuthOrOnboardingPage();
+
+ const onApplicationOperation = useCallback(() => {
+ store.set(
+ applicationBroadcastEventCountState.atom,
+ (eventCount) => eventCount + 1,
+ );
+ }, [store]);
+
+ useListenToMetadataOperationBrowserEvent<FlatApplication>({
+ metadataName: 'application',
+ onMetadataOperationBrowserEvent: onApplicationOperation,
+ });
+
+ const loadApplications = useCallback(async () => {
+ const loadSequence = store.get(applicationsLoadSequenceState.atom) + 1;
+
+ store.set(applicationsLoadSequenceState.atom, loadSequence);
+
+ if (!hasApplicationsPermission || isOnAuthOrOnboardingPage) {
+ return;
+ }
+
+ for (
+ let attempt = 0;
+ attempt < APPLICATIONS_LOAD_MAX_ATTEMPTS;
+ attempt += 1
+ ) {
+ const eventCountBeforeQuery = store.get(
+ applicationBroadcastEventCountState.atom,
+ );
+
+ const result = await client
+ .query({
+ query: FindManyApplicationsDocument,
+ fetchPolicy: 'network-only',
+ context: { queryDeduplication: false },
+ })
+ .catch(() => null);
+
+ if (store.get(applicationsLoadSequenceState.atom) !== loadSequence) {
+ return;
+ }
+
+ if (!isDefined(result)) {
+ continue;
+ }
+
+ if (!isDefined(result.data?.findManyApplications)) {
+ return;
+ }
+
+ const hasReceivedEventsDuringQuery =
+ store.get(applicationBroadcastEventCountState.atom) !==
+ eventCountBeforeQuery;
+
+ if (hasReceivedEventsDuringQuery) {
+ continue;
+ }
+
+ const applications: FlatApplication[] =
+ result.data.findManyApplications.map((application) => ({
+ id: application.id,
+ universalIdentifier: application.universalIdentifier,
+ name: application.name,
+ description: application.description,
+ version: application.version,
+ state: application.state,
+ applicationRegistrationId: application.applicationRegistrationId,
+ }));
+
+ replaceDraft('applications', applications);
+ applyChanges();
+
+ return;
+ }
+ }, [
+ client,
+ store,
+ hasApplicationsPermission,
+ isOnAuthOrOnboardingPage,
+ replaceDraft,
+ applyChanges,
+ ]);
+
+ useEffect(() => {
+ void loadApplications();
+ }, [loadApplications]);
+
+ useListenToBrowserEvent({
+ eventName: SSE_CLIENT_RECONNECTED_EVENT_NAME,
+ onBrowserEvent: loadApplications,
+ });
+
+ return null;
+};
diff --git a/packages/twenty-front/src/modules/applications/graphql/queries/findManyApplications.ts b/packages/twenty-front/src/modules/applications/graphql/queries/findManyApplications.ts
index 3dc8f243d98..94b3413058c 100644
--- a/packages/twenty-front/src/modules/applications/graphql/queries/findManyApplications.ts
+++ b/packages/twenty-front/src/modules/applications/graphql/queries/findManyApplications.ts
@@ -8,6 +8,7 @@ export const FIND_MANY_APPLICATIONS = gql`
description
logoUrl
version
+ state
universalIdentifier
applicationRegistrationId
applicationRegistration {
diff --git a/packages/twenty-front/src/modules/applications/hooks/useInstalledApplications.ts b/packages/twenty-front/src/modules/applications/hooks/useInstalledApplications.ts
new file mode 100644
index 00000000000..a5218629f0a
--- /dev/null
+++ b/packages/twenty-front/src/modules/applications/hooks/useInstalledApplications.ts
@@ -0,0 +1,33 @@
+import { useRefetchOnApplicationLifecycleSettled } from '@/applications/hooks/useRefetchOnApplicationLifecycleSettled';
+import { useRefetchOnApplicationRegistrationChange } from '@/applications/hooks/useRefetchOnApplicationRegistrationChange';
+import { applicationsSelector } from '@/applications/states/applicationsSelector';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { useQuery } from '@apollo/client/react';
+import { FindManyApplicationsDocument } from '~/generated-metadata/graphql';
+import { type ApplicationWithoutRelation } from '~/pages/settings/applications/types/applicationWithoutRelation';
+
+export const useInstalledApplications = (): ApplicationWithoutRelation[] => {
+ const { data, refetch } = useQuery(FindManyApplicationsDocument);
+
+ useRefetchOnApplicationLifecycleSettled({ refetch });
+ useRefetchOnApplicationRegistrationChange({ refetch });
+
+ const applications = useAtomStateValue(applicationsSelector);
+
+ const queriedApplicationsById = new Map(
+ (data?.findManyApplications ?? []).map((application) => [
+ application.id,
+ application,
+ ]),
+ );
+
+ return applications.map((application) => {
+ const queriedApplication = queriedApplicationsById.get(application.id);
+
+ return {
+ ...application,
+ logoUrl: queriedApplication?.logoUrl,
+ applicationRegistration: queriedApplication?.applicationRegistration,
+ };
+ });
+};
diff --git a/packages/twenty-front/src/modules/applications/hooks/useRefetchOnApplicationLifecycleSettled.ts b/packages/twenty-front/src/modules/applications/hooks/useRefetchOnApplicationLifecycleSettled.ts
new file mode 100644
index 00000000000..0f6c3c869d3
--- /dev/null
+++ b/packages/twenty-front/src/modules/applications/hooks/useRefetchOnApplicationLifecycleSettled.ts
@@ -0,0 +1,67 @@
+import { useListenToMetadataOperationBrowserEvent } from '@/browser-event/hooks/useListenToMetadataOperationBrowserEvent';
+import { type MetadataOperationBrowserEventDetail } from '@/browser-event/types/MetadataOperationBrowserEventDetail';
+import { type FlatApplication } from '@/metadata-store/types/FlatApplication';
+import { useCallback } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { ApplicationState } from '~/generated-metadata/graphql';
+
+const QUERY_ONLY_APPLICATION_FIELDS = ['logo'];
+
+type UseRefetchOnApplicationLifecycleSettledArgs = {
+ applicationId?: string;
+ refetch: () => void;
+};
+
+export const useRefetchOnApplicationLifecycleSettled = ({
+ applicationId,
+ refetch,
+}: UseRefetchOnApplicationLifecycleSettledArgs) => {
+ const onApplicationOperation = useCallback(
+ ({ operation }: MetadataOperationBrowserEventDetail<FlatApplication>) => {
+ if (operation.type === 'delete') {
+ if (isDefined(applicationId)) {
+ return;
+ }
+
+ refetch();
+
+ return;
+ }
+
+ const application =
+ operation.type === 'create'
+ ? operation.createdRecord
+ : operation.updatedRecord;
+
+ if (isDefined(applicationId) && application.id !== applicationId) {
+ return;
+ }
+
+ if (application.state !== ApplicationState.INSTALLED) {
+ return;
+ }
+
+ const updatedFields =
+ operation.type === 'update' ? (operation.updatedFields ?? []) : [];
+
+ const hasSettledOnThisEvent =
+ operation.type === 'create' || updatedFields.includes('state');
+
+ const hasChangedQueryOnlyField = updatedFields.some((updatedField) =>
+ QUERY_ONLY_APPLICATION_FIELDS.includes(updatedField),
+ );
+
+ if (!hasSettledOnThisEvent && !hasChangedQueryOnlyField) {
+ return;
+ }
+
+ refetch();
+ },
+ [applicationId, refetch],
+ );
+
+ useListenToMetadataOperationBrowserEvent<FlatApplication>({
+ metadataName: 'application',
+ onMetadataOperationBrowserEvent: onApplicationOperation,
+ });
+};
diff --git a/packages/twenty-front/src/modules/applications/hooks/useRefetchOnApplicationRegistrationChange.ts b/packages/twenty-front/src/modules/applications/hooks/useRefetchOnApplicationRegistrationChange.ts
new file mode 100644
index 00000000000..f63914d6136
--- /dev/null
+++ b/packages/twenty-front/src/modules/applications/hooks/useRefetchOnApplicationRegistrationChange.ts
@@ -0,0 +1,54 @@
+import { useListenToMetadataOperationBrowserEvent } from '@/browser-event/hooks/useListenToMetadataOperationBrowserEvent';
+import { type MetadataOperation } from '@/browser-event/types/MetadataOperation';
+import { type MetadataOperationBrowserEventDetail } from '@/browser-event/types/MetadataOperationBrowserEventDetail';
+import { useCallback } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+
+type ApplicationRegistrationBroadcastRecord = { id: string };
+
+type UseRefetchOnApplicationRegistrationChangeArgs = {
+ applicationRegistrationId?: string;
+ refetch: () => void;
+};
+
+const getChangedRegistrationId = (
+ operation: MetadataOperation<ApplicationRegistrationBroadcastRecord>,
+): string => {
+ switch (operation.type) {
+ case 'create':
+ return operation.createdRecord.id;
+ case 'update':
+ return operation.updatedRecord.id;
+ case 'delete':
+ return operation.deletedRecordId;
+ }
+};
+
+export const useRefetchOnApplicationRegistrationChange = ({
+ applicationRegistrationId,
+ refetch,
+}: UseRefetchOnApplicationRegistrationChangeArgs) => {
+ const onApplicationRegistrationOperation = useCallback(
+ ({
+ operation,
+ }: MetadataOperationBrowserEventDetail<ApplicationRegistrationBroadcastRecord>) => {
+ if (
+ isDefined(applicationRegistrationId) &&
+ (getChangedRegistrationId(operation) !== applicationRegistrationId ||
+ operation.type === 'delete')
+ ) {
+ return;
+ }
+
+ refetch();
+ },
+ [applicationRegistrationId, refetch],
+ );
+
+ useListenToMetadataOperationBrowserEvent<ApplicationRegistrationBroadcastRecord>(
+ {
+ metadataName: 'applicationRegistration',
+ onMetadataOperationBrowserEvent: onApplicationRegistrationOperation,
+ },
+ );
+};
diff --git a/packages/twenty-front/src/modules/applications/states/applicationBroadcastEventCountState.ts b/packages/twenty-front/src/modules/applications/states/applicationBroadcastEventCountState.ts
new file mode 100644
index 00000000000..b3ed75da939
--- /dev/null
+++ b/packages/twenty-front/src/modules/applications/states/applicationBroadcastEventCountState.ts
@@ -0,0 +1,6 @@
+import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
+
+export const applicationBroadcastEventCountState = createAtomState<number>({
+ key: 'applicationBroadcastEventCountState',
+ defaultValue: 0,
+});
diff --git a/packages/twenty-front/src/modules/applications/states/applicationsLoadSequenceState.ts b/packages/twenty-front/src/modules/applications/states/applicationsLoadSequenceState.ts
new file mode 100644
index 00000000000..f77efb0df13
--- /dev/null
+++ b/packages/twenty-front/src/modules/applications/states/applicationsLoadSequenceState.ts
@@ -0,0 +1,6 @@
+import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
+
+export const applicationsLoadSequenceState = createAtomState<number>({
+ key: 'applicationsLoadSequenceState',
+ defaultValue: 0,
+});
diff --git a/packages/twenty-front/src/modules/applications/states/applicationsSelector.ts b/packages/twenty-front/src/modules/applications/states/applicationsSelector.ts
new file mode 100644
index 00000000000..07f5ab37aaa
--- /dev/null
+++ b/packages/twenty-front/src/modules/applications/states/applicationsSelector.ts
@@ -0,0 +1,12 @@
+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';
+import { type FlatApplication } from '@/metadata-store/types/FlatApplication';
+import { createAtomSelector } from '@/ui/utilities/state/jotai/utils/createAtomSelector';
+
+export const applicationsSelector = createAtomSelector<FlatApplication[]>({
+ key: 'applicationsSelector',
+ get: ({ get }) => {
+ const storeItem = get(metadataStoreState, 'applications');
+
+ return storeItem.current as FlatApplication[];
+ },
+});
diff --git a/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts b/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts
index 83af71e07bd..d5a957f9e01 100644
--- a/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts
+++ b/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts
@@ -6,6 +6,7 @@ import { type AllMetadataName } from 'twenty-shared/metadata';
const ALL_NON_SYNCABLE_BROADCAST_ENTITY_NAME = {
agentChatThread: 'agentChatThread',
application: 'application',
+ applicationRegistration: 'applicationRegistration',
} as const;
type NonSyncableBroadcastEntityName =
diff --git a/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts b/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts
index ed59aa4144d..ef0bf783fc4 100644
--- a/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts
+++ b/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts
@@ -34,6 +34,7 @@ export const ALL_METADATA_ENTITY_KEYS = [
// TODO: clarify what really is metadata (syncable entity?)
// vs 'core engine entity' or 'broadcastable entity'
'agentChatThreads',
+ 'applications',
] as const;
export type MetadataEntityKey = (typeof ALL_METADATA_ENTITY_KEYS)[number];
diff --git a/packages/twenty-front/src/modules/metadata-store/types/FlatApplication.ts b/packages/twenty-front/src/modules/metadata-store/types/FlatApplication.ts
new file mode 100644
index 00000000000..befc7cea565
--- /dev/null
+++ b/packages/twenty-front/src/modules/metadata-store/types/FlatApplication.ts
@@ -0,0 +1,12 @@
+import { type Application } from '~/generated-metadata/graphql';
+
+export type FlatApplication = Pick<
+ Application,
+ | 'id'
+ | 'universalIdentifier'
+ | 'name'
+ | 'description'
+ | 'version'
+ | 'state'
+ | 'applicationRegistrationId'
+>;
diff --git a/packages/twenty-front/src/modules/metadata-store/types/MetadataEntityTypeMap.ts b/packages/twenty-front/src/modules/metadata-store/types/MetadataEntityTypeMap.ts
index 9e44948d044..85446445c77 100644
--- a/packages/twenty-front/src/modules/metadata-store/types/MetadataEntityTypeMap.ts
+++ b/packages/twenty-front/src/modules/metadata-store/types/MetadataEntityTypeMap.ts
@@ -1,5 +1,6 @@
import { type FlatAgent } from '@/metadata-store/types/FlatAgent';
import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';
+import { type FlatApplication } from '@/metadata-store/types/FlatApplication';
import { type FlatCommandMenuItem } from '@/metadata-store/types/FlatCommandMenuItem';
import { type FlatFieldMetadataItem } from '@/metadata-store/types/FlatFieldMetadataItem';
import { type FlatFrontComponent } from '@/metadata-store/types/FlatFrontComponent';
@@ -50,4 +51,5 @@ export type MetadataEntityTypeMap = {
rowLevelPermissionPredicates: FlatRowLevelPermissionPredicate;
rowLevelPermissionPredicateGroups: FlatRowLevelPermissionPredicateGroup;
agentChatThreads: FlatAgentChatThread;
+ applications: FlatApplication;
};
diff --git a/packages/twenty-front/src/modules/metadata-store/utils/mapAllMetadataNameToEntityKey.ts b/packages/twenty-front/src/modules/metadata-store/utils/mapAllMetadataNameToEntityKey.ts
index 3d39e24b2d4..d1a2fe187c9 100644
--- a/packages/twenty-front/src/modules/metadata-store/utils/mapAllMetadataNameToEntityKey.ts
+++ b/packages/twenty-front/src/modules/metadata-store/utils/mapAllMetadataNameToEntityKey.ts
@@ -26,6 +26,7 @@ const METADATA_NAME_TO_ENTITY_KEY: Record<string, MetadataEntityKey> = {
frontComponent: 'frontComponents',
webhook: 'webhooks',
agentChatThread: 'agentChatThreads',
+ application: 'applications',
};
export const mapAllMetadataNameToEntityKey = (
diff --git a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx
index 38ed6309de5..d6c1c07def5 100644
--- a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx
@@ -1,5 +1,6 @@
import { CurrentApplicationContext } from '@/applications/contexts/CurrentApplicationContext';
import { AppChip } from '@/applications/components/AppChip';
+import { useRefetchOnApplicationLifecycleSettled } from '@/applications/hooks/useRefetchOnApplicationLifecycleSettled';
import { useResolvedApplicationDescription } from '@/applications/hooks/useResolvedApplicationDescription';
import { isTwentyStandardApplication } from '@/applications/utils/isTwentyStandardApplication';
import { isWorkspaceCustomApplication } from '@/applications/utils/isWorkspaceCustomApplication';
@@ -66,11 +67,13 @@ export const SettingsApplicationDetails = () => {
APPLICATION_DETAIL_ID,
);
- const { data } = useQuery(FindOneApplicationDocument, {
+ const { data, refetch } = useQuery(FindOneApplicationDocument, {
variables: { id: applicationId },
skip: !applicationId,
});
+ useRefetchOnApplicationLifecycleSettled({ applicationId, refetch });
+
const application = data?.findOneApplication;
const { connectionProviders } =
diff --git a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationRegistrationDetails.tsx b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationRegistrationDetails.tsx
index 007ddb1123e..a1b6ff7ec7b 100644
--- a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationRegistrationDetails.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationRegistrationDetails.tsx
@@ -1,3 +1,4 @@
+import { useRefetchOnApplicationRegistrationChange } from '@/applications/hooks/useRefetchOnApplicationRegistrationChange';
import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';
import { useQuery } from '@apollo/client/react';
import { useParams } from 'react-router-dom';
@@ -37,9 +38,17 @@ export const SettingsApplicationRegistrationDetails = () => {
applicationRegistrationId: string;
}>();
- const { data, loading } = useQuery(FindOneApplicationRegistrationDocument, {
- variables: { id: applicationRegistrationId },
- skip: !applicationRegistrationId,
+ const { data, loading, refetch } = useQuery(
+ FindOneApplicationRegistrationDocument,
+ {
+ variables: { id: applicationRegistrationId },
+ skip: !applicationRegistrationId,
+ },
+ );
+
+ useRefetchOnApplicationRegistrationChange({
+ applicationRegistrationId,
+ refetch,
});
const registration = data?.findOneApplicationRegistration;
diff --git a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsDeveloperTab.tsx b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsDeveloperTab.tsx
index 1f1cef56486..2d29fc2eef0 100644
--- a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsDeveloperTab.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsDeveloperTab.tsx
@@ -1,3 +1,4 @@
+import { useRefetchOnApplicationRegistrationChange } from '@/applications/hooks/useRefetchOnApplicationRegistrationChange';
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
import { getDocumentationUrl } from '@/support/utils/getDocumentationUrl';
import { Table } from '@/ui/layout/table/components/Table';
@@ -53,7 +54,9 @@ export const SettingsApplicationsDeveloperTab = () => {
const { copyToClipboard } = useCopyToClipboard();
- const { data } = useQuery(FindManyApplicationRegistrationsDocument);
+ const { data, refetch } = useQuery(FindManyApplicationRegistrationsDocument);
+
+ useRefetchOnApplicationRegistrationChange({ refetch });
const canClaimApplications = useHasPermissionFlag(
PermissionFlagType.APPLICATIONS,
diff --git a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsInstalledTab.tsx b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsInstalledTab.tsx
index 09075835314..a63db91a3b4 100644
--- a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsInstalledTab.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsInstalledTab.tsx
@@ -1,15 +1,12 @@
-import { useQuery } from '@apollo/client/react';
-import { FindManyApplicationsDocument } from '~/generated-metadata/graphql';
+import { useInstalledApplications } from '@/applications/hooks/useInstalledApplications';
import { SettingsApplicationsTable } from '~/pages/settings/applications/components/SettingsApplicationsTable';
export const SettingsApplicationsInstalledTab = () => {
- const { data } = useQuery(FindManyApplicationsDocument);
+ const installedApplications = useInstalledApplications();
- const applications = data?.findManyApplications ?? [];
-
- if (applications.length === 0) {
+ if (installedApplications.length === 0) {
return null;
}
- return <SettingsApplicationsTable applications={applications} />;
+ return <SettingsApplicationsTable applications={installedApplications} />;
};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/__tests__/application-registration-asset-broadcast.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/__tests__/application-registration-asset-broadcast.spec.ts
new file mode 100644
index 00000000000..f888d5f7eb0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/__tests__/application-registration-asset-broadcast.spec.ts
@@ -0,0 +1,107 @@
+import { Test, type TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+
+import { ApplicationRegistrationAssetService } from 'src/engine/core-modules/application/application-registration/application-registration-asset.service';
+import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
+import { ApplicationRegistrationService } from 'src/engine/core-modules/application/application-registration/application-registration.service';
+import { ServerFileStorageService } from 'src/engine/core-modules/file-storage/services/server-file-storage.service';
+
+describe('ApplicationRegistrationAssetService - asset broadcast', () => {
+ let service: ApplicationRegistrationAssetService;
+ let applicationRegistrationRepository: {
+ findOne: jest.Mock;
+ update: jest.Mock;
+ };
+ let applicationRegistrationService: {
+ broadcastApplicationRegistrationUpdatedById: jest.Mock;
+ };
+
+ const APPLICATION_REGISTRATION_ID = 'registration-id';
+
+ const manifestApplication = {
+ logo: 'assets/logo.png',
+ } as never;
+
+ // Storage validates the bytes, so a real (1x1) PNG is needed for the write
+ // path to produce a fileId rather than fall back to the previous one
+ const readAsset = jest
+ .fn()
+ .mockResolvedValue(
+ Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
+ 'base64',
+ ),
+ );
+
+ beforeEach(async () => {
+ applicationRegistrationRepository = {
+ findOne: jest.fn(),
+ update: jest.fn(),
+ };
+
+ applicationRegistrationService = {
+ broadcastApplicationRegistrationUpdatedById: jest.fn(),
+ };
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ ApplicationRegistrationAssetService,
+ {
+ provide: getRepositoryToken(ApplicationRegistrationEntity),
+ useValue: applicationRegistrationRepository,
+ },
+ {
+ provide: ServerFileStorageService,
+ useValue: {
+ writeServerFile: jest
+ .fn()
+ .mockResolvedValue({ id: 'stored-logo-file-id' }),
+ findServerFile: jest.fn().mockResolvedValue(null),
+ },
+ },
+ {
+ provide: ApplicationRegistrationService,
+ useValue: applicationRegistrationService,
+ },
+ ],
+ }).compile();
+
+ service = module.get(ApplicationRegistrationAssetService);
+ });
+
+ it('broadcasts once the stored assets differ from the row written before them', async () => {
+ applicationRegistrationRepository.findOne.mockResolvedValue({
+ id: APPLICATION_REGISTRATION_ID,
+ logoFileId: null,
+ galleryImages: [],
+ });
+
+ await service.storeRegistrationAssets({
+ applicationRegistrationId: APPLICATION_REGISTRATION_ID,
+ manifestApplication,
+ readAsset,
+ });
+
+ expect(
+ applicationRegistrationService.broadcastApplicationRegistrationUpdatedById,
+ ).toHaveBeenCalledWith(APPLICATION_REGISTRATION_ID);
+ });
+
+ it('does not broadcast when the asset write leaves the row unchanged', async () => {
+ applicationRegistrationRepository.findOne.mockResolvedValue({
+ id: APPLICATION_REGISTRATION_ID,
+ logoFileId: 'stored-logo-file-id',
+ galleryImages: [],
+ });
+
+ await service.storeRegistrationAssets({
+ applicationRegistrationId: APPLICATION_REGISTRATION_ID,
+ manifestApplication,
+ readAsset,
+ });
+
+ expect(
+ applicationRegistrationService.broadcastApplicationRegistrationUpdatedById,
+ ).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/__tests__/application-registration-upsert-from-catalog.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/__tests__/application-registration-upsert-from-catalog.spec.ts
index d294ab9a03a..f400ef6ff10 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/__tests__/application-registration-upsert-from-catalog.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/__tests__/application-registration-upsert-from-catalog.spec.ts
@@ -14,6 +14,7 @@ import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queu
import { getQueueToken } from 'src/engine/core-modules/message-queue/utils/get-queue-token.util';
import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { WorkspaceEventBroadcaster } from 'src/engine/subscriptions/workspace-event-broadcaster/workspace-event-broadcaster.service';
describe('ApplicationRegistrationService - upsertFromCatalog', () => {
let service: ApplicationRegistrationService;
@@ -101,6 +102,10 @@ describe('ApplicationRegistrationService - upsertFromCatalog', () => {
provide: getQueueToken(MessageQueue.workspaceQueue),
useValue: { add: jest.fn() },
},
+ {
+ provide: WorkspaceEventBroadcaster,
+ useValue: { broadcast: jest.fn() },
+ },
],
}).compile();
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration-asset.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration-asset.service.ts
index f0a639538e1..5dce4cba0f1 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration-asset.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration-asset.service.ts
@@ -1,12 +1,14 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
+import isEqual from 'lodash.isequal';
import { ServerFileFolder } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { Repository } from 'typeorm';
import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
+import { ApplicationRegistrationService } from 'src/engine/core-modules/application/application-registration/application-registration.service';
import { type ApplicationRegistrationGalleryImage } from 'src/engine/core-modules/application/application-registration/types/application-registration-gallery-image.type';
import { isStorableAssetPath } from 'src/engine/core-modules/application/application-registration/utils/is-storable-asset-path.util';
import { toGalleryImagePaths } from 'src/engine/core-modules/application/application-registration/utils/to-gallery-image-paths.util';
@@ -30,6 +32,7 @@ export class ApplicationRegistrationAssetService {
@InjectRepository(ApplicationRegistrationEntity)
private readonly applicationRegistrationRepository: Repository<ApplicationRegistrationEntity>,
private readonly serverFileStorageService: ServerFileStorageService,
+ private readonly applicationRegistrationService: ApplicationRegistrationService,
) {}
async storeRegistrationAssets({
@@ -72,6 +75,12 @@ export class ApplicationRegistrationAssetService {
galleryImages.push({ path, fileId });
}
+ const registrationBeforeAssetWrite =
+ await this.applicationRegistrationRepository.findOne({
+ select: { id: true, logoFileId: true, galleryImages: true },
+ where: { id: applicationRegistrationId },
+ });
+
await this.applicationRegistrationRepository.update(
applicationRegistrationId,
{
@@ -79,6 +88,19 @@ export class ApplicationRegistrationAssetService {
galleryImages,
} as QueryDeepPartialEntity<ApplicationRegistrationEntity>,
);
+
+ const haveAssetsChanged =
+ !isDefined(registrationBeforeAssetWrite) ||
+ registrationBeforeAssetWrite.logoFileId !== logoFileId ||
+ !isEqual(registrationBeforeAssetWrite.galleryImages, galleryImages);
+
+ // Callers broadcast the registration update before this write, so without
+ // a second event a client refetching on that event keeps the pre-asset row
+ if (haveAssetsChanged) {
+ await this.applicationRegistrationService.broadcastApplicationRegistrationUpdatedById(
+ applicationRegistrationId,
+ );
+ }
}
private async storeAssetFile({
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
index 7c1f0b31392..c933730fb80 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
@@ -5,6 +5,7 @@ import crypto from 'crypto';
import { isNonEmptyString } from '@sniptt/guards';
import * as bcrypt from 'bcrypt';
+import isEqual from 'lodash.isequal';
import { type Manifest } from 'twenty-shared/application';
import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
@@ -36,6 +37,7 @@ import {
} from 'src/engine/core-modules/application/application-registration/dtos/update-application-registration.input';
import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
import { buildRegistrationManifestUpdateFields } from 'src/engine/core-modules/application/application-registration/utils/build-registration-manifest-update-fields.util';
+import { serializeApplicationRegistrationForBroadcast } from 'src/engine/core-modules/application/application-registration/utils/serialize-application-registration-for-broadcast.util';
import { fromManifestApplicationToDisplayFields } from 'src/engine/core-modules/application/application-registration/utils/from-manifest-application-to-display-fields.util';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import {
@@ -51,6 +53,7 @@ import { ServerFileStorageService } from 'src/engine/core-modules/file-storage/s
import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { WorkspaceEventBroadcaster } from 'src/engine/subscriptions/workspace-event-broadcaster/workspace-event-broadcaster.service';
import { TWENTY_CLI_APPLICATION_REGISTRATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-cli-application-registration.constant';
const BCRYPT_SALT_ROUNDS = 10;
@@ -127,8 +130,90 @@ export class ApplicationRegistrationService {
private readonly metricsService: MetricsService,
@InjectMessageQueue(MessageQueue.workspaceQueue)
private readonly workspaceQueueService: MessageQueueService,
+ private readonly workspaceEventBroadcaster: WorkspaceEventBroadcaster,
) {}
+ async broadcastApplicationRegistrationUpdatedById(
+ applicationRegistrationId: string,
+ registrationBeforeUpdate?: ApplicationRegistrationEntity,
+ ): Promise<void> {
+ try {
+ const updatedRegistration =
+ await this.applicationRegistrationRepository.findOne({
+ select: APPLICATION_REGISTRATION_WITHOUT_MANIFEST_SELECT,
+ where: { id: applicationRegistrationId },
+ });
+
+ if (!isDefined(updatedRegistration)) {
+ return;
+ }
+
+ const serializedUpdatedRegistration =
+ serializeApplicationRegistrationForBroadcast(updatedRegistration);
+
+ if (
+ isDefined(registrationBeforeUpdate) &&
+ isEqual(
+ serializeApplicationRegistrationForBroadcast(
+ registrationBeforeUpdate,
+ ),
+ serializedUpdatedRegistration,
+ )
+ ) {
+ return;
+ }
+
+ await this.broadcastApplicationRegistrationEvent({
+ type: 'updated',
+ applicationRegistration: updatedRegistration,
+ });
+ } catch (error) {
+ this.logger.warn(
+ `Failed to reload application registration ${applicationRegistrationId} for broadcast`,
+ error,
+ );
+ }
+ }
+
+ private async broadcastApplicationRegistrationEvent({
+ type,
+ applicationRegistration,
+ }: {
+ type: 'created' | 'updated' | 'deleted';
+ applicationRegistration: ApplicationRegistrationEntity;
+ }): Promise<void> {
+ const { ownerWorkspaceId } = applicationRegistration;
+
+ if (!isDefined(ownerWorkspaceId)) {
+ return;
+ }
+
+ const serializedApplicationRegistration =
+ serializeApplicationRegistrationForBroadcast(applicationRegistration);
+
+ try {
+ await this.workspaceEventBroadcaster.broadcast({
+ workspaceId: ownerWorkspaceId,
+ events: [
+ {
+ type,
+ entityName: 'applicationRegistration',
+ recordId: applicationRegistration.id,
+ properties:
+ type === 'deleted'
+ ? { before: serializedApplicationRegistration }
+ : { after: serializedApplicationRegistration },
+ },
+ ],
+ });
+ } catch (error) {
+ this.logger.warn(
+ `Failed to broadcast ${type} event for application registration ${applicationRegistration.universalIdentifier} in workspace ${ownerWorkspaceId}`,
+ error,
+ );
+ }
+ }
+
// Best-effort: a queue outage must not fail the publish flow that
// triggered the upgrade.
async enqueueAutoUpgradeApplications(
@@ -188,6 +273,7 @@ export class ApplicationRegistrationService {
async setLatestAvailableVersionIfChanged(
applicationRegistrationId: string,
newVersion: string | null,
+ { shouldBroadcastUpdate = true }: { shouldBroadcastUpdate?: boolean } = {},
): Promise<boolean> {
const result = await this.applicationRegistrationRepository
.createQueryBuilder()
@@ -199,7 +285,15 @@ export class ApplicationRegistrationService {
})
.execute();
- return (result.affected ?? 0) > 0;
+ const hasChanged = (result.affected ?? 0) > 0;
+
+ if (hasChanged && shouldBroadcastUpdate) {
+ await this.broadcastApplicationRegistrationUpdatedById(
+ applicationRegistrationId,
+ );
+ }
+
+ return hasChanged;
}
async findMany(
@@ -444,6 +538,11 @@ export class ApplicationRegistrationService {
await this.invalidateMarketplaceAppsCache();
+ await this.broadcastApplicationRegistrationEvent({
+ type: 'created',
+ applicationRegistration: saved,
+ });
+
return { applicationRegistration: saved, clientSecret };
}
@@ -453,9 +552,15 @@ export class ApplicationRegistrationService {
): Promise<ApplicationRegistrationEntity> {
const { id, update } = input;
- await this.findOneById(id, ownerWorkspaceId);
+ const existingRegistration = await this.findOneById(id, ownerWorkspaceId);
+
await this.applyUpdate(id, update);
+ await this.broadcastApplicationRegistrationUpdatedById(
+ id,
+ existingRegistration,
+ );
+
return this.findOneById(id, ownerWorkspaceId);
}
@@ -494,10 +599,12 @@ export class ApplicationRegistrationService {
updateData.isPreInstalled = update.isPreInstalled;
if (isDefined(update.isVetted)) updateData.isVetted = update.isVetted;
- if (Object.keys(updateData).length > 0) {
- await this.applicationRegistrationRepository.update(id, updateData);
- await this.invalidateMarketplaceAppsCache();
+ if (Object.keys(updateData).length === 0) {
+ return;
}
+
+ await this.applicationRegistrationRepository.update(id, updateData);
+ await this.invalidateMarketplaceAppsCache();
}
async updateFromManifest({
@@ -506,6 +613,7 @@ export class ApplicationRegistrationService {
sourceType,
latestAvailableVersion,
preventVersionDowngrade = false,
+ registrationBeforeUpdate,
additionalFields,
}: {
applicationRegistrationId: string;
@@ -514,6 +622,7 @@ export class ApplicationRegistrationService {
// null clears the stored version; undefined leaves it untouched.
latestAvailableVersion?: string | null;
preventVersionDowngrade?: boolean;
+ registrationBeforeUpdate?: ApplicationRegistrationEntity;
additionalFields?: Partial<
Pick<
ApplicationRegistrationEntity,
@@ -588,6 +697,11 @@ export class ApplicationRegistrationService {
await this.invalidateMarketplaceAppsCache();
+ await this.broadcastApplicationRegistrationUpdatedById(
+ applicationRegistrationId,
+ registrationBeforeUpdate ?? existing,
+ );
+
return true;
},
`application-registration-update:${applicationRegistrationId}`,
@@ -596,7 +710,10 @@ export class ApplicationRegistrationService {
}
async delete(id: string, ownerWorkspaceId: string): Promise<boolean> {
- await this.findOneById(id, ownerWorkspaceId);
+ const applicationRegistration = await this.findOneById(
+ id,
+ ownerWorkspaceId,
+ );
// Stored assets (logo, gallery images) go with the registration; deleting
// them first also removes the bytes, which the row FK cascade cannot do.
@@ -613,6 +730,11 @@ export class ApplicationRegistrationService {
await this.invalidateMarketplaceAppsCache();
+ await this.broadcastApplicationRegistrationEvent({
+ type: 'deleted',
+ applicationRegistration,
+ });
+
return true;
}
@@ -670,6 +792,7 @@ export class ApplicationRegistrationService {
const isNewVersion = await this.setLatestAvailableVersionIfChanged(
existing.id,
params.latestAvailableVersion ?? null,
+ { shouldBroadcastUpdate: false },
);
await this.updateFromManifest({
@@ -677,6 +800,7 @@ export class ApplicationRegistrationService {
manifest: params.manifest,
sourceType: params.sourceType,
latestAvailableVersion: params.latestAvailableVersion,
+ registrationBeforeUpdate: existing,
additionalFields: {
name: params.name,
sourcePackage: params.sourcePackage,
@@ -703,6 +827,7 @@ export class ApplicationRegistrationService {
const isNewVersion = await this.setLatestAvailableVersionIfChanged(
existing.id,
params.latestAvailableVersion ?? null,
+ { shouldBroadcastUpdate: false },
);
// A registration first created by a local install (CLI dev / tarball
@@ -727,6 +852,11 @@ export class ApplicationRegistrationService {
await this.invalidateMarketplaceAppsCache();
+ await this.broadcastApplicationRegistrationUpdatedById(
+ existing.id,
+ existing,
+ );
+
if (isNewVersion) {
this.emitRegistrationPublishMetric({
isNewRegistration: false,
@@ -1055,9 +1185,17 @@ export class ApplicationRegistrationService {
await this.invalidateMarketplaceAppsCache();
- return this.applicationRegistrationRepository.findOneOrFail({
- where: { id: registration.id },
+ const claimedRegistration =
+ await this.applicationRegistrationRepository.findOneOrFail({
+ where: { id: registration.id },
+ });
+
+ await this.broadcastApplicationRegistrationEvent({
+ type: 'created',
+ applicationRegistration: claimedRegistration,
});
+
+ return claimedRegistration;
}
async transferOwnership(params: {
@@ -1094,9 +1232,22 @@ export class ApplicationRegistrationService {
await this.invalidateMarketplaceAppsCache();
- return this.applicationRegistrationRepository.findOneOrFail({
- where: { id: registration.id },
+ const transferredRegistration =
+ await this.applicationRegistrationRepository.findOneOrFail({
+ where: { id: registration.id },
+ });
+
+ await this.broadcastApplicationRegistrationEvent({
+ type: 'deleted',
+ applicationRegistration: registration,
+ });
+
+ await this.broadcastApplicationRegistrationEvent({
+ type: 'created',
+ applicationRegistration: transferredRegistration,
});
+
+ return transferredRegistration;
}
private async generateClientSecret(): Promise<{
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/utils/__tests__/serialize-application-registration-for-broadcast.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/utils/__tests__/serialize-application-registration-for-broadcast.util.spec.ts
new file mode 100644
index 00000000000..3a7a2f30fc0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/utils/__tests__/serialize-application-registration-for-broadcast.util.spec.ts
@@ -0,0 +1,58 @@
+import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
+import { serializeApplicationRegistrationForBroadcast } from 'src/engine/core-modules/application/application-registration/utils/serialize-application-registration-for-broadcast.util';
+
+type SerializableApplicationRegistration = Parameters<
+ typeof serializeApplicationRegistrationForBroadcast
+>[0];
+
+const buildApplicationRegistration = (
+ overrides: Partial<SerializableApplicationRegistration> = {},
+): SerializableApplicationRegistration => ({
+ id: 'd0d5f1b2-1f2a-4a2e-9f7b-2f9a0c1d3e44',
+ universalIdentifier: '4a4c1e2f-2a29-4f8f-9a55-2f8d0e2b4c33',
+ name: 'Test registration',
+ latestAvailableVersion: '1.2.0',
+ sourceType: ApplicationRegistrationSourceType.NPM,
+ isListed: true,
+ isVetted: false,
+ ownerWorkspaceId: '6b6f4a95-4a9d-4a53-9a7e-1c7c2f3b5e11',
+ ...overrides,
+});
+
+describe('serializeApplicationRegistrationForBroadcast', () => {
+ it('carries every field the front holds', () => {
+ expect(
+ serializeApplicationRegistrationForBroadcast(
+ buildApplicationRegistration(),
+ ),
+ ).toEqual({
+ id: 'd0d5f1b2-1f2a-4a2e-9f7b-2f9a0c1d3e44',
+ universalIdentifier: '4a4c1e2f-2a29-4f8f-9a55-2f8d0e2b4c33',
+ name: 'Test registration',
+ latestAvailableVersion: '1.2.0',
+ sourceType: ApplicationRegistrationSourceType.NPM,
+ isListed: true,
+ isVetted: false,
+ ownerWorkspaceId: '6b6f4a95-4a9d-4a53-9a7e-1c7c2f3b5e11',
+ });
+ });
+
+ it.each([null, undefined])(
+ 'emits null rather than dropping keys for %p fields',
+ (unsetValue) => {
+ expect(
+ serializeApplicationRegistrationForBroadcast(
+ buildApplicationRegistration({
+ latestAvailableVersion: unsetValue,
+ ownerWorkspaceId: unsetValue,
+ }),
+ ),
+ ).toEqual(
+ expect.objectContaining({
+ latestAvailableVersion: null,
+ ownerWorkspaceId: null,
+ }),
+ );
+ },
+ );
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/utils/serialize-application-registration-for-broadcast.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/utils/serialize-application-registration-for-broadcast.util.ts
new file mode 100644
index 00000000000..2cd88408a5a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/utils/serialize-application-registration-for-broadcast.util.ts
@@ -0,0 +1,27 @@
+import { type ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
+
+type SerializableApplicationRegistration = Pick<
+ ApplicationRegistrationEntity,
+ | 'id'
+ | 'universalIdentifier'
+ | 'name'
+ | 'latestAvailableVersion'
+ | 'sourceType'
+ | 'isListed'
+ | 'isVetted'
+ | 'ownerWorkspaceId'
+>;
+
+export const serializeApplicationRegistrationForBroadcast = (
+ applicationRegistration: SerializableApplicationRegistration,
+) => ({
+ id: applicationRegistration.id,
+ universalIdentifier: applicationRegistration.universalIdentifier,
+ name: applicationRegistration.name,
+ latestAvailableVersion:
+ applicationRegistration.latestAvailableVersion ?? null,
+ sourceType: applicationRegistration.sourceType,
+ isListed: applicationRegistration.isListed,
+ isVetted: applicationRegistration.isVetted,
+ ownerWorkspaceId: applicationRegistration.ownerWorkspaceId ?? null,
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.service.ts b/packages/twenty-server/src/engine/core-modules/application/application.service.ts
index e15f0ee0783..c426ebbe520 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application.service.ts
@@ -28,6 +28,8 @@ import { FrontComponentEntity } from 'src/engine/metadata-modules/front-componen
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
import { logicFunctionCreateHash } from 'src/engine/metadata-modules/logic-function/utils/logic-function-create-hash.utils';
import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
+import { serializeApplicationForBroadcast } from 'src/engine/core-modules/application/utils/serialize-application-for-broadcast.util';
+import { WorkspaceEventBroadcaster } from 'src/engine/subscriptions/workspace-event-broadcaster/workspace-event-broadcaster.service';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@@ -60,6 +62,7 @@ export class ApplicationService {
private readonly objectMetadataRepository: Repository<ObjectMetadataEntity>,
@InjectRepository(ApplicationVariableEntity)
private readonly applicationVariableRepository: Repository<ApplicationVariableEntity>,
+ private readonly workspaceEventBroadcaster: WorkspaceEventBroadcaster,
) {}
async findApplicationRoleId(
@@ -581,6 +584,42 @@ export class ApplicationService {
}
}
+ private async broadcastApplicationEvent({
+ type,
+ application,
+ updatedFields,
+ }: {
+ type: 'created' | 'updated' | 'deleted';
+ application: ApplicationEntity;
+ updatedFields?: string[];
+ }): Promise<void> {
+ const serializedApplication = serializeApplicationForBroadcast(application);
+
+ try {
+ await this.workspaceEventBroadcaster.broadcast({
+ workspaceId: application.workspaceId,
+ events: [
+ {
+ type,
+ entityName: 'application',
+ recordId: application.id,
+ properties: {
+ ...(isDefined(updatedFields) ? { updatedFields } : {}),
+ ...(type === 'deleted'
+ ? { before: serializedApplication }
+ : { after: serializedApplication }),
+ },
+ },
+ ],
+ });
+ } catch (error) {
+ this.logger.warn(
+ `Failed to broadcast ${type} event for application ${application.universalIdentifier} in workspace ${application.workspaceId}`,
+ error,
+ );
+ }
+ }
+
async create(
data: Partial<ApplicationEntity> & { workspaceId: string },
queryRunner?: QueryRunner,
@@ -597,6 +636,11 @@ export class ApplicationService {
'flatApplicationMaps',
]);
+ await this.broadcastApplicationEvent({
+ type: 'created',
+ application: savedApplication,
+ });
+
return savedApplication;
}
@@ -606,13 +650,18 @@ export class ApplicationService {
workspaceId: string;
},
): Promise<ApplicationEntity> {
- await this.applicationRepository.update({ id }, data);
+ await this.applicationRepository.update(
+ { id, workspaceId: data.workspaceId },
+ data,
+ );
await this.workspaceCacheService.invalidateAndRecompute(data.workspaceId, [
'flatApplicationMaps',
]);
- const updatedApplication = await this.findById(id);
+ const updatedApplication = await this.applicationRepository.findOne({
+ where: { id, workspaceId: data.workspaceId },
+ });
if (!isDefined(updatedApplication)) {
throw new ApplicationException(
@@ -621,6 +670,14 @@ export class ApplicationService {
);
}
+ await this.broadcastApplicationEvent({
+ type: 'updated',
+ application: updatedApplication,
+ updatedFields: Object.keys(data).filter(
+ (field) => field !== 'workspaceId',
+ ),
+ });
+
return updatedApplication;
}
@@ -711,5 +768,10 @@ export class ApplicationService {
workspaceId,
ALL_FLAT_ENTITY_MAPS_PROPERTIES,
);
+
+ await this.broadcastApplicationEvent({
+ type: 'deleted',
+ application,
+ });
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/serialize-application-for-broadcast.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/serialize-application-for-broadcast.util.spec.ts
new file mode 100644
index 00000000000..afb1ff3a7a8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/__tests__/serialize-application-for-broadcast.util.spec.ts
@@ -0,0 +1,58 @@
+import { ApplicationState } from 'src/engine/core-modules/application/enums/application-state.enum';
+import { serializeApplicationForBroadcast } from 'src/engine/core-modules/application/utils/serialize-application-for-broadcast.util';
+
+type SerializableApplication = Parameters<
+ typeof serializeApplicationForBroadcast
+>[0];
+
+const buildApplication = (
+ overrides: Partial<SerializableApplication> = {},
+): SerializableApplication => ({
+ id: 'a2f6b0a5-0f4a-4f9f-9f0c-6c2d5f0f4a11',
+ universalIdentifier: '4a4c1e2f-2a29-4f8f-9a55-2f8d0e2b4c33',
+ name: 'Test application',
+ description: 'A test application',
+ version: '1.0.0',
+ state: ApplicationState.INSTALLING,
+ applicationRegistrationId: 'ce4b7b8e-9e5b-4b7c-bd7a-5f2f61f0a9d2',
+ sdkClientCoreChecksum: 'checksum',
+ ...overrides,
+});
+
+describe('serializeApplicationForBroadcast', () => {
+ it('carries every field the front holds', () => {
+ expect(serializeApplicationForBroadcast(buildApplication())).toEqual({
+ id: 'a2f6b0a5-0f4a-4f9f-9f0c-6c2d5f0f4a11',
+ universalIdentifier: '4a4c1e2f-2a29-4f8f-9a55-2f8d0e2b4c33',
+ name: 'Test application',
+ description: 'A test application',
+ version: '1.0.0',
+ state: ApplicationState.INSTALLING,
+ applicationRegistrationId: 'ce4b7b8e-9e5b-4b7c-bd7a-5f2f61f0a9d2',
+ sdkClientCoreChecksum: 'checksum',
+ });
+ });
+
+ it.each([null, undefined])(
+ 'emits null rather than dropping keys for %p fields',
+ (unsetValue) => {
+ const serializedApplication = serializeApplicationForBroadcast(
+ buildApplication({
+ description: unsetValue,
+ version: unsetValue,
+ applicationRegistrationId: unsetValue,
+ sdkClientCoreChecksum: unsetValue,
+ }),
+ );
+
+ expect(serializedApplication).toEqual(
+ expect.objectContaining({
+ description: null,
+ version: null,
+ applicationRegistrationId: null,
+ sdkClientCoreChecksum: null,
+ }),
+ );
+ },
+ );
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/utils/serialize-application-for-broadcast.util.ts b/packages/twenty-server/src/engine/core-modules/application/utils/serialize-application-for-broadcast.util.ts
new file mode 100644
index 00000000000..59004f81500
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/utils/serialize-application-for-broadcast.util.ts
@@ -0,0 +1,26 @@
+import { type ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
+
+type SerializableApplication = Pick<
+ ApplicationEntity,
+ | 'id'
+ | 'universalIdentifier'
+ | 'name'
+ | 'description'
+ | 'version'
+ | 'state'
+ | 'applicationRegistrationId'
+ | 'sdkClientCoreChecksum'
+>;
+
+export const serializeApplicationForBroadcast = (
+ application: SerializableApplication,
+) => ({
+ id: application.id,
+ universalIdentifier: application.universalIdentifier,
+ name: application.name,
+ description: application.description ?? null,
+ version: application.version ?? null,
+ state: application.state,
+ applicationRegistrationId: application.applicationRegistrationId ?? null,
+ sdkClientCoreChecksum: application.sdkClientCoreChecksum ?? null,
+});
diff --git a/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-generation.service.ts b/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-generation.service.ts
index bdf887fdef6..cd4055f16fb 100644
--- a/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-generation.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/sdk-client/sdk-client-generation.service.ts
@@ -11,8 +11,11 @@ import { FileFolder } from 'twenty-shared/types';
import { Repository } from 'typeorm';
import { WorkspaceSchemaFactory } from 'src/engine/api/graphql/workspace-schema.factory';
-import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
import { createZipFile } from 'src/engine/core-modules/logic-function/logic-function-drivers/utils/create-zip-file';
import { TemporaryDirManager } from 'src/engine/core-modules/logic-function/logic-function-drivers/utils/temporary-dir-manager';
@@ -34,8 +37,6 @@ import {
import { type SdkClientGenerationTrigger } from 'src/engine/core-modules/sdk-client/types/sdk-client-generation-trigger.type';
import { fromWorkspaceEntityToFlat } from 'src/engine/core-modules/workspace/utils/from-workspace-entity-to-flat.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
-import { WorkspaceEventBroadcaster } from 'src/engine/subscriptions/workspace-event-broadcaster/workspace-event-broadcaster.service';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
const SDK_CLIENT_ARCHIVE_NAME = 'twenty-client-sdk.zip';
const SDK_CLIENT_GENERATION_RETRY_LIMIT = 3;
@@ -46,16 +47,12 @@ export class SdkClientGenerationService {
constructor(
private readonly fileStorageService: FileStorageService,
- @InjectRepository(ApplicationEntity)
- private readonly applicationRepository: Repository<ApplicationEntity>,
@InjectRepository(WorkspaceEntity)
private readonly workspaceRepository: Repository<WorkspaceEntity>,
- private readonly workspaceCacheService: WorkspaceCacheService,
private readonly workspaceSchemaFactory: WorkspaceSchemaFactory,
private readonly applicationService: ApplicationService,
@InjectMessageQueue(MessageQueue.workspaceQueue)
private readonly messageQueueService: MessageQueueService,
- private readonly workspaceEventBroadcaster: WorkspaceEventBroadcaster,
private readonly metricsService: MetricsService,
) {}
@@ -222,21 +219,10 @@ export class SdkClientGenerationService {
settings: { isTemporaryFile: false, toDelete: false },
});
- await this.applicationRepository.update(
- { id: applicationId, workspaceId },
- {
- isSdkLayerStale: true,
- sdkClientCoreChecksum,
- },
- );
-
- await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
- 'flatApplicationMaps',
- ]);
-
- await this.broadcastSdkClientCoreChecksumUpdate({
+ await this.storeSdkClientCoreChecksum({
workspaceId,
applicationId,
+ applicationUniversalIdentifier,
sdkClientCoreChecksum,
});
@@ -251,38 +237,36 @@ export class SdkClientGenerationService {
}
}
- private async broadcastSdkClientCoreChecksumUpdate({
+ private async storeSdkClientCoreChecksum({
workspaceId,
applicationId,
+ applicationUniversalIdentifier,
sdkClientCoreChecksum,
}: {
workspaceId: string;
applicationId: string;
+ applicationUniversalIdentifier: string;
sdkClientCoreChecksum: string;
}): Promise<void> {
try {
- await this.workspaceEventBroadcaster.broadcast({
+ await this.applicationService.update(applicationId, {
+ isSdkLayerStale: true,
+ sdkClientCoreChecksum,
workspaceId,
- events: [
- {
- type: 'updated',
- entityName: 'application',
- recordId: applicationId,
- properties: {
- updatedFields: ['sdkClientCoreChecksum'],
- after: {
- id: applicationId,
- sdkClientCoreChecksum,
- },
- },
- },
- ],
});
} catch (error) {
- this.logger.warn(
- `Failed to broadcast SDK client core checksum update for application ${applicationId} in workspace ${workspaceId}`,
- error,
- );
+ if (
+ error instanceof ApplicationException &&
+ error.code === ApplicationExceptionCode.APPLICATION_NOT_FOUND
+ ) {
+ this.logger.warn(
+ `Skipped SDK client checksum write for application ${applicationUniversalIdentifier} in workspace ${workspaceId}: the application no longer exists`,
+ );
+
+ return;
+ }
+
+ throw error;
}
}
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/find-records-relation-traversal-workflow.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/find-records-relation-traversal-workflow.integration-spec.ts
index de2621ccda9..8026a28d8d1 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/find-records-relation-traversal-workflow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/find-records-relation-traversal-workflow.integration-spec.ts
@@ -10,6 +10,7 @@ import {
waitForWorkflowCompletion,
} from 'test/integration/graphql/suites/workflow/utils/workflow-run-test.util';
import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { isDefined } from 'twenty-shared/utils';
import { v4 as uuidv4 } from 'uuid';
const client = request(`http://localhost:${APP_PORT}`);
@@ -350,10 +351,23 @@ describe('FindRecords workflow action with relation-traversal filter (e2e)', ()
const result = workflowRun?.state?.stepInfos?.[findRecordsStepId!]
?.result as
- | { all?: Array<{ id: string }>; totalCount?: number | string }
+ | {
+ all?: Array<{ id: string; companyId: string | null }>;
+ totalCount?: number | string;
+ }
| undefined;
- expect(result?.all).toEqual([]);
- expect(Number(result?.totalCount)).toBe(0);
+ const returnedRecords = result?.all;
+
+ expect(Array.isArray(returnedRecords)).toBe(true);
+ expect(Number.isFinite(Number(result?.totalCount))).toBe(true);
+
+ // An empty filter value can only match people with no company, and other
+ // specs sharing the database seed those, so assert the shape rather than []
+ const returnedCompanyIds = (returnedRecords ?? []).map(
+ (record) => record.companyId,
+ );
+
+ expect(returnedCompanyIds.filter(isDefined)).toEqual([]);
});
});
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/application-broadcast-events.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/application-broadcast-events.integration-spec.ts
new file mode 100644
index 00000000000..47ce1089c5b
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/application-broadcast-events.integration-spec.ts
@@ -0,0 +1,198 @@
+import gql from 'graphql-tag';
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import { uninstallApplication } from 'test/integration/metadata/suites/application/utils/uninstall-application.util';
+import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { v4 as uuidv4 } from 'uuid';
+
+import { type WorkspaceBroadcastEvent } from 'src/engine/subscriptions/workspace-event-broadcaster/types/workspace-broadcast-event.type';
+import { type WorkspaceEventBroadcaster } from 'src/engine/subscriptions/workspace-event-broadcaster/workspace-event-broadcaster.service';
+
+const APPLICATION_PAYLOAD_KEYS = [
+ 'applicationRegistrationId',
+ 'description',
+ 'id',
+ 'name',
+ 'sdkClientCoreChecksum',
+ 'state',
+ 'universalIdentifier',
+ 'version',
+];
+
+const APPLICATION_REGISTRATION_PAYLOAD_KEYS = [
+ 'id',
+ 'isListed',
+ 'isVetted',
+ 'latestAvailableVersion',
+ 'name',
+ 'ownerWorkspaceId',
+ 'sourceType',
+ 'universalIdentifier',
+];
+
+describe('Application broadcast events', () => {
+ let appId: string;
+ let roleId: string;
+ let broadcastSpy: jest.SpyInstance;
+
+ const eventsFor = (
+ entityName: string,
+ type: WorkspaceBroadcastEvent['type'],
+ ): WorkspaceBroadcastEvent[] =>
+ broadcastSpy.mock.calls
+ .flatMap(([{ events }]) => events)
+ .filter(
+ (event) => event.entityName === entityName && event.type === type,
+ );
+
+ beforeEach(async () => {
+ appId = uuidv4();
+ roleId = uuidv4();
+
+ const workspaceEventBroadcaster =
+ getAppProviderByClassName<WorkspaceEventBroadcaster>(
+ 'WorkspaceEventBroadcaster',
+ );
+
+ broadcastSpy = jest
+ .spyOn(workspaceEventBroadcaster, 'broadcast')
+ .mockResolvedValue(undefined);
+
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: appId,
+ name: 'Broadcast test application',
+ description: 'App for testing lifecycle broadcasts',
+ sourcePath: 'test-broadcast-events',
+ });
+ }, 60000);
+
+ afterEach(async () => {
+ broadcastSpy.mockRestore();
+
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: appId,
+ });
+ });
+
+ it('broadcasts the registration and application rows through their lifecycle', async () => {
+ const registrationCreatedEvent = eventsFor(
+ 'applicationRegistration',
+ 'created',
+ ).find(
+ (event) =>
+ (event.properties.after as { universalIdentifier?: string })
+ ?.universalIdentifier === appId,
+ );
+
+ expect(registrationCreatedEvent).toBeDefined();
+ expect(
+ Object.keys(registrationCreatedEvent?.properties.after ?? {}).sort(),
+ ).toEqual(APPLICATION_REGISTRATION_PAYLOAD_KEYS);
+ expect(registrationCreatedEvent?.properties.after).toMatchObject({
+ name: 'Broadcast test application',
+ });
+
+ const applicationCreatedEvent = eventsFor('application', 'created').find(
+ (event) =>
+ (event.properties.after as { universalIdentifier?: string })
+ ?.universalIdentifier === appId,
+ );
+
+ expect(applicationCreatedEvent).toBeDefined();
+ expect(
+ Object.keys(applicationCreatedEvent?.properties.after ?? {}).sort(),
+ ).toEqual(APPLICATION_PAYLOAD_KEYS);
+ expect(applicationCreatedEvent?.properties.after).toMatchObject({
+ id: applicationCreatedEvent?.recordId,
+ name: 'Broadcast test application',
+ state: expect.any(String),
+ });
+
+ const applicationRegistrationId = registrationCreatedEvent?.recordId;
+
+ broadcastSpy.mockClear();
+
+ const updateRegistrationResponse = await makeMetadataAPIRequest({
+ query: gql`
+ mutation UpdateApplicationRegistration(
+ $input: UpdateApplicationRegistrationInput!
+ ) {
+ updateApplicationRegistration(input: $input) {
+ id
+ }
+ }
+ `,
+ variables: {
+ input: {
+ id: applicationRegistrationId,
+ update: { name: 'Broadcast test application renamed' },
+ },
+ },
+ });
+
+ expect(updateRegistrationResponse.body.errors).toBeUndefined();
+
+ const registrationUpdatedEvents = eventsFor(
+ 'applicationRegistration',
+ 'updated',
+ ).filter((event) => event.recordId === applicationRegistrationId);
+
+ expect(registrationUpdatedEvents).toHaveLength(1);
+ expect(
+ Object.keys(registrationUpdatedEvents[0].properties.after ?? {}).sort(),
+ ).toEqual(APPLICATION_REGISTRATION_PAYLOAD_KEYS);
+ expect(registrationUpdatedEvents[0].properties.after).toMatchObject({
+ name: 'Broadcast test application renamed',
+ });
+
+ broadcastSpy.mockClear();
+
+ await syncApplication({
+ manifest: buildBaseManifest({ appId, roleId }),
+ expectToFail: false,
+ });
+
+ const applicationUpdatedEvents = eventsFor('application', 'updated');
+
+ expect(
+ applicationUpdatedEvents.some(
+ (event) =>
+ (event.properties.after as { universalIdentifier?: string })
+ ?.universalIdentifier === appId,
+ ),
+ ).toBe(true);
+
+ for (const applicationUpdatedEvent of applicationUpdatedEvents) {
+ expect(
+ Object.keys(applicationUpdatedEvent.properties.after ?? {}).sort(),
+ ).toEqual(APPLICATION_PAYLOAD_KEYS);
+ expect(applicationUpdatedEvent.properties.updatedFields).toEqual(
+ expect.arrayContaining([expect.any(String)]),
+ );
+ expect(applicationUpdatedEvent.properties.updatedFields).not.toContain(
+ 'workspaceId',
+ );
+ }
+
+ broadcastSpy.mockClear();
+
+ await uninstallApplication({
+ universalIdentifier: appId,
+ expectToFail: false,
+ });
+
+ const applicationDeletedEvent = eventsFor('application', 'deleted').find(
+ (event) =>
+ (event.properties.before as { universalIdentifier?: string })
+ ?.universalIdentifier === appId,
+ );
+
+ expect(applicationDeletedEvent).toBeDefined();
+ expect(
+ Object.keys(applicationDeletedEvent?.properties.before ?? {}).sort(),
+ ).toEqual(APPLICATION_PAYLOAD_KEYS);
+ }, 60000);
+});