Skip to content

The open alternative to Salesforce, designed for AI.

fix: keep chats and forms usable during workspace upgrades (#27005)

Félix Malfaitc5b6dee7e82a
diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.ts
index 8804553e9b3..4ee4eae49a3 100644
--- a/packages/twenty-front/src/generated/graphql.ts
+++ b/packages/twenty-front/src/generated/graphql.ts
@@ -1509,6 +1509,13 @@ export type StopWorkflowRunMutationVariables = Exact<{
export type StopWorkflowRunMutation = { __typename?: 'Mutation', stopWorkflowRun: { __typename: 'WorkflowRun', id: any, status: WorkflowRunStatusEnum } };
+export type SubmitFormStepMutationVariables = Exact<{
+ input: SubmitFormStepInput;
+}>;
+
+
+export type SubmitFormStepMutation = { __typename?: 'Mutation', submitFormStep: boolean };
+
export type UpdateWorkflowRunStepMutationVariables = Exact<{
input: UpdateWorkflowRunStepInput;
}>;
@@ -1608,6 +1615,7 @@ export const DuplicateWorkflowVersionStepDocument = {"kind":"Document","definiti
export const RetryWorkflowRunDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RetryWorkflowRun"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workflowRunId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"retryWorkflowRun"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workflowRunId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workflowRunId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"__typename"}}]}}]}}]} as unknown as DocumentNode<RetryWorkflowRunMutation, RetryWorkflowRunMutationVariables>;
export const RunWorkflowVersionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RunWorkflowVersion"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"RunWorkflowVersionInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"runWorkflowVersion"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workflowRunId"}}]}}]}}]} as unknown as DocumentNode<RunWorkflowVersionMutation, RunWorkflowVersionMutationVariables>;
export const StopWorkflowRunDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"StopWorkflowRun"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workflowRunId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stopWorkflowRun"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workflowRunId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workflowRunId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"__typename"}}]}}]}}]} as unknown as DocumentNode<StopWorkflowRunMutation, StopWorkflowRunMutationVariables>;
+export const SubmitFormStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SubmitFormStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SubmitFormStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"submitFormStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<SubmitFormStepMutation, SubmitFormStepMutationVariables>;
export const UpdateWorkflowRunStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowRunStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowRunStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowRunStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"nextStepIds"}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"x"}},{"kind":"Field","name":{"kind":"Name","value":"y"}}]}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowRunStepMutation, UpdateWorkflowRunStepMutationVariables>;
export const UpdateWorkflowVersionStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowVersionStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowVersionStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowVersionStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"nextStepIds"}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"x"}},{"kind":"Field","name":{"kind":"Name","value":"y"}}]}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowVersionStepMutation, UpdateWorkflowVersionStepMutationVariables>;
export const UpdateWorkflowVersionTriggerDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowVersionTrigger"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowVersionTriggerInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowVersionTrigger"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"trigger"}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowVersionTriggerMutation, UpdateWorkflowVersionTriggerMutationVariables>;
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx
index 046b5d0d776..50dd73853ba 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx
@@ -1,16 +1,28 @@
import { useLingui } from '@lingui/react/macro';
+import { isDefined } from 'twenty-shared/utils';
import { useIsMobile } from 'twenty-ui/utilities';
import { AiChatCloseButton } from '@/ai/components/AiChatCloseButton';
+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { currentAiChatThreadDataSelector } from '@/ai/states/selectors/currentAiChatThreadDataSelector';
import { PageCardHeader } from '@/ui/layout/page/components/PageCardHeader';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
export const AiChatPageHeader = () => {
const { t } = useLingui();
const isMobile = useIsMobile();
+ const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
+ const currentAiChatThreadData = useAtomStateValue(
+ currentAiChatThreadDataSelector,
+ );
return (
<PageCardHeader
- title={t`New chat`}
+ title={
+ isDefined(currentAiChatThread)
+ ? (currentAiChatThreadData?.title ?? t`Chat`)
+ : t`New chat`
+ }
actionButton={isMobile ? <AiChatCloseButton /> : undefined}
/>
);
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsx
index f46c752f751..8a81baede63 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsx
@@ -1,6 +1,14 @@
import { i18n } from '@lingui/core';
import { I18nProvider } from '@lingui/react';
import { render, screen } from '@testing-library/react';
+import { Provider } from 'jotai';
+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';
+import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
import { type ReactNode } from 'react';
import { SOURCE_LOCALE } from 'twenty-shared/translations';
@@ -15,6 +23,32 @@ jest.mock('@/ui/layout/page/components/PageCardHeader', () => ({
}));
describe('AiChatPageHeader', () => {
+ beforeEach(() => resetJotaiStore());
+
+ it('keeps the saved conversation title on the default chat surface', () => {
+ jotaiStore.set(currentAiChatThreadState.atom, 'thread-id');
+ jotaiStore.set(agentChatThreadListState.atom, {
+ threadIds: ['thread-id'],
+ hasNextPage: false,
+ endCursor: null,
+ });
+ jotaiStore.set(recordStoreFamilyState.atomFamily('thread-id'), {
+ id: 'thread-id',
+ __typename: 'AgentChatThread',
+ title: 'Existing conversation',
+ });
+
+ render(
+ <Provider store={jotaiStore}>
+ <I18nProvider i18n={i18n}>
+ <AiChatPageHeader />
+ </I18nProvider>
+ </Provider>,
+ );
+
+ expect(screen.getByText('Existing conversation')).toBeVisible();
+ });
+
it('titles the page of a chat that has no record yet', () => {
render(
<I18nProvider i18n={i18n}>
diff --git a/packages/twenty-front/src/modules/workflow/graphql/mutations/submitFormStep.ts b/packages/twenty-front/src/modules/workflow/graphql/mutations/submitFormStep.ts
new file mode 100644
index 00000000000..a8ad41b7718
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/graphql/mutations/submitFormStep.ts
@@ -0,0 +1,7 @@
+import { gql } from '@apollo/client';
+
+export const SUBMIT_FORM_STEP = gql`
+ mutation SubmitFormStep($input: SubmitFormStepInput!) {
+ submitFormStep(input: $input)
+ }
+`;
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/__stories__/WorkflowFormStepSubmitButton.stories.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/__stories__/WorkflowFormStepSubmitButton.stories.tsx
new file mode 100644
index 00000000000..babff67d2c7
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/__stories__/WorkflowFormStepSubmitButton.stories.tsx
@@ -0,0 +1,182 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { graphql, HttpResponse } from 'msw';
+import { useState } from 'react';
+import { expect, userEvent, within } from 'storybook/test';
+import { Toaster } from 'twenty-ui/components';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { useWorkflowRun } from '@/workflow/hooks/useWorkflowRun';
+import { WorkflowFormStepSubmitButton } from '@/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepSubmitButton';
+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';
+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';
+import { WorkspaceDecorator } from '~/testing/decorators/WorkspaceDecorator';
+import { graphqlMocks } from '~/testing/graphqlMocks';
+import { oneSucceededWorkflowRunQueryResult } from '~/testing/mock-data/workflow-run';
+import { mockedApolloCoreClient } from '~/testing/mockedApolloCoreClient';
+import { mockedApolloClient } from '~/testing/mockedApolloClient';
+
+const WORKFLOW_RUN_ID = oneSucceededWorkflowRunQueryResult.workflowRun.id;
+const STEP_ID = '212a171a-f887-4213-8892-e39c2a3ecc30';
+const THREAD_ID = 'a19e36a1-e3bb-4fa0-8317-79c7e938849e';
+
+const FormSubmission = () => {
+ const [isSubmitted, setIsSubmitted] = useState(false);
+ const workflowRun = useWorkflowRun({ workflowRunId: WORKFLOW_RUN_ID });
+
+ if (isSubmitted) {
+ return <div>Form submitted</div>;
+ }
+
+ if (!workflowRun) {
+ return <div>Loading form</div>;
+ }
+
+ return (
+ <>
+ <WorkflowFormStepSubmitButton
+ workflowRunId={WORKFLOW_RUN_ID}
+ stepId={STEP_ID}
+ disabled={false}
+ getResponse={async () => ({ name: 'Tim' })}
+ onSubmitted={() => setIsSubmitted(true)}
+ />
+ <Toaster />
+ </>
+ );
+};
+
+const createHandlers = ({
+ threadId,
+ errorCode,
+}: {
+ threadId?: string;
+ errorCode?: string;
+} = {}) => [
+ graphql.query('FindOneWorkflowRun', () =>
+ HttpResponse.json({
+ data: {
+ workflowRun: {
+ ...oneSucceededWorkflowRunQueryResult.workflowRun,
+ status: 'RUNNING',
+ endedAt: null,
+ enqueuedAt: null,
+ updatedBy: null,
+ createdBy: {
+ ...oneSucceededWorkflowRunQueryResult.workflowRun.createdBy,
+ context: { provider: null },
+ },
+ state: {
+ ...oneSucceededWorkflowRunQueryResult.workflowRun.state,
+ stepInfos: { [STEP_ID]: { status: 'PENDING', threadId } },
+ },
+ },
+ },
+ }),
+ ),
+ graphql.mutation(threadId ? 'AnswerToolCall' : 'SubmitFormStep', () =>
+ HttpResponse.json(
+ errorCode
+ ? {
+ errors: [
+ {
+ message: 'Unable to submit form',
+ extensions: {
+ code: errorCode,
+ userFriendlyMessage: 'Unable to submit form',
+ },
+ },
+ ],
+ }
+ : {
+ data: threadId
+ ? {
+ answerToolCall: {
+ __typename: 'AnswerToolCallResult',
+ streamId: null,
+ },
+ }
+ : { submitFormStep: true },
+ },
+ ),
+ ),
+ ...graphqlMocks.handlers,
+];
+
+const meta: Meta<typeof FormSubmission> = {
+ title: 'Modules/Workflow/Actions/Form/WorkflowFormStepSubmitButton',
+ component: FormSubmission,
+ decorators: [
+ ComponentDecorator,
+ MemoryRouterDecorator,
+ ObjectMetadataItemsDecorator,
+ WorkspaceDecorator,
+ ToastDecorator,
+ ],
+ beforeEach: async () => {
+ await Promise.all([
+ mockedApolloClient.clearStore(),
+ mockedApolloCoreClient.clearStore(),
+ ]);
+ },
+ parameters: { msw: { handlers: createHandlers() } },
+};
+
+export default meta;
+type Story = StoryObj<typeof FormSubmission>;
+
+export const WithoutConversation: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.click(
+ await canvas.findByRole('button', { name: /Submit/ }),
+ );
+ expect(await canvas.findByText('Form submitted')).toBeVisible();
+ },
+};
+
+export const WithConversation: Story = {
+ parameters: { msw: { handlers: createHandlers({ threadId: THREAD_ID }) } },
+ play: WithoutConversation.play,
+};
+
+export const NoLongerPending: Story = {
+ parameters: {
+ msw: { handlers: createHandlers({ errorCode: 'TOOL_CALL_NOT_PENDING' }) },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.click(
+ await canvas.findByRole('button', { name: /Submit/ }),
+ );
+ expect(
+ await within(document.body).findByText(
+ 'This form no longer waits for an answer',
+ ),
+ ).toBeVisible();
+ expect(canvas.queryByText('Form submitted')).not.toBeInTheDocument();
+ expect(canvas.getByRole('button', { name: /Submit/ })).toBeEnabled();
+ },
+};
+
+export const SubmissionError: Story = {
+ parameters: {
+ msw: {
+ handlers: createHandlers({ errorCode: 'TOOL_CALL_RESOLUTION_FORBIDDEN' }),
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.click(
+ await canvas.findByRole('button', { name: /Submit/ }),
+ );
+ expect(
+ await within(document.body).findByText('Unable to submit form'),
+ ).toBeVisible();
+ expect(canvas.queryByText('Form submitted')).not.toBeInTheDocument();
+ expect(canvas.getByRole('button', { name: /Submit/ })).toBeEnabled();
+ },
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts
index 3e2a9eaf9c8..02b644a1711 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts
@@ -5,7 +5,12 @@ import { useAnswerToolCall } from '@/ai/hooks/useAnswerToolCall';
import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';
import { useFindOneRecordQuery } from '@/object-record/hooks/useFindOneRecordQuery';
+import { SUBMIT_FORM_STEP } from '@/workflow/graphql/mutations/submitFormStep';
import { useWorkflowRun } from '@/workflow/hooks/useWorkflowRun';
+import {
+ type SubmitFormStepMutation,
+ type SubmitFormStepMutationVariables,
+} from '~/generated/graphql';
import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
export const useAnswerFormStep = ({
@@ -39,20 +44,24 @@ export const useAnswerFormStep = ({
fetchPolicy: 'network-only',
});
- // A form step's call is named after the step, in the conversation its
- // current execution recorded. Returns false when the form no longer waits:
- // it has no conversation, or someone answered it or the run ended first.
+ // Forms started before conversations are available still have the run and step IDs.
const answerFormStep = async (
response: Record<string, unknown>,
): Promise<boolean> => {
- const threadId = workflowRun?.state?.stepInfos[stepId]?.threadId;
-
- if (!isDefined(threadId)) {
- return false;
- }
-
try {
- await answerToolCall({ threadId, toolCallId: stepId, response });
+ const threadId = workflowRun?.state?.stepInfos[stepId]?.threadId;
+
+ if (isDefined(threadId)) {
+ await answerToolCall({ threadId, toolCallId: stepId, response });
+ } else {
+ await apolloCoreClient.mutate<
+ SubmitFormStepMutation,
+ SubmitFormStepMutationVariables
+ >({
+ mutation: SUBMIT_FORM_STEP,
+ variables: { input: { workflowRunId, stepId, response } },
+ });
+ }
} catch (error) {
if (!isGraphqlErrorOfType(error, AiChatErrorCode.TOOL_CALL_NOT_PENDING)) {
throw error;
diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
index fe886a3bf21..6b8c4d3e99b 100644
--- a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
+++ b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
@@ -13,6 +13,9 @@ import { AiChatTab } from '@/ai/components/AiChatTab';
import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';
import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
+import { recordPageLayoutByObjectMetadataIdFamilySelector } from '@/page-layout/states/selectors/recordPageLayoutByObjectMetadataIdFamilySelector';
+import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
import { getDisplayedAiChatThreadId } from '@/ai/utils/getDisplayedAiChatThreadId';
import { PageCardLayout } from '@/ui/layout/page/components/PageCardLayout';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
@@ -32,6 +35,17 @@ export const AiChatPage = () => {
const { threadId } = useParams();
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
const isMobile = useIsMobile();
+ const chatObjectMetadata = useAtomFamilySelectorValue(
+ objectMetadataItemFamilySelector,
+ {
+ objectName: CoreObjectNameSingular.AgentChatThread,
+ objectNameType: 'singular',
+ },
+ );
+ const chatRecordPageLayout = useAtomFamilySelectorValue(
+ recordPageLayoutByObjectMetadataIdFamilySelector,
+ { objectMetadataId: chatObjectMetadata?.id ?? '' },
+ );
const displayedThreadId = getDisplayedAiChatThreadId({
urlThreadId: threadId,
currentAiChatThread,
@@ -42,7 +56,7 @@ export const AiChatPage = () => {
<AiChatPageThreadUrlSyncEffect />
<AiChatPageCloseSidePanelChatEffect />
<AiChatPageContinueInSidePanelEffect />
- {isDefined(displayedThreadId) ? (
+ {isDefined(displayedThreadId) && isDefined(chatRecordPageLayout) ? (
<RecordShowPageContent
parameters={{
objectNameSingular: CoreObjectNameSingular.AgentChatThread,
@@ -55,7 +69,7 @@ export const AiChatPage = () => {
isRecordIdentifierBarHidden
/>
) : (
- // A new chat has no record until its first message is sent
+ // Saved chats also use this surface until their record layout exists.
<PageCardLayout header={<AiChatPageHeader />}>
<StyledChatContainer>
<AiChatSurfaceContext.Provider value={AI_CHAT_SURFACE.PAGE}>
diff --git a/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatPage.test.tsx b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatPage.test.tsx
index becc72e5248..8c2072fe893 100644
--- a/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatPage.test.tsx
+++ b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatPage.test.tsx
@@ -45,6 +45,25 @@ jest.mock('@/ai/components/AiChatPageCloseSidePanelChatEffect', () => ({
}));
let mockIsMobile = false;
+let mockHasChatLayout = true;
+let mockHasChatObject = true;
+
+jest.mock(
+ '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue',
+ () => ({
+ useAtomFamilySelectorValue: (
+ _selector: unknown,
+ parameters: Record<string, unknown>,
+ ) =>
+ 'objectMetadataId' in parameters
+ ? mockHasChatLayout && parameters.objectMetadataId
+ ? { id: 'chat-layout-id' }
+ : undefined
+ : mockHasChatObject
+ ? { id: 'chat-object-id' }
+ : null,
+ }),
+);
jest.mock('twenty-ui/utilities', () => ({
...jest.requireActual('twenty-ui/utilities'),
@@ -99,6 +118,8 @@ describe('AiChatPage', () => {
beforeEach(() => {
jest.clearAllMocks();
mockIsMobile = false;
+ mockHasChatLayout = true;
+ mockHasChatObject = true;
sessionStorage.clear();
resetJotaiStore();
});
@@ -115,6 +136,20 @@ describe('AiChatPage', () => {
},
);
+ it.each(['object', 'layout'])(
+ 'keeps a saved chat usable without its %s metadata',
+ (missingMetadata) => {
+ mockHasChatObject = missingMetadata !== 'object';
+ mockHasChatLayout = missingMetadata !== 'layout';
+ jotaiStore.set(currentAiChatThreadState.atom, THREAD_ID);
+
+ const { getByTestId, queryByText } = renderAt(`/chat/${THREAD_ID}`);
+
+ expect(getByTestId('ai-chat-tab')).toHaveTextContent('page');
+ expect(queryByText(/Record page/)).toBeNull();
+ },
+ );
+
it('renders the current chat as its record page when the URL has no chat', () => {
jotaiStore.set(currentAiChatThreadState.atom, THREAD_ID);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-history-workspace-storage.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-history-workspace-storage.service.spec.ts
index 5c8b163462c..fd1a6bdc136 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-history-workspace-storage.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-history-workspace-storage.service.spec.ts
@@ -40,6 +40,31 @@ describe('AgentHistoryWorkspaceStorageService', () => {
expect(runner.release).toHaveBeenCalledTimes(1);
});
+ it.each([
+ ['shared', 'pg_advisory_xact_lock_shared'],
+ ['exclusive', 'pg_advisory_xact_lock'],
+ ] as const)(
+ 'holds the %s workspace fence until the operation completes',
+ async (lockMode, lockFunction) => {
+ await service.run(
+ WORKSPACE_ID,
+ async () => {
+ expect(runner.query).toHaveBeenNthCalledWith(
+ 1,
+ `SELECT ${lockFunction}(hashtextextended($1, 0))`,
+ [`agent-history-storage-v1:${WORKSPACE_ID}`],
+ );
+ expect(runner.commitTransaction).not.toHaveBeenCalled();
+ expect(runner.release).not.toHaveBeenCalled();
+ },
+ { lockMode },
+ );
+
+ expect(runner.commitTransaction).toHaveBeenCalledTimes(1);
+ expect(runner.release).toHaveBeenCalledTimes(1);
+ },
+ );
+
it.each([[], undefined])(
'rejects incomplete upgrades before running domain writes (%s)',
async (ready) => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts
index 547021142e0..32e8e98e85d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts
@@ -56,6 +56,7 @@ export class AgentHistoryWorkspaceStorageService {
async run<TResult>(
workspaceId: string,
work: (context: AgentHistoryStorageContext) => Promise<TResult>,
+ { lockMode = 'shared' }: { lockMode?: 'shared' | 'exclusive' } = {},
): Promise<TResult> {
if (!isNonEmptyString(workspaceId)) {
throw new AgentHistoryStorageException(
@@ -70,7 +71,9 @@ export class AgentHistoryWorkspaceStorageService {
await runner.startTransaction();
// A retried upgrade clears its destination; no live write may race that copy.
await runner.query(
- 'SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0))',
+ lockMode === 'exclusive'
+ ? 'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))'
+ : 'SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0))',
[`${HISTORY_READINESS_KEY}:${workspaceId}`],
);
const ready = await runner.query(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer.service.spec.ts
index 4aaf55b2801..698882b3d88 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer.service.spec.ts
@@ -105,6 +105,8 @@ describe('ToolCallAnswerService', () => {
};
const workflowRunnerWorkspaceService = {
resumeAnsweredStep: jest.fn().mockResolvedValue(undefined),
+ completeFormStep: jest.fn().mockResolvedValue(true),
+ resume: jest.fn().mockResolvedValue(undefined),
};
const step = { id: 'step-id', type: 'AI_AGENT' };
const workflowRunWorkspaceService = {
@@ -143,6 +145,10 @@ describe('ToolCallAnswerService', () => {
}),
};
+ const agentHistoryWorkspaceStorageService = {
+ run: jest.fn().mockImplementation((_workspaceId, work) => work()),
+ };
+
const service = new ToolCallAnswerService(
threadRepository as never,
agentChatService as never,
@@ -172,10 +178,12 @@ describe('ToolCallAnswerService', () => {
}),
} as never,
toolRegistryService as never,
+ agentHistoryWorkspaceStorageService as never,
);
return {
service,
+ agentHistoryWorkspaceStorageService,
step,
agentChatService,
agentChatStreamingService,
@@ -661,6 +669,248 @@ describe('ToolCallAnswerService', () => {
});
});
+ describe('form submissions without a conversation', () => {
+ const formArguments = {
+ workflowRunId: 'workflow-run-id',
+ stepId: 'step-id',
+ response: { discount: '20%' },
+ userWorkspaceId: 'user-workspace-id',
+ workspaceMemberId: 'member-id',
+ workspace,
+ };
+ const formStep = {
+ id: 'step-id',
+ type: 'FORM',
+ settings: { input: FORM_FIELDS },
+ };
+ const pendingRun = {
+ status: 'RUNNING',
+ state: {
+ stepInfos: { 'step-id': { status: 'PENDING' } },
+ flow: { steps: [formStep] },
+ },
+ };
+ const buildFormService = (options: BuildOptions = {}) => {
+ const result = buildService(options);
+ result.workflowRunWorkspaceService.getWorkflowRun.mockResolvedValue(
+ pendingRun,
+ );
+ return result;
+ };
+
+ it('validates and resumes a form that has no conversation yet', async () => {
+ const { service, workflowRunnerWorkspaceService, agentChatService } =
+ buildFormService();
+
+ await service.answerFormStep(formArguments);
+
+ expect(
+ workflowRunnerWorkspaceService.completeFormStep,
+ ).toHaveBeenCalledWith({
+ workspaceId: workspace.id,
+ workflowRunId: formArguments.workflowRunId,
+ step: formStep,
+ expectedThreadId: null,
+ response: formArguments.response,
+ });
+ expect(agentChatService.findToolPart).not.toHaveBeenCalled();
+ expect(workflowRunnerWorkspaceService.resume).toHaveBeenCalledWith({
+ workspaceId: workspace.id,
+ workflowRunId: formArguments.workflowRunId,
+ lastExecutedStepId: formArguments.stepId,
+ });
+ });
+
+ it('fails the run after releasing the history fence if its accepted answer cannot be resumed', async () => {
+ const {
+ service,
+ workflowRunnerWorkspaceService,
+ workflowRunWorkspaceService,
+ agentHistoryWorkspaceStorageService,
+ } = buildFormService();
+ const queueError = new Error('Queue unavailable');
+ let isHistoryFenceHeld = false;
+
+ agentHistoryWorkspaceStorageService.run.mockImplementation(
+ async (_workspaceId, work) => {
+ isHistoryFenceHeld = true;
+
+ try {
+ return await work();
+ } finally {
+ isHistoryFenceHeld = false;
+ }
+ },
+ );
+ workflowRunnerWorkspaceService.completeFormStep.mockImplementation(
+ async () => {
+ expect(isHistoryFenceHeld).toBe(true);
+
+ return true;
+ },
+ );
+ workflowRunnerWorkspaceService.resume.mockImplementation(async () => {
+ expect(isHistoryFenceHeld).toBe(false);
+
+ throw queueError;
+ });
+ workflowRunWorkspaceService.endWorkflowRun.mockImplementation(
+ async () => {
+ expect(isHistoryFenceHeld).toBe(false);
+ },
+ );
+
+ await expect(service.answerFormStep(formArguments)).rejects.toBe(
+ queueError,
+ );
+ expect(workflowRunWorkspaceService.endWorkflowRun).toHaveBeenCalledWith({
+ workspaceId: workspace.id,
+ workflowRunId: formArguments.workflowRunId,
+ status: 'FAILED',
+ error: 'The run could not resume after its form was answered',
+ });
+ });
+
+ it('uses the conversation if the backfill finished before the submission acquired its lock', async () => {
+ const {
+ service,
+ workflowRunWorkspaceService,
+ workflowRunnerWorkspaceService,
+ agentHistoryWorkspaceStorageService,
+ } = buildFormService();
+ workflowRunWorkspaceService.getWorkflowRun
+ .mockResolvedValueOnce(pendingRun)
+ .mockResolvedValueOnce({
+ ...pendingRun,
+ state: {
+ ...pendingRun.state,
+ stepInfos: {
+ 'step-id': { status: 'PENDING', threadId: 'backfilled-thread' },
+ },
+ },
+ });
+ const answer = jest
+ .spyOn(service, 'answer')
+ .mockResolvedValue({ streamId: null, turnId: null });
+
+ await service.answerFormStep(formArguments);
+
+ expect(agentHistoryWorkspaceStorageService.run).toHaveBeenCalledWith(
+ workspace.id,
+ expect.any(Function),
+ { lockMode: 'exclusive' },
+ );
+ expect(answer).toHaveBeenCalledWith(
+ expect.objectContaining({
+ threadId: 'backfilled-thread',
+ toolCallId: 'step-id',
+ }),
+ );
+ expect(
+ workflowRunnerWorkspaceService.completeFormStep,
+ ).not.toHaveBeenCalled();
+ expect(workflowRunnerWorkspaceService.resume).not.toHaveBeenCalled();
+ });
+
+ it('requires workflow permission before reading or answering the run', async () => {
+ const {
+ service,
+ workflowRunWorkspaceService,
+ workflowRunnerWorkspaceService,
+ } = buildFormService({ hasPermission: false });
+
+ await expect(service.answerFormStep(formArguments)).rejects.toMatchObject(
+ { code: 'TOOL_CALL_RESOLUTION_FORBIDDEN' },
+ );
+ expect(workflowRunWorkspaceService.getWorkflowRun).not.toHaveBeenCalled();
+ expect(
+ workflowRunnerWorkspaceService.completeFormStep,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('requires access to the specific run', async () => {
+ const { service, workflowRunRepository, workflowRunnerWorkspaceService } =
+ buildFormService();
+ workflowRunRepository.findOne.mockResolvedValue(null);
+
+ await expect(service.answerFormStep(formArguments)).rejects.toMatchObject(
+ { code: 'TOOL_CALL_NOT_FOUND' },
+ );
+ expect(
+ workflowRunnerWorkspaceService.completeFormStep,
+ ).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { ...pendingRun, status: 'STOPPED' },
+ {
+ ...pendingRun,
+ state: {
+ ...pendingRun.state,
+ stepInfos: { 'step-id': { status: 'SUCCESS' } },
+ },
+ },
+ {
+ ...pendingRun,
+ state: {
+ ...pendingRun.state,
+ stepInfos: { 'step-id': { status: 'PENDING', error: 'failed' } },
+ },
+ },
+ {
+ ...pendingRun,
+ state: {
+ ...pendingRun.state,
+ flow: { steps: [{ ...formStep, type: 'AI_AGENT' }] },
+ },
+ },
+ { ...pendingRun, state: { ...pendingRun.state, flow: { steps: [] } } },
+ ])('rejects a run without an answerable form: %j', async (run) => {
+ const {
+ service,
+ workflowRunWorkspaceService,
+ workflowRunnerWorkspaceService,
+ } = buildFormService();
+ workflowRunWorkspaceService.getWorkflowRun.mockResolvedValue(run);
+
+ await expect(service.answerFormStep(formArguments)).rejects.toMatchObject(
+ { code: 'TOOL_CALL_NOT_PENDING' },
+ );
+ expect(
+ workflowRunnerWorkspaceService.completeFormStep,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('validates answers with the same schema as conversation forms', async () => {
+ const { service, workflowRunnerWorkspaceService } = buildFormService();
+
+ await expect(
+ service.answerFormStep({
+ ...formArguments,
+ response: { unknownField: 'value' },
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_TOOL_CALL_OUTPUT' });
+ expect(
+ workflowRunnerWorkspaceService.completeFormStep,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('rejects an answer when another submission or a conversation claimed the step', async () => {
+ const {
+ service,
+ workflowRunnerWorkspaceService,
+ workflowRunWorkspaceService,
+ } = buildFormService();
+ workflowRunnerWorkspaceService.completeFormStep.mockResolvedValue(false);
+
+ await expect(service.answerFormStep(formArguments)).rejects.toMatchObject(
+ { code: 'TOOL_CALL_NOT_PENDING' },
+ );
+ expect(workflowRunnerWorkspaceService.resume).not.toHaveBeenCalled();
+ expect(workflowRunWorkspaceService.endWorkflowRun).not.toHaveBeenCalled();
+ });
+ });
+
describe('the deprecated entry points', () => {
it('answers a form step through the call named after it in its conversation', async () => {
const { service, agentChatService } = buildService({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
index 7408936a354..e3b5f0bf70a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
@@ -5,6 +5,7 @@ import { generateId } from 'ai';
import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';
import { PermissionFlagType } from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
+import { StepStatus } from 'twenty-shared/workflow';
import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
import { workspaceAuthContextStorage } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
@@ -12,6 +13,7 @@ import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/servi
import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/tool-context.type';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
+import { REQUEST_FORM_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/request-form.pausing-tool';
import { type PausingToolCompletionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type';
import { parsePausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/parse-pausing-tool-call.util';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
@@ -23,6 +25,7 @@ import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/service
import { mapErrorToStreamError } from 'src/engine/metadata-modules/ai/ai-chat/utils/map-error-to-stream-error.util';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentHistoryWorkspaceStorageService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';
import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import {
AiException,
@@ -38,6 +41,7 @@ import {
type WorkflowRunWorkspaceEntity,
} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+import { isWorkflowFormAction } from 'src/modules/workflow/workflow-executor/workflow-actions/form/guards/is-workflow-form-action.guard';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';
@@ -78,6 +82,7 @@ export class ToolCallAnswerService {
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly agentActorContextService: AgentActorContextService,
private readonly toolRegistryService: ToolRegistryService,
+ private readonly agentHistoryWorkspaceStorageService: AgentHistoryWorkspaceStorageService,
) {}
async answer(args: AnswerToolCallArgs): Promise<AnswerToolCallOutcome> {
@@ -286,8 +291,7 @@ export class ToolCallAnswerService {
}
}
- // Behind submitFormStep, kept for clients built before answerToolCall: a
- // form step's call is named after the step, in the step's conversation.
+ // Runs created before conversations are available still need to accept answers.
async answerFormStep({
workflowRunId,
stepId,
@@ -296,17 +300,138 @@ export class ToolCallAnswerService {
workflowRunId: string;
stepId: string;
}): Promise<void> {
+ await this.assertCanAnswerForWorkflowRun({
+ workflowRunId,
+ workspaceId: args.workspace.id,
+ userWorkspaceId: args.userWorkspaceId,
+ });
+
const workflowRun = await this.workflowRunWorkspaceService.getWorkflowRun({
workflowRunId,
workspaceId: args.workspace.id,
});
const threadId = workflowRun?.state?.stepInfos?.[stepId]?.threadId;
- if (!isDefined(threadId)) {
+ if (isDefined(threadId)) {
+ await this.answer({ ...args, threadId, toolCallId: stepId });
+
+ return;
+ }
+
+ // The pending-form backfill holds the history fence while reading and
+ // rewriting runs. It must not overwrite an answer accepted in the meantime.
+ const recordedThreadId = await this.agentHistoryWorkspaceStorageService.run(
+ args.workspace.id,
+ async () => {
+ const currentRun =
+ await this.workflowRunWorkspaceService.getWorkflowRun({
+ workflowRunId,
+ workspaceId: args.workspace.id,
+ });
+ const currentThreadId =
+ currentRun?.state?.stepInfos?.[stepId]?.threadId;
+
+ if (isDefined(currentThreadId)) {
+ return currentThreadId;
+ }
+
+ await this.answerFormWithoutConversation({
+ ...args,
+ workflowRunId,
+ stepId,
+ workflowRun: currentRun,
+ });
+
+ return null;
+ },
+ { lockMode: 'exclusive' },
+ );
+
+ // Release the fence before the conversation answer takes its own history locks.
+ if (isDefined(recordedThreadId)) {
+ await this.answer({
+ ...args,
+ threadId: recordedThreadId,
+ toolCallId: stepId,
+ });
+
+ return;
+ }
+
+ // The answer is already committed. Release the history fence before resuming
+ // or failing the run, since failure closes its other waiting conversations.
+ try {
+ await this.workflowRunnerWorkspaceService.resume({
+ workspaceId: args.workspace.id,
+ workflowRunId,
+ lastExecutedStepId: stepId,
+ });
+ } catch (error) {
+ await this.workflowRunWorkspaceService.endWorkflowRun({
+ workspaceId: args.workspace.id,
+ workflowRunId,
+ status: WorkflowRunStatus.FAILED,
+ error: 'The run could not resume after its form was answered',
+ });
+
+ throw error;
+ }
+ }
+
+ private async answerFormWithoutConversation({
+ workflowRun,
+ workflowRunId,
+ stepId,
+ ...args
+ }: Omit<AnswerToolCallArgs, 'threadId' | 'toolCallId' | 'modelId'> & {
+ workflowRun: WorkflowRunWorkspaceEntity | null;
+ workflowRunId: string;
+ stepId: string;
+ }): Promise<void> {
+ const stepInfo = workflowRun?.state?.stepInfos?.[stepId];
+ const step = workflowRun?.state?.flow?.steps.find(
+ ({ id }) => id === stepId,
+ );
+
+ if (
+ workflowRun?.status !== WorkflowRunStatus.RUNNING ||
+ stepInfo?.status !== StepStatus.PENDING ||
+ isDefined(stepInfo.error) ||
+ !isDefined(step) ||
+ !isWorkflowFormAction(step)
+ ) {
throw this.notPending();
}
- await this.answer({ ...args, threadId, toolCallId: stepId });
+ const formCall = REQUEST_FORM_PAUSING_TOOL.parseCall({
+ fields: step.settings.input,
+ });
+
+ if (!isDefined(formCall)) {
+ throw this.notPending();
+ }
+
+ const validation = formCall.validate(args.response);
+
+ if (!validation.isValid) {
+ throw new AiException(
+ validation.errorMessage,
+ AiExceptionCode.INVALID_TOOL_CALL_OUTPUT,
+ );
+ }
+
+ const hasCompletedStep =
+ await this.workflowRunnerWorkspaceService.completeFormStep({
+ workspaceId: args.workspace.id,
+ workflowRunId,
+ step,
+ expectedThreadId: null,
+ response: validation.output,
+ });
+
+ if (!hasCompletedStep) {
+ throw this.notPending();
+ }
}
// Behind answerAgentChatQuestion, kept for clients built before
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
index 60ef10b5b8b..18954692b9d 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts
@@ -168,6 +168,57 @@ describe('WorkflowRunWorkspaceService conversations', () => {
});
});
+ describe('form steps without a conversation', () => {
+ const completeForm = (service: WorkflowRunWorkspaceService) =>
+ service.updateStepInfoIfPending({
+ stepId: 'step-id',
+ stepInfo: { status: StepStatus.SUCCESS, result: { name: 'Tim' } },
+ expectedThreadId: null,
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ });
+
+ it('completes a pending form exactly once', async () => {
+ const { service, updateWorkflowRun } = buildService({
+ stepInfo: { status: StepStatus.PENDING },
+ });
+ updateWorkflowRun.mockImplementation(async ({ partialUpdate }) => {
+ jest.spyOn(service, 'getWorkflowRunOrFail').mockResolvedValue({
+ id: 'workflow-run-id',
+ status: WorkflowRunStatus.RUNNING,
+ state: partialUpdate.state,
+ } as never);
+ });
+
+ expect(await completeForm(service)).toBe(true);
+ expect(await completeForm(service)).toBe(false);
+ expect(updateWorkflowRun).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ [
+ 'a conversation was added',
+ { stepInfo: { status: StepStatus.PENDING, threadId: 'new-thread' } },
+ ],
+ [
+ 'the run stopped',
+ {
+ status: WorkflowRunStatus.STOPPED,
+ stepInfo: { status: StepStatus.PENDING },
+ },
+ ],
+ [
+ 'the form failed',
+ { stepInfo: { status: StepStatus.PENDING, error: 'failed' } },
+ ],
+ ])('does not complete when %s', async (_description, overrides) => {
+ const { service, updateWorkflowRun } = buildService(overrides);
+
+ expect(await completeForm(service)).toBe(false);
+ expect(updateWorkflowRun).not.toHaveBeenCalled();
+ });
+ });
+
describe('endWorkflowRun', () => {
const endRun = (service: WorkflowRunWorkspaceService) =>
service.endWorkflowRun({
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
index 4a7ce641a0a..fd56fb44cde 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
@@ -436,7 +436,7 @@ export class WorkflowRunWorkspaceService {
}: {
stepId: string;
stepInfo: Partial<WorkflowRunStepInfo>;
- expectedThreadId?: string;
+ expectedThreadId?: string | null;
workflowRunId: string;
workspaceId: string;
}): Promise<boolean> {
@@ -450,8 +450,9 @@ export class WorkflowRunWorkspaceService {
if (
workflowRunToUpdate.status !== WorkflowRunStatus.RUNNING ||
currentStepInfo?.status !== StepStatus.PENDING ||
- (isDefined(expectedThreadId) &&
- currentStepInfo.threadId !== expectedThreadId)
+ isDefined(currentStepInfo.error) ||
+ (expectedThreadId !== undefined &&
+ (currentStepInfo.threadId ?? null) !== expectedThreadId)
) {
return false;
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
index 1e7eb0d0931..2bf07f68c10 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
@@ -3,7 +3,10 @@ import { WorkflowActionType } from 'twenty-shared/workflow';
import { type MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { type WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';
import { type WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';
-import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+import {
+ type WorkflowAction,
+ type WorkflowFormAction,
+} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { RUN_WORKFLOW_JOB_NAME } from 'src/modules/workflow/workflow-runner/constants/run-workflow-job-name';
import { type CoreWorkflowRunnerService } from 'src/modules/workflow/workflow-runner/services/core-workflow-runner.service';
import { type WorkflowThrottlingWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run-queue/workspace-services/workflow-throttling.workspace-service';
@@ -19,11 +22,20 @@ const AGENT_STEP = {
type: WorkflowActionType.AI_AGENT,
} as WorkflowAction;
-const FORM_STEP = {
+const FORM_STEP: WorkflowFormAction = {
id: 'form-step-id',
+ name: 'Form',
+ valid: true,
type: WorkflowActionType.FORM,
- settings: { input: [] },
-} as unknown as WorkflowAction;
+ settings: {
+ input: [],
+ outputSchema: {},
+ errorHandlingOptions: {
+ retryOnFailure: { value: 0 },
+ continueOnFailure: { value: false },
+ },
+ },
+};
describe('WorkflowRunnerWorkspaceService', () => {
const messageQueueService = { add: jest.fn() };
@@ -61,6 +73,30 @@ describe('WorkflowRunnerWorkspaceService', () => {
jest.clearAllMocks();
});
+ it('records the enriched result of a form without a conversation before scheduling its continuation', async () => {
+ const completed = await service.completeFormStep({
+ workspaceId: WORKSPACE_ID,
+ workflowRunId: WORKFLOW_RUN_ID,
+ step: FORM_STEP,
+ expectedThreadId: null,
+ response: { discount: 15 },
+ });
+
+ expect(completed).toBe(true);
+ expect(
+ workflowRunWorkspaceService.updateStepInfoIfPending,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({
+ expectedThreadId: null,
+ stepInfo: {
+ status: 'SUCCESS',
+ result: { discount: 15, enriched: true },
+ },
+ }),
+ );
+ expect(messageQueueService.add).not.toHaveBeenCalled();
+ });
+
describe('resumeAnsweredStep', () => {
it('schedules an explicit resume of an agent step in its conversation', async () => {
await resumeAnsweredStep(AGENT_STEP);
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
index 50d8e7f9213..c9ef785f37b 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
@@ -10,7 +10,10 @@ import { MessageQueueService } from 'src/engine/core-modules/message-queue/servi
import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
import { workflowHasRunningSteps } from 'src/modules/workflow/common/utils/workflow-has-running-steps.util';
import { WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';
-import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+import {
+ type WorkflowFormAction,
+ type WorkflowAction,
+} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { isWorkflowFormAction } from 'src/modules/workflow/workflow-executor/workflow-actions/form/guards/is-workflow-form-action.guard';
import {
WorkflowRunException,
@@ -123,6 +126,36 @@ export class WorkflowRunnerWorkspaceService {
return;
}
+ const hasCompletedStep = await this.completeFormStep({
+ workspaceId,
+ workflowRunId,
+ step,
+ expectedThreadId: threadId,
+ response,
+ });
+
+ if (hasCompletedStep) {
+ await this.resume({
+ workspaceId,
+ workflowRunId,
+ lastExecutedStepId: step.id,
+ });
+ }
+ }
+
+ async completeFormStep({
+ workspaceId,
+ workflowRunId,
+ step,
+ expectedThreadId,
+ response,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ step: WorkflowFormAction;
+ expectedThreadId: string | null;
+ response: Record<string, unknown>;
+ }): Promise<boolean> {
const enrichedResponse =
await this.workflowVersionStepOperationsWorkspaceService.enrichFormStepResponse(
{
@@ -132,25 +165,16 @@ export class WorkflowRunnerWorkspaceService {
},
);
- const hasCompletedStep =
- await this.workflowRunWorkspaceService.updateStepInfoIfPending({
- stepId: step.id,
- stepInfo: {
- status: StepStatus.SUCCESS,
- result: enrichedResponse,
- },
- expectedThreadId: threadId,
- workspaceId,
- workflowRunId,
- });
-
- if (hasCompletedStep) {
- await this.resume({
- workspaceId,
- workflowRunId,
- lastExecutedStepId: step.id,
- });
- }
+ return this.workflowRunWorkspaceService.updateStepInfoIfPending({
+ stepId: step.id,
+ stepInfo: {
+ status: StepStatus.SUCCESS,
+ result: enrichedResponse,
+ },
+ expectedThreadId,
+ workspaceId,
+ workflowRunId,
+ });
}
async stopWorkflowRun(workspaceId: string, workflowRunId: string) {