The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Keep finished workflow runs from being reverted by older query responses (#27972)
Thomas Trompette8ef56208b1b3
diff --git a/packages/twenty-front/src/modules/object-metadata/components/ApolloCoreProvider.tsx b/packages/twenty-front/src/modules/object-metadata/components/ApolloCoreProvider.tsxindex 11595b73a15..67884c505a4 100644--- a/packages/twenty-front/src/modules/object-metadata/components/ApolloCoreProvider.tsx+++ b/packages/twenty-front/src/modules/object-metadata/components/ApolloCoreProvider.tsx@@ -1,13 +1,16 @@import { useApolloFactory } from '@/apollo/hooks/useApolloFactory';import { ApolloCoreClientContext } from '@/object-metadata/contexts/ApolloCoreClientContext';+import { workflowRunStaleResponseLink } from '@/workflow/utils/workflowRunStaleResponseLink';export const ApolloCoreProvider = ({children,}: {children: React.ReactNode;}) => {- const apolloCoreClient = useApolloFactory();+ const apolloCoreClient = useApolloFactory({+ extraLinks: [workflowRunStaleResponseLink],+ });return (<ApolloCoreClientContext.Provider value={apolloCoreClient}>diff --git a/packages/twenty-front/src/modules/workflow/hooks/useWorkflowRunStepLog.ts b/packages/twenty-front/src/modules/workflow/hooks/useWorkflowRunStepLog.tsindex 4e819e6f35c..a228322eb14 100644--- a/packages/twenty-front/src/modules/workflow/hooks/useWorkflowRunStepLog.ts+++ b/packages/twenty-front/src/modules/workflow/hooks/useWorkflowRunStepLog.ts@@ -16,7 +16,7 @@ export const useWorkflowRunStepLog = ({>({objectNameSingular: CoreObjectNameSingular.WorkflowRun,objectRecordId: workflowRunId,- recordGqlFields: { id: true, stepLogs: true },+ recordGqlFields: { id: true, stepLogs: true, updatedAt: true },skip,});diff --git a/packages/twenty-front/src/modules/workflow/utils/__tests__/workflowRunStaleResponseLink.test.ts b/packages/twenty-front/src/modules/workflow/utils/__tests__/workflowRunStaleResponseLink.test.tsnew file mode 100644index 00000000000..2b7c3579731--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/utils/__tests__/workflowRunStaleResponseLink.test.ts@@ -0,0 +1,186 @@+import {+ ApolloClient,+ ApolloLink,+ gql,+ InMemoryCache,+ Observable,+} from '@apollo/client';++import { workflowRunStaleResponseLink } from '@/workflow/utils/workflowRunStaleResponseLink';++const FIND_ONE_WORKFLOW_RUN = gql`+ query FindOneWorkflowRun($objectRecordId: UUID!) {+ workflowRun(filter: { id: { eq: $objectRecordId } }) {+ id+ status+ stepLogs+ updatedAt+ }+ }+`;++const FIND_ONE_COMPANY = gql`+ query FindOneCompany($objectRecordId: UUID!) {+ company(filter: { id: { eq: $objectRecordId } }) {+ id+ name+ updatedAt+ }+ }+`;++const RUNNING_AT = '2026-10-13T10:00:01.000Z';+const COMPLETED_AT = '2026-10-13T10:00:02.000Z';++const setup = ({ response }: { response: Record<string, unknown> }) => {+ const client = new ApolloClient({+ cache: new InMemoryCache(),+ link: ApolloLink.from([+ workflowRunStaleResponseLink,+ new ApolloLink(+ () =>+ new Observable((observer) => {+ observer.next({ data: response });+ observer.complete();+ }),+ ),+ ]),+ });++ client.cache.writeQuery({+ query: FIND_ONE_WORKFLOW_RUN,+ variables: { objectRecordId: 'run-1' },+ data: {+ workflowRun: {+ __typename: 'WorkflowRun',+ id: 'run-1',+ status: 'COMPLETED',+ stepLogs: { 'step-1': 'completed' },+ updatedAt: COMPLETED_AT,+ },+ },+ });++ client.cache.writeQuery({+ query: FIND_ONE_COMPANY,+ variables: { objectRecordId: 'company-1' },+ data: {+ company: {+ __typename: 'Company',+ id: 'company-1',+ name: 'Apple',+ updatedAt: COMPLETED_AT,+ },+ },+ });++ return { client };+};++const queryWorkflowRun = async ({ client }: { client: ApolloClient }) => {+ const { data } = await client.query<{+ workflowRun: Record<string, unknown>;+ }>({+ query: FIND_ONE_WORKFLOW_RUN,+ variables: { objectRecordId: 'run-1' },+ fetchPolicy: 'network-only',+ });++ return data?.workflowRun;+};++describe('workflowRunStaleResponseLink', () => {+ it('should keep the cached run when an older response lands after it', async () => {+ const { client } = setup({+ response: {+ workflowRun: {+ __typename: 'WorkflowRun',+ id: 'run-1',+ status: 'RUNNING',+ stepLogs: { 'step-1': 'running' },+ updatedAt: RUNNING_AT,+ },+ },+ });++ expect(await queryWorkflowRun({ client })).toMatchObject({+ status: 'COMPLETED',+ stepLogs: { 'step-1': 'completed' },+ updatedAt: COMPLETED_AT,+ });+ });++ it('should keep a cached null value when an older response has one set', async () => {+ const { client } = setup({+ response: {+ workflowRun: {+ __typename: 'WorkflowRun',+ id: 'run-1',+ status: 'FAILED',+ stepLogs: { 'step-1': 'failed' },+ updatedAt: COMPLETED_AT,+ },+ },+ });++ client.cache.writeQuery({+ query: FIND_ONE_WORKFLOW_RUN,+ variables: { objectRecordId: 'run-1' },+ data: {+ workflowRun: {+ __typename: 'WorkflowRun',+ id: 'run-1',+ status: 'RUNNING',+ stepLogs: null,+ updatedAt: '2026-10-13T10:00:03.000Z',+ },+ },+ });++ expect(await queryWorkflowRun({ client })).toMatchObject({+ status: 'RUNNING',+ stepLogs: null,+ });+ });++ it('should let a newer run response through', async () => {+ const { client } = setup({+ response: {+ workflowRun: {+ __typename: 'WorkflowRun',+ id: 'run-1',+ status: 'FAILED',+ stepLogs: { 'step-1': 'failed' },+ updatedAt: '2026-10-13T10:00:03.000Z',+ },+ },+ });++ expect(await queryWorkflowRun({ client })).toMatchObject({+ status: 'FAILED',+ });+ });++ it('should leave other objects untouched', async () => {+ const { client } = setup({+ response: {+ company: {+ __typename: 'Company',+ id: 'company-1',+ name: 'Apple Inc',+ updatedAt: RUNNING_AT,+ },+ },+ });++ const { data } = await client.query<{+ company: Record<string, unknown>;+ }>({+ query: FIND_ONE_COMPANY,+ variables: { objectRecordId: 'company-1' },+ fetchPolicy: 'network-only',+ });++ expect(data?.company.name).toBe('Apple Inc');+ });+});diff --git a/packages/twenty-front/src/modules/workflow/utils/workflowRunStaleResponseLink.ts b/packages/twenty-front/src/modules/workflow/utils/workflowRunStaleResponseLink.tsnew file mode 100644index 00000000000..8f7ba7f4f2e--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/utils/workflowRunStaleResponseLink.ts@@ -0,0 +1,158 @@+import { ApolloLink, gql } from '@apollo/client';+import { type ApolloCache } from '@apollo/client/cache';+import { isNonEmptyString, isUndefined } from '@sniptt/guards';+import { parse } from 'graphql';+import { map } from 'rxjs';+import { isDefined, isPlainObject } from 'twenty-shared/utils';++const WORKFLOW_RUN_TYPENAME = 'WorkflowRun';++const CACHED_WORKFLOW_RUN_UPDATED_AT_FRAGMENT = gql`+ fragment CachedWorkflowRunUpdatedAt on WorkflowRun {+ updatedAt+ }+`;++const isGraphqlObject = (value: unknown): value is Record<string, unknown> =>+ isPlainObject(value) && isNonEmptyString(value.__typename);++const isPlainFieldValue = (value: unknown) =>+ !isGraphqlObject(value) &&+ !(Array.isArray(value) && value.some(isGraphqlObject));++const keepNewerCachedFields = ({+ workflowRun,+ cache,+}: {+ workflowRun: Record<string, unknown>;+ cache: ApolloCache;+}) => {+ if (+ !isNonEmptyString(workflowRun.id) ||+ !isNonEmptyString(workflowRun.updatedAt)+ ) {+ return workflowRun;+ }++ const cacheId = `${WORKFLOW_RUN_TYPENAME}:${workflowRun.id}`;++ const cachedUpdatedAt = cache.readFragment<{ updatedAt?: string }>({+ id: cacheId,+ fragment: CACHED_WORKFLOW_RUN_UPDATED_AT_FRAGMENT,+ })?.updatedAt;++ if (+ !isNonEmptyString(cachedUpdatedAt) ||+ Date.parse(cachedUpdatedAt) <= Date.parse(workflowRun.updatedAt)+ ) {+ return workflowRun;+ }++ const plainFieldNames = Object.keys(workflowRun).filter(+ (fieldName) =>+ fieldName !== '__typename' &&+ fieldName !== 'id' &&+ isPlainFieldValue(workflowRun[fieldName]),+ );++ const cachedWorkflowRun = cache.readFragment<Record<string, unknown>>({+ id: cacheId,+ fragment: parse(+ `fragment CachedWorkflowRunFields on ${WORKFLOW_RUN_TYPENAME} { ${plainFieldNames.join(' ')} }`,+ ),+ returnPartialData: true,+ });++ if (!isDefined(cachedWorkflowRun)) {+ return workflowRun;+ }++ return {+ ...workflowRun,+ ...Object.fromEntries(+ plainFieldNames+ .filter((fieldName) => !isUndefined(cachedWorkflowRun[fieldName]))+ .map((fieldName) => [fieldName, cachedWorkflowRun[fieldName]]),+ ),+ };+};++const keepNewerCachedWorkflowRunsInFields = ({+ node,+ cache,+}: {+ node: Record<string, unknown>;+ cache: ApolloCache;+}) => {+ const patchedEntries = Object.entries(node).map(+ ([fieldName, fieldValue]) =>+ [+ fieldName,+ keepNewerCachedWorkflowRuns({ value: fieldValue, cache }),+ ] as const,+ );++ return patchedEntries.some(+ ([fieldName, patchedFieldValue]) => patchedFieldValue !== node[fieldName],+ )+ ? Object.fromEntries(patchedEntries)+ : node;+};++const keepNewerCachedWorkflowRuns = ({+ value,+ cache,+}: {+ value: unknown;+ cache: ApolloCache;+}): unknown => {+ if (Array.isArray(value)) {+ const patchedItems = value.map((item) =>+ keepNewerCachedWorkflowRuns({ value: item, cache }),+ );++ return patchedItems.some((item, index) => item !== value[index])+ ? patchedItems+ : value;+ }++ if (!isGraphqlObject(value)) {+ return value;+ }++ return keepNewerCachedWorkflowRunsInFields({+ node:+ value.__typename === WORKFLOW_RUN_TYPENAME+ ? keepNewerCachedFields({ workflowRun: value, cache })+ : value,+ cache,+ });+};++export const workflowRunStaleResponseLink = new ApolloLink(+ (operation, forward) => {+ if (+ !isNonEmptyString(operation.operationName) ||+ !operation.operationName.includes(WORKFLOW_RUN_TYPENAME)+ ) {+ return forward(operation);+ }++ return forward(operation).pipe(+ map((result) => {+ if (!isPlainObject(result.data)) {+ return result;+ }++ const patchedData = keepNewerCachedWorkflowRunsInFields({+ node: result.data,+ cache: operation.client.cache,+ });++ return patchedData === result.data+ ? result+ : { ...result, data: patchedData };+ }),+ );+ },+);diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep.tsindex 788beabcda6..0000b94e068 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep.ts@@ -31,6 +31,7 @@ export const useSubmitFormStep = ({status: true,startedAt: true,endedAt: true,+ updatedAt: true,},},);