Skip to content

The open alternative to Salesforce, designed for AI.

Fix AI step QA findings after the inline-config rework (#29506)

Félix Malfait905c7bdb5012
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/hooks/useTurnIntoBlockOptions.ts b/packages/twenty-front/src/modules/advanced-text-editor/hooks/useTurnIntoBlockOptions.ts
index 05ecff24bc6..e0d34b9b613 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/hooks/useTurnIntoBlockOptions.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/hooks/useTurnIntoBlockOptions.ts
@@ -54,10 +54,12 @@ export const useTurnIntoBlockOptions = (editor: Editor) => {
const liftOutOfBlockquote = (chain: ChainedCommands) =>
isInBlockquote ? chain.lift(TIPTAP_NODE_TYPES.BLOCKQUOTE) : chain;
- const configuredHeadingLevels: number[] =
- currentEditor.extensionManager.extensions.find(
- ({ name }) => name === TIPTAP_NODE_TYPES.HEADING,
- )?.options.levels ?? [];
+ // the selector runs once more after unmount, when a destroyed editor has no extensions left
+ const configuredHeadingLevels: number[] = currentEditor.isDestroyed
+ ? []
+ : (currentEditor.extensionManager.extensions.find(
+ ({ name }) => name === TIPTAP_NODE_TYPES.HEADING,
+ )?.options.levels ?? []);
return [
{
diff --git a/packages/twenty-front/src/modules/ai/constants/ChatReferenceBodyPattern.ts b/packages/twenty-front/src/modules/ai/constants/ChatReferenceBodyPattern.ts
index 81af118630c..e1b6aac7d9c 100644
--- a/packages/twenty-front/src/modules/ai/constants/ChatReferenceBodyPattern.ts
+++ b/packages/twenty-front/src/modules/ai/constants/ChatReferenceBodyPattern.ts
@@ -1,2 +1,3 @@
-// Excluding brackets and line breaks stops an unclosed reference from swallowing the text and markers after it.
-export const CHAT_REFERENCE_BODY_PATTERN = '[^\\[\\]\\n]*';
+// No line breaks or unbalanced brackets, so an unclosed reference can't swallow the text after it; a name may hold balanced [..] pairs.
+export const CHAT_REFERENCE_BODY_PATTERN =
+ '(?:[^\\[\\]\\n]|\\[[^\\[\\]\\n]*\\])*';
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/parseChatReferences.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/parseChatReferences.test.ts
index e59166befea..f7d58f87c02 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/parseChatReferences.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/parseChatReferences.test.ts
@@ -19,6 +19,19 @@ describe('parseChatReferences', () => {
displayName: 'Acme',
},
},
+ {
+ name: 'a record whose name holds brackets',
+ text: 'See [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:[24]7.ai]] now',
+ reference: {
+ kind: 'record',
+ fullMatch:
+ '[[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:[24]7.ai]]',
+ index: 4,
+ objectNameSingular: 'company',
+ recordId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
+ displayName: '[24]7.ai',
+ },
+ },
{
name: 'a record written without the record prefix',
text: 'Merge [[person:11111111-1111-1111-1111-111111111111:Alice]] first',
@@ -258,10 +271,6 @@ describe('parseChatReferences', () => {
name: 'a reference closed across a line break',
text: 'Open [[object:partner:Partners\nand others]]',
},
- {
- name: 'a reference whose display name contains brackets',
- text: 'Open [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:[test] name]]',
- },
{
name: 'references closed by a retired closing tag',
text: 'Contact [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:Acme[[/record]] and [[object:partner:Partners[[/object]] and [[field:person:stage:Stage[[/field]] and [[view:44444444-4444-4444-4444-444444444444:Pipeline[[/view]]',
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/protectChatReferencesForMarkdown.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/protectChatReferencesForMarkdown.test.ts
index d81695c8d2e..e79e409cf2a 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/protectChatReferencesForMarkdown.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/protectChatReferencesForMarkdown.test.ts
@@ -71,13 +71,13 @@ describe('protectChatReferencesForMarkdown', () => {
).toBe('See [[view:44444444-4444-4444-4444-444444444444:Q1 \\- pipeline]]');
});
- it('should leave a marker whose label contains brackets unchanged', () => {
+ it('should escape brackets in a label', () => {
expect(
protectChatReferencesForMarkdown(
'Open [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:[test] name]]',
),
).toBe(
- 'Open [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:[test] name]]',
+ 'Open [[record:company:a1b2c3d4-e5f6-7890-abcd-ef1234567890:\\[test\\] name]]',
);
});
diff --git a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx
index 153879b01d7..fd5bb5a4686 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx
@@ -17,11 +17,13 @@ import { CORE_ACTIONS } from '@/workflow/workflow-steps/workflow-actions/constan
import { FLOW_ACTIONS } from '@/workflow/workflow-steps/workflow-actions/constants/FlowActions';
import { HUMAN_INPUT_ACTIONS } from '@/workflow/workflow-steps/workflow-actions/constants/HumanInputActions';
import { RECORD_ACTIONS } from '@/workflow/workflow-steps/workflow-actions/constants/RecordActions';
-import { isAgentSelectableAsWorkflowStep } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/isAgentSelectableAsWorkflowStep';
import { useQuery } from '@apollo/client/react';
import { useLingui } from '@lingui/react/macro';
import { isDefined } from 'twenty-shared/utils';
-import { WORKFLOW_ACTION_FEATURE_FLAGS } from 'twenty-shared/workflow';
+import {
+ isAgentRunnableAsWorkflowStep,
+ WORKFLOW_ACTION_FEATURE_FLAGS,
+} from 'twenty-shared/workflow';
import {
FeatureFlagKey,
FindManyAgentsDocument,
@@ -88,7 +90,7 @@ export const SidePanelWorkflowSelectAction = ({
});
const stepAgents = (agentsData?.findManyAgents ?? []).filter(
- isAgentSelectableAsWorkflowStep,
+ isAgentRunnableAsWorkflowStep,
);
const handleActionClick = (actionType: WorkflowActionType) => {
diff --git a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/__tests__/SidePanelWorkflowSelectAction.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/__tests__/SidePanelWorkflowSelectAction.test.tsx
index 296445c2083..d96d0a6de74 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/__tests__/SidePanelWorkflowSelectAction.test.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/__tests__/SidePanelWorkflowSelectAction.test.tsx
@@ -142,14 +142,14 @@ describe('SidePanelWorkflowSelectAction', () => {
expect(screen.getByText('Generate')).toBeInTheDocument();
});
- it('lists only the agents with a JSON output, each creating a step that runs it', async () => {
+ it('lists agents whatever their output, each creating a step that runs it', async () => {
const onActionSelected = jest.fn();
renderPicker(onActionSelected);
await userEvent.click(await screen.findByText('Lead scorer'));
- expect(screen.queryByText('Chat helper')).not.toBeInTheDocument();
+ expect(screen.getByText('Chat helper')).toBeInTheDocument();
expect(onActionSelected).toHaveBeenCalledWith({
type: 'AI_AGENT',
defaultSettings: { input: { agentId: 'lead-scorer' } },
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/__tests__/isAgentSelectableAsWorkflowStep.test.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/__tests__/isAgentSelectableAsWorkflowStep.test.ts
deleted file mode 100644
index 5a17f48830d..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/__tests__/isAgentSelectableAsWorkflowStep.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { isAgentSelectableAsWorkflowStep } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/isAgentSelectableAsWorkflowStep';
-
-const JSON_RESPONSE_FORMAT = {
- type: 'json',
- schema: {
- type: 'object',
- properties: { score: { type: 'number' } },
- required: ['score'],
- additionalProperties: false,
- },
-};
-
-describe('isAgentSelectableAsWorkflowStep', () => {
- it('offers an active agent with a JSON output', () => {
- expect(
- isAgentSelectableAsWorkflowStep({
- isActive: true,
- isSystem: false,
- responseFormat: JSON_RESPONSE_FORMAT,
- }),
- ).toBe(true);
- });
-
- it.each([
- ['a text output', { type: 'text' }],
- ['no output format', null],
- [
- 'a JSON output without fields',
- { type: 'json', schema: { type: 'object', properties: {} } },
- ],
- ])('does not offer an agent with %s', (_, responseFormat) => {
- expect(
- isAgentSelectableAsWorkflowStep({
- isActive: true,
- isSystem: false,
- responseFormat,
- }),
- ).toBe(false);
- });
-
- it('does not offer an inactive or system agent', () => {
- expect(
- isAgentSelectableAsWorkflowStep({
- isActive: false,
- isSystem: false,
- responseFormat: JSON_RESPONSE_FORMAT,
- }),
- ).toBe(false);
- expect(
- isAgentSelectableAsWorkflowStep({
- isActive: true,
- isSystem: true,
- responseFormat: JSON_RESPONSE_FORMAT,
- }),
- ).toBe(false);
- });
-});
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/isAgentSelectableAsWorkflowStep.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/isAgentSelectableAsWorkflowStep.ts
deleted file mode 100644
index 06fd017fc92..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/utils/isAgentSelectableAsWorkflowStep.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { type FlatAgent } from '@/metadata-store/types/FlatAgent';
-import {
- agentResponseFormatSchema,
- isAgentRunnableAsWorkflowStep,
-} from 'twenty-shared/workflow';
-
-// picker-only: a step's output must be known when the workflow is built, so only agents with a JSON output are listed
-export const isAgentSelectableAsWorkflowStep = (
- agent: Pick<FlatAgent, 'isActive' | 'isSystem' | 'responseFormat'>,
-): boolean => {
- const parsedResponseFormat = agentResponseFormatSchema.safeParse(
- agent.responseFormat,
- );
-
- return (
- isAgentRunnableAsWorkflowStep(agent) &&
- parsedResponseFormat.success &&
- parsedResponseFormat.data.type === 'json' &&
- Object.keys(parsedResponseFormat.data.schema.properties).length > 0
- );
-};
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts
index fabef02be79..e8c8841bfd6 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts
@@ -91,30 +91,53 @@ describe('CoreWorkflowVersionMutationWorkspaceService.updateStep', () => {
['removes its agent', { agentId: 'agent-id' }, {}],
['adds an agent', {}, { agentId: 'agent-id' }],
['changes its agent', { agentId: 'agent-id' }, { agentId: 'other-id' }],
- ])(
- 'refuses to update an AI step that %s',
- async (_, existingInput, updatedInput) => {
- const { service, coreWorkflowVersionWriteService } = await buildService({
- existingStep: buildAiAgentStep({
- input: { ...existingInput, prompt: 'Qualify' },
- }),
- });
+ ])('rebuilds an AI step that %s', async (_, existingInput, updatedInput) => {
+ const existingStep = buildAiAgentStep({
+ input: { ...existingInput, prompt: 'Qualify' },
+ });
+ const {
+ service,
+ coreWorkflowVersionWriteService,
+ workflowVersionStepOperationsWorkspaceService,
+ } = await buildService({ existingStep });
+ const step = buildAiAgentStep({
+ input: { ...updatedInput, prompt: 'Qualify' },
+ });
+ const builtStep = buildAiAgentStep({ input: { prompt: 'Qualify' } });
- await expect(
- service.updateStep({
- workspaceId: WORKSPACE_ID,
- userWorkspaceId: undefined,
- coreWorkflowVersionId: CORE_WORKFLOW_VERSION_ID,
- step: buildAiAgentStep({
- input: { ...updatedInput, prompt: 'Qualify' },
- }),
- }),
- ).rejects.toThrow('Create a new step instead');
- expect(
- coreWorkflowVersionWriteService.writeContent,
- ).not.toHaveBeenCalled();
- },
- );
+ workflowVersionStepOperationsWorkspaceService.runStepCreationSideEffectsAndBuildStep.mockResolvedValue(
+ {
+ builtStep: { ...builtStep, nextStepIds: [], position: { x: 0, y: 0 } },
+ },
+ );
+
+ const updatedStep = await service.updateStep({
+ workspaceId: WORKSPACE_ID,
+ userWorkspaceId: undefined,
+ coreWorkflowVersionId: CORE_WORKFLOW_VERSION_ID,
+ step,
+ });
+
+ expect(
+ workflowVersionStepOperationsWorkspaceService.runStepCreationSideEffectsAndBuildStep,
+ ).toHaveBeenCalledTimes(1);
+ expect(
+ workflowVersionStepOperationsWorkspaceService.runStepCreationSideEffectsAndBuildStep,
+ ).toHaveBeenCalledWith({
+ type: WorkflowActionType.AI_AGENT,
+ workspaceId: WORKSPACE_ID,
+ position: step.position,
+ id: 'step-id',
+ defaultSettings: step.settings,
+ });
+ expect(updatedStep).toEqual(builtStep);
+ expect(coreWorkflowVersionWriteService.writeContent).toHaveBeenCalledWith(
+ expect.objectContaining({ steps: [builtStep] }),
+ );
+ expect(
+ workflowVersionStepOperationsWorkspaceService.runWorkflowVersionStepDeletionSideEffects,
+ ).toHaveBeenCalledWith({ step: existingStep, workspaceId: WORKSPACE_ID });
+ });
it('updates an AI step in place when its agent is unchanged', async () => {
const existingStep = buildAiAgentStep({
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts
index 18568972155..476e66051e4 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service.ts
@@ -221,20 +221,11 @@ export class CoreWorkflowVersionMutationWorkspaceService {
);
}
- // an AI step's kind and agent are fixed once it exists: a different agent is a new step
- if (isWorkflowAiAgentStepKindChanged({ existingStep, updatedStep: step })) {
- throw new WorkflowVersionStepException(
- 'An AI step cannot switch between generating and running an agent, or to another agent. Create a new step instead.',
- WorkflowVersionStepExceptionCode.INVALID_REQUEST,
- {
- userFriendlyMessage: msg`An AI step cannot change its agent. Create a new step instead.`,
- },
- );
- }
-
- const isStepTypeChanged = existingStep.type !== step.type;
+ const isStepRebuilt =
+ existingStep.type !== step.type ||
+ isWorkflowAiAgentStepKindChanged({ existingStep, updatedStep: step });
- const { updatedStep, additionalCreatedSteps } = isStepTypeChanged
+ const { updatedStep, additionalCreatedSteps } = isStepRebuilt
? await this.rebuildStepForTypeChange({
existingStep,
newStep: step,
@@ -259,7 +250,7 @@ export class CoreWorkflowVersionMutationWorkspaceService {
steps: updatedSteps,
})
.catch(async (error: unknown) => {
- if (isStepTypeChanged) {
+ if (isStepRebuilt) {
const stepsToDelete =
error instanceof CoreWorkflowVersionPostCommitError
? [existingStep]
@@ -280,7 +271,7 @@ export class CoreWorkflowVersionMutationWorkspaceService {
throw error;
});
- if (isStepTypeChanged) {
+ if (isStepRebuilt) {
await this.workflowVersionStepOperationsWorkspaceService.runWorkflowVersionStepDeletionSideEffects(
{
step: existingStep,
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
index 25b7773cc55..0f286e58229 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
@@ -183,21 +183,21 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
workspaceId: string;
applicationId: string;
}): Promise<void> {
+ const agent = await this.agentService.createOneAgent(
+ {
+ label: 'Workflow Assistant',
+ icon: 'IconLego',
+ description: 'Runs the seeded workflows that wait for a person.',
+ prompt:
+ 'You are a helpful AI assistant. Complete the task based on the workflow context.',
+ modelId: AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
+ responseFormat: { type: 'text' },
+ },
+ workspaceId,
+ );
+
for (const agentWorkflow of AGENT_WORKFLOWS_TO_SEED) {
const stepId = seedId(agentWorkflow.stepKey, workspaceId);
- const agent = await this.agentService.createOneAgent(
- {
- label: 'Workflow Agent ' + stepId.substring(0, 4),
- icon: 'IconLego',
- description: '',
- prompt:
- 'You are a helpful AI assistant. Complete the task based on the workflow context.',
- modelId: AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
- responseFormat: { type: 'text' },
- isSystem: true,
- },
- workspaceId,
- );
const step: WorkflowAiAgentAction = {
id: stepId,
name: agentWorkflow.stepName,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
index b802c5f87ee..220e5f8b395 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
@@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common';
import { msg } from '@lingui/core/macro';
-import { isNonEmptyString } from '@sniptt/guards';
+import { isNonEmptyString, isString } from '@sniptt/guards';
import { inputSchemaToOutputSchema } from 'twenty-shared/logic-function';
import {
FieldMetadataType,
@@ -528,6 +528,11 @@ export class WorkflowVersionStepOperationsWorkspaceService {
const defaultAgentId = isPlainObject(defaultAgentInput)
? defaultAgentInput.agentId
: undefined;
+ // the prompt is the user's own text, so switching an AI step's kind or agent keeps it
+ const defaultPrompt =
+ isPlainObject(defaultAgentInput) && isString(defaultAgentInput.prompt)
+ ? defaultAgentInput.prompt
+ : '';
if (isNonEmptyString(defaultAgentId)) {
const agent =
@@ -544,7 +549,7 @@ export class WorkflowVersionStepOperationsWorkspaceService {
...BASE_STEP_DEFINITION,
input: {
agentId: agent.id,
- prompt: '',
+ prompt: defaultPrompt,
},
},
},
@@ -560,7 +565,7 @@ export class WorkflowVersionStepOperationsWorkspaceService {
...BASE_STEP_DEFINITION,
input: {
instructions: '',
- prompt: '',
+ prompt: defaultPrompt,
},
},
},
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/__tests__/ai-agent.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/__tests__/ai-agent.workflow-action.spec.ts
new file mode 100644
index 00000000000..2fd8da9ea8c
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/__tests__/ai-agent.workflow-action.spec.ts
@@ -0,0 +1,95 @@
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import { type AgentRunPersonaService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-persona.service';
+import { type AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
+import { WorkflowStepExecutorExceptionCode } from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+import { type WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
+import { AiAgentWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action';
+import { type WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
+import { type WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';
+
+const executeWithInput = async (input: Record<string, unknown>) => {
+ const agentRunnerService = { start: jest.fn() };
+ const action = new AiAgentWorkflowAction(
+ agentRunnerService as unknown as AgentRunnerService,
+ {
+ getExecutionContext: jest.fn().mockResolvedValue({
+ application: { id: 'application-id' },
+ authContext: { type: 'api-key' },
+ }),
+ assertRunApplicationCanTriggerStepTargetOrThrow: jest.fn(),
+ } as unknown as WorkflowExecutionContextService,
+ {
+ setAiAgentStepLog: jest.fn(),
+ } as unknown as WorkflowRunStepLogWorkspaceService,
+ {
+ openConversation: jest.fn().mockResolvedValue({ threadId: 'thread-id' }),
+ } as unknown as WorkflowAgentConversationWorkspaceService,
+ {
+ resolveOrThrow: jest
+ .fn()
+ .mockResolvedValue({ applicationId: 'application-id', modelId: 'm' }),
+ } as unknown as AgentRunPersonaService,
+ );
+
+ const execution = action.execute({
+ currentStepId: 'step-id',
+ steps: [
+ {
+ id: 'step-id',
+ name: 'Summarize',
+ type: WorkflowActionType.AI_AGENT,
+ valid: true,
+ settings: {
+ input,
+ outputSchema: {},
+ errorHandlingOptions: {
+ continueOnFailure: { value: false },
+ retryOnFailure: { value: 0 },
+ },
+ },
+ nextStepIds: [],
+ },
+ ] as never,
+ context: { trigger: { note: ' ' } },
+ runInfo: { workflowRunId: 'run-id', workspaceId: 'workspace-id' },
+ });
+
+ return { execution, agentRunnerService };
+};
+
+describe('AiAgentWorkflowAction', () => {
+ it.each([
+ ['no prompt', {}],
+ ['a blank prompt', { prompt: ' ' }],
+ ['a prompt resolving to blank', { prompt: '{{trigger.note}}' }],
+ ])('fails a Generate step with %s', async (_, input) => {
+ const { execution, agentRunnerService } = await executeWithInput(input);
+
+ await expect(execution).rejects.toMatchObject({
+ code: WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ });
+ expect(agentRunnerService.start).not.toHaveBeenCalled();
+ });
+
+ it('starts a Generate step that has a prompt', async () => {
+ const { execution, agentRunnerService } = await executeWithInput({
+ prompt: 'Summarize the deal',
+ });
+
+ await expect(execution).resolves.toEqual({ wait: { type: 'CALLBACK' } });
+ expect(agentRunnerService.start).toHaveBeenCalledTimes(1);
+ });
+
+ it('starts an Agent step without a prompt', async () => {
+ const { execution, agentRunnerService } = await executeWithInput({
+ agentId: '20202020-0000-4000-8000-000000000001',
+ });
+
+ await expect(execution).resolves.toEqual({ wait: { type: 'CALLBACK' } });
+ expect(agentRunnerService.start).toHaveBeenCalledTimes(1);
+ expect(agentRunnerService.start).toHaveBeenCalledWith(
+ expect.objectContaining({ prompt: null }),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
index 78241695189..a08c4697d6e 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
@@ -107,6 +107,21 @@ export class AiAgentWorkflowAction implements WorkflowAction {
);
}
+ const resolvedPrompt = resolveInput(prompt, context) as string | undefined;
+ const isGenerateStep = isWorkflowAiAgentGenerateStep(step.settings.input);
+
+ // a Test run skips activation's validation, and a Generate step has nothing to answer without a prompt
+ const isPromptEmpty =
+ !isDefined(resolvedPrompt) ||
+ (isString(resolvedPrompt) && !isNonEmptyString(resolvedPrompt.trim()));
+
+ if (isGenerateStep && isPromptEmpty) {
+ throw new WorkflowStepExecutorException(
+ `AI step "${step.name}" has no prompt.`,
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ );
+ }
+
const executionContext =
await this.workflowExecutionContextService.getExecutionContext(runInfo);
@@ -129,8 +144,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
);
// an Agent step converses so it keeps its wait tools; a Generate step runs one-shot
- const hasConversation = !isWorkflowAiAgentGenerateStep(step.settings.input);
- const conversation = hasConversation
+ const conversation = !isGenerateStep
? await this.workflowAgentConversationService.openConversation({
runInfo,
stepId: currentStepId,
@@ -153,8 +167,6 @@ export class AiAgentWorkflowAction implements WorkflowAction {
})
: null;
- const resolvedPrompt = resolveInput(prompt, context) as string | undefined;
-
// a conversation is linked from the start, so the run can be followed while it goes on
await this.workflowRunStepLogService.setAiAgentStepLog({
workflowRunId: runInfo.workflowRunId,
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-draft-step-resources.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-draft-step-resources.integration-spec.ts
index 6f95702bccd..b8f97d09f3a 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-draft-step-resources.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-draft-step-resources.integration-spec.ts
@@ -216,7 +216,63 @@ describe('AI agent step duplication and deletion (e2e)', () => {
});
describe('AI agent step kind change (e2e)', () => {
- it('refuses to switch a Generate step to an agent', async () => {
+ it('switches a Generate step to an agent and keeps its prompt', async () => {
+ const { data: agentData } = await createOneAgent({
+ expectToFail: false,
+ input: {
+ label: 'Kind Change Agent',
+ prompt: 'You qualify leads.',
+ modelId: TEST_AI_MODEL_ID,
+ },
+ });
+ const agentId = agentData.createOneAgent.id;
+ const { coreWorkflowId, coreWorkflowVersionId } = await createCoreWorkflow({
+ name: 'AI Step Kind Switch Test',
+ });
+
+ await updateCoreWorkflowVersionTrigger({
+ coreWorkflowVersionId,
+ trigger: {
+ name: 'Manual Trigger',
+ type: 'MANUAL',
+ settings: { outputSchema: {} },
+ nextStepIds: [],
+ position: { x: 0, y: 0 },
+ },
+ });
+
+ const generateStep = await createCoreWorkflowVersionStep<AiAgentStep>({
+ coreWorkflowVersionId,
+ stepType: 'AI_AGENT',
+ });
+
+ await updateCoreWorkflowVersionStep({
+ coreWorkflowVersionId,
+ step: {
+ ...generateStep,
+ settings: {
+ ...generateStep.settings,
+ input: { prompt: 'Qualify the lead', agentId },
+ },
+ },
+ });
+
+ const { steps } = await findCoreWorkflowVersion<AiAgentStep>({
+ coreWorkflowVersionId,
+ });
+
+ expect(
+ steps?.find((step) => step.id === generateStep.id)?.settings.input,
+ ).toEqual({
+ agentId,
+ prompt: 'Qualify the lead',
+ });
+
+ await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });
+ await deleteOneAgent({ expectToFail: false, input: { id: agentId } });
+ });
+
+ it('refuses to switch a Generate step to an agent that does not exist', async () => {
const { coreWorkflowId, coreWorkflowVersionId } = await createCoreWorkflow({
name: 'AI Step Kind Change Test',
});
@@ -251,7 +307,7 @@ describe('AI agent step kind change (e2e)', () => {
},
},
}),
- ).rejects.toThrow('Create a new step instead');
+ ).rejects.toThrow('not found');
await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });
});