The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(workflow): let an agent step pause on a question until someone answers (#26766)
Félix Malfait3a1e3c6a5466
diff --git a/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts b/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.tsindex 5055119369a..8c0d5c483de 100644--- a/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts@@ -25,6 +25,7 @@ import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEventimport { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';import { markWorkspaceCreditsExhausted } from '@/workspace/utils/updateWorkspaceResourceCreditCap';import { useToast } from 'twenty-ui/components';+import { type AnswerAgentChatQuestionMutation } from '~/generated-metadata/graphql';import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';export const useSubmitQuestionAnswer = () => {@@ -91,18 +92,25 @@ export const useSubmitQuestionAnswer = () => {store.set(agentChatUploadedFilesState.atom, []);try {- await apolloClient.mutate({- mutation: ANSWER_AGENT_CHAT_QUESTION,- variables: {- threadId,- messageId,- answers,- modelId: modelIdForRequest,- fileAttachments: isNonEmptyArray(fileAttachments)- ? fileAttachments- : undefined,- },- });+ const { data } =+ await apolloClient.mutate<AnswerAgentChatQuestionMutation>({+ mutation: ANSWER_AGENT_CHAT_QUESTION,+ variables: {+ threadId,+ messageId,+ answers,+ modelId: modelIdForRequest,+ fileAttachments: isNonEmptyArray(fileAttachments)+ ? fileAttachments+ : undefined,+ },+ });++ // A workflow agent's answer resumes its run, not a chat stream, so+ // no first chunk will arrive.+ if (!isDefined(data?.answerAgentChatQuestion.streamId)) {+ store.set(isAwaitingFirstChunkAtom, false);+ }dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);} catch (error) {diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsxindex b5f772c320e..9c9d58f0c51 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsx@@ -5,6 +5,7 @@ import { agentResponseSchemaToOutputSchema } from '@/ai/utils/agentResponseSchemimport { createDefaultOutputSchemaField } from '@/ai/utils/createDefaultOutputSchemaField';import { fieldsToSchema } from '@/ai/utils/fieldsToSchema';import { schemaToFields } from '@/ai/utils/schemaToFields';+import { FormBooleanFieldInput } from '@/object-record/record-field/ui/form-types/components/FormBooleanFieldInput';import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';import { type WorkflowAiAgentAction } from '@/workflow/types/Workflow';@@ -125,6 +126,19 @@ export const WorkflowAiAgentPromptTab = ({});};+ const handleCanAskQuestionsChange = (value: boolean | string | null) => {+ onActionUpdate?.({+ ...action,+ settings: {+ ...action.settings,+ input: {+ ...action.settings.input,+ canAskQuestions: value === true,+ },+ },+ });+ };+const handleOutputSchemaChange = (updatedFields: OutputSchemaField[]) => {setOutputSchemaFields(updatedFields);void debouncedUpdateResponseSchema(fieldsToSchema(updatedFields));@@ -148,6 +162,13 @@ export const WorkflowAiAgentPromptTab = ({readonly={readonly}/>+ <FormBooleanFieldInput+ label={t`Can ask questions`}+ defaultValue={action.settings.input.canAskQuestions === true}+ readonly={readonly}+ onChange={handleCanAskQuestionsChange}+ />+<SettingsAgentModelCapabilitiesselectedModelId={agent.modelId}modelConfiguration={agent.modelConfiguration || {}}diff --git a/packages/twenty-server/src/database/commands/data-seed-dev-workspace.command.ts b/packages/twenty-server/src/database/commands/data-seed-dev-workspace.command.tsindex 2bef6b74ace..4e24f07ffde 100644--- a/packages/twenty-server/src/database/commands/data-seed-dev-workspace.command.ts+++ b/packages/twenty-server/src/database/commands/data-seed-dev-workspace.command.ts@@ -7,7 +7,7 @@ import {SEED_YCOMBINATOR_WORKSPACE_ID,SeededWorkspacesIds,} from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';-import { DevSeederService } from 'src/engine/workspace-manager/dev-seeder/services/dev-seeder.service';+import { DevSeederWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/services/dev-seeder.workspace-service';type DataSeedWorkspaceOptions = {light?: boolean;@@ -21,7 +21,9 @@ type DataSeedWorkspaceOptions = {export class DataSeedWorkspaceCommand extends CommandRunner {private readonly logger = new Logger(DataSeedWorkspaceCommand.name);- constructor(private readonly devSeederService: DevSeederService) {+ constructor(+ private readonly devSeederWorkspaceService: DevSeederWorkspaceService,+ ) {super();}@@ -44,7 +46,7 @@ export class DataSeedWorkspaceCommand extends CommandRunner {try {for (const workspaceId of workspaceIds) {- await this.devSeederService.seedDev(workspaceId, {+ await this.devSeederWorkspaceService.seedDev(workspaceId, {light: options.light,});}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.tsindex 4028a6878c5..63cddab5266 100644--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.ts+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.ts@@ -19,7 +19,6 @@ import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspaconst WORKFLOW_RUN_THREAD_FIELD_UNIVERSAL_IDENTIFIERS = [STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier,- STANDARD_OBJECTS.agentChatThread.fields.workflowStepId.universalIdentifier,STANDARD_OBJECTS.workflowRun.fields.agentChatThreads.universalIdentifier,];diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.tsindex a8f719c470a..b65b29d8945 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts@@ -5,6 +5,7 @@ import {generateText,jsonSchema,type LanguageModelUsage,+ type ModelMessage,Output,isStepCount,type StepResult,@@ -51,6 +52,7 @@ import { type AgentToolLoadingStrategy } from 'src/engine/metadata-modules/ai/aiimport { assertAgentResponseFormatHasOutputFieldsOrThrow } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/assert-agent-response-format-has-output-fields-or-throw.util';import { buildAgentRolePermissionConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util';import { buildStrictAgentResponseSchema } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-strict-agent-response-schema.util';+import { endsOnPausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util';import { AGENT_CONFIG } from 'src/engine/metadata-modules/ai/ai-agent/constants/agent-config.const';import { STRUCTURED_OUTPUT_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/structured-output-system-prompt.const';import { type AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';@@ -271,9 +273,17 @@ export class AgentAsyncExecutorService {runAsRoleId,operationType = UsageOperationType.AI_WORKFLOW_TOKEN,toolLoadingStrategy = 'preload',+ priorModelMessages = [],+ pausingTools = {},}: {agent: AgentEntity | null;messages: RunAgentMessage[];+ // A conversation being continued, with its tool calls and results, which+ // plain run messages cannot carry.+ priorModelMessages?: ModelMessage[];+ // Tools whose call ends the execution so that the caller can wait for+ // something outside it, such as a person answering.+ pausingTools?: ToolSet;baseSystemPrompt: string;actorContext?: ActorMetadata;authContext?: WorkspaceAuthContext;@@ -283,7 +293,7 @@ export class AgentAsyncExecutorService {operationType?: UsageOperationType;toolLoadingStrategy?: AgentToolLoadingStrategy;}): Promise<AgentExecutionResult> {- if (!isNonEmptyArray(messages)) {+ if (!isNonEmptyArray(messages) && !isNonEmptyArray(priorModelMessages)) {throw new AiException('Provide at least one message to run an agent',AiExceptionCode.INVALID_AGENT_INPUT,@@ -395,13 +405,16 @@ export class AgentAsyncExecutorService {)?.modalities,});+ const pausingToolNames = Object.keys(pausingTools);+const textResponse = await generateText({instructions: `${baseSystemPrompt}\n\n${agent ? tipTapDocumentToMarkdown(agent.prompt) : ''}${toolCatalogSection}`,- tools,+ tools: { ...tools, ...pausingTools },model: registeredModel.model,- messages: modelMessages,+ messages: [...priorModelMessages, ...modelMessages],stopWhen: (step) =>isStepCount(AGENT_CONFIG.MAX_STEPS)(step) ||+ endsOnPausingToolCall({ steps: step.steps, pausingToolNames }) ||hasNoMoreAvailableCredits,providerOptions,...buildAiTelemetry({@@ -506,7 +519,13 @@ export class AgentAsyncExecutorService {let result: object = { response: textResponse.text };- if (agentSchema) {+ const endsOnPausingTool = endsOnPausingToolCall({+ steps: textResponse.steps,+ pausingToolNames,+ });++ // An execution stopped on a pausing tool has no final answer to structure.+ if (isDefined(agentSchema) && !endsOnPausingTool) {const structuredResult = await generateText({instructions: STRUCTURED_OUTPUT_SYSTEM_PROMPT,model: registeredModel.model,@@ -581,6 +600,9 @@ export class AgentAsyncExecutorService {cacheCreationTokens,nativeWebSearchCallCount,hasNoMoreAvailableCredits,+ // An execution out of credits fails even if it asked something, so it+ // must not be left waiting for an answer.+ isPaused: endsOnPausingTool && !hasNoMoreAvailableCredits,steps: executionSteps,modelId: resolvedModelId,totalCostInDollars,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type.tsindex 6397b5825de..c297f48d441 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type.ts@@ -6,6 +6,7 @@ export interface AgentExecutionResult {cacheCreationTokens: number;nativeWebSearchCallCount: number;hasNoMoreAvailableCredits: boolean;+ isPaused?: boolean;steps?: StepResult<ToolSet>[];modelId?: string;totalCostInDollars?: number;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/ends-on-pausing-tool-call.util.spec.tsnew file mode 100644index 00000000000..2976ae6d029--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts@@ -0,0 +1,37 @@+import { endsOnPausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util';++const stepCalling = (...toolNames: string[]) => ({+ toolCalls: toolNames.map((toolName) => ({ toolName })),+});++describe('endsOnPausingToolCall', () => {+ it('pauses when the last step calls a pausing tool', () => {+ expect(+ endsOnPausingToolCall({+ steps: [stepCalling('search'), stepCalling('ask_questions')],+ pausingToolNames: ['ask_questions'],+ }),+ ).toBe(true);+ });++ it('does not pause on a pausing tool called in an earlier step', () => {+ expect(+ endsOnPausingToolCall({+ steps: [stepCalling('ask_questions'), stepCalling('search')],+ pausingToolNames: ['ask_questions'],+ }),+ ).toBe(false);+ });++ it('never pauses without pausing tools or steps', () => {+ expect(+ endsOnPausingToolCall({+ steps: [stepCalling('ask_questions')],+ pausingToolNames: [],+ }),+ ).toBe(false);+ expect(+ endsOnPausingToolCall({ steps: [], pausingToolNames: ['ask_questions'] }),+ ).toBe(false);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/map-ui-message-parts-to-persisted-db-parts.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/map-ui-message-parts-to-persisted-db-parts.util.spec.tsnew file mode 100644index 00000000000..30b8966ea75--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/map-ui-message-parts-to-persisted-db-parts.util.spec.ts@@ -0,0 +1,46 @@+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';++import { mapUIMessagePartsToPersistedDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util';++describe('mapUIMessagePartsToPersistedDBParts', () => {+ it('stores a dangling tool call as an interrupted one', () => {+ const [storedPart] = mapUIMessagePartsToPersistedDBParts(+ [+ {+ type: 'tool-search',+ toolCallId: 'call-1',+ state: 'input-available',+ input: { query: 'acme' },+ } as unknown as ExtendedUIMessagePart,+ ],+ 'message-id',+ 'workspace-id',+ );++ expect(storedPart).toMatchObject({+ messageId: 'message-id',+ toolCallId: 'call-1',+ state: 'output-error',+ errorMessage: 'Tool execution was interrupted.',+ });+ });++ it('drops a tool call still streaming its input', () => {+ expect(+ mapUIMessagePartsToPersistedDBParts(+ [+ { type: 'text', text: 'Looking it up' },+ {+ type: 'tool-search',+ toolCallId: 'call-1',+ state: 'input-streaming',+ } as unknown as ExtendedUIMessagePart,+ ],+ 'message-id',+ 'workspace-id',+ ),+ ).toEqual([+ expect.objectContaining({ type: 'text', textContent: 'Looking it up' }),+ ]);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.tsnew file mode 100644index 00000000000..a086e2d9642--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.ts@@ -0,0 +1,12 @@+// Not the SDK's hasToolCall: its stop condition may return a promise, and this+// check is also read synchronously once the run returns, to report the pause.+export const endsOnPausingToolCall = ({+ steps,+ pausingToolNames,+}: {+ steps: { toolCalls: { toolName: string }[] }[];+ pausingToolNames: string[];+}): boolean =>+ steps[steps.length - 1]?.toolCalls.some((toolCall) =>+ pausingToolNames.includes(toolCall.toolName),+ ) ?? false;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util.tsnew file mode 100644index 00000000000..2db30328783--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util.ts@@ -0,0 +1,18 @@+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';++import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';+import { finalizeDanglingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/finalize-dangling-tool-parts.util';+import { mapUIMessagePartsToDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts';++// A stored message is replayed to a model later, so a dangling tool part must+// be finalized before it is stored, whichever path records the message.+export const mapUIMessagePartsToPersistedDBParts = (+ uiMessageParts: ExtendedUIMessagePart[],+ messageId: string,+ workspaceId: string,+): Partial<AgentMessagePartWorkspaceEntity>[] =>+ mapUIMessagePartsToDBParts(+ finalizeDanglingToolParts(uiMessageParts),+ messageId,+ workspaceId,+ );diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.tsindex 352809e9c15..af22a6eae52 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts@@ -48,6 +48,9 @@ import { ChatExecutionService } from './services/chat-execution.service';import { MessagePruningService } from './services/message-pruning.service';import { SystemPromptBuilderService } from './services/system-prompt-builder.service';+import { AgentChatWorkflowQuestionService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service';+import { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workflow-runner.module';+@Module({imports: [RecordShareModule,@@ -78,10 +81,12 @@ import { SystemPromptBuilderService } from './services/system-prompt-builder.serToolProviderModule,DashboardToolsModule,WorkflowToolsModule,+ WorkflowRunnerModule,],providers: [AgentChatActorService,AgentChatSharingService,+ AgentChatWorkflowQuestionService,AiChatUsageService,AiChatUsageResolver,AgentChatCancelSubscriberService,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.tsindex a91ad94b132..74b078a7dea 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts@@ -90,6 +90,7 @@ const buildResolver = () => {.mockResolvedValue({ chunks: [], maxSeq: 0 }),};const redis = { getClient: jest.fn() };+ const workflowQuestions = { answer: jest.fn() };const resolver = new AgentChatResolver(chatService,{} as never,@@ -103,6 +104,7 @@ const buildResolver = () => {validateModelAvailability: jest.fn(),} as never,redis as never,+ workflowQuestions as never,threadRepository as never,);return {diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.tsindex 48351aa2bc8..d9b33c965ae 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts@@ -1,6 +1,8 @@import { AuthWorkspaceMemberId } from 'src/engine/decorators/auth/auth-workspace-member-id.decorator';import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';+import { AgentChatWorkflowQuestionService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service';+import { isWorkflowRunThread } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util';import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';import { UseFilters, UseGuards, UseInterceptors } from '@nestjs/common';@@ -84,6 +86,7 @@ export class AgentChatResolver {private readonly aiBillingService: AiBillingService,private readonly aiModelRegistryService: AiModelRegistryService,private readonly redisClientService: RedisClientService,+ private readonly agentChatWorkflowQuestionService: AgentChatWorkflowQuestionService,@InjectAgentHistoryRepository('agentChatThread')private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,) {}@@ -449,6 +452,27 @@ export class AgentChatResolver {@AuthWorkspaceMemberId() workspaceMemberId: string,@AuthWorkspace() workspace: WorkspaceEntity,): Promise<SendChatMessageResultDTO> {+ const readableThread = await this.sharingService.getReadableThread({+ threadId,+ workspaceMemberId,+ workspaceId: workspace.id,+ });++ // A workflow agent's conversation is otherwise read-only: its answer+ // resumes the run rather than a chat stream, so no chat model is involved.+ if (isWorkflowRunThread(readableThread)) {+ await this.agentChatWorkflowQuestionService.answer({+ thread: readableThread,+ messageId,+ answers,+ fileAttachments: fileAttachments ?? undefined,+ userWorkspaceId,+ workspaceId: workspace.id,+ });++ return { messageId, queued: false };+ }+if (this.aiModelRegistryService.getAvailableModels().length === 0) {throw new AiException('No AI models are available. Configure at least one AI provider.',diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-workflow-question.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-workflow-question.service.spec.tsnew file mode 100644index 00000000000..a88591f61ab--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-workflow-question.service.spec.ts@@ -0,0 +1,198 @@+import { type AskQuestionAnswer } from 'twenty-shared/ai';++import { type AgentMessageEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';+import { type AiChatFileAttachment } from 'src/engine/metadata-modules/ai/ai-chat/types/ai-chat-file-attachment.type';+import { AgentChatWorkflowQuestionService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service';+import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';+import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';+import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';+import { type PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';+import { type WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';++const WORKSPACE_ID = 'workspace-id';+const WORKFLOW_RUN_ID = 'workflow-run-id';+const THREAD_ID = 'thread-id';+const QUESTION_MESSAGE_ID = 'question-message-id';+const ANSWER_MESSAGE_ID = 'answer-message-id';++const ROLLBACK = { partId: 'part-id', previousOutput: {} };++describe('AgentChatWorkflowQuestionService', () => {+ const messageRepository = { delete: jest.fn() };++ const agentChatService = {+ resolvePendingQuestion: jest.fn(),+ addMessage: jest.fn(),+ restorePendingQuestion: jest.fn(),+ closePendingQuestion: jest.fn(),+ };++ const permissionsService = {+ userHasWorkspaceSettingPermission: jest.fn(),+ };++ const workflowRunnerWorkspaceService = {+ resumeAgentStepWithAnswer: jest.fn(),+ };++ const service = new AgentChatWorkflowQuestionService(+ messageRepository as unknown as AgentHistoryRepository<AgentMessageEntity>,+ agentChatService as unknown as AgentChatService,+ permissionsService as unknown as PermissionsService,+ workflowRunnerWorkspaceService as unknown as WorkflowRunnerWorkspaceService,+ );++ const answers: AskQuestionAnswer[] = [+ { questionIndex: 0, selectedOptionIndices: [0] },+ ];++ const answer = (+ overrides: {+ answers?: AskQuestionAnswer[];+ fileAttachments?: AiChatFileAttachment[];+ } = {},+ ) =>+ service.answer({+ thread: {+ id: THREAD_ID,+ workflowRunId: WORKFLOW_RUN_ID,+ } as AgentChatThreadWorkspaceEntity & { workflowRunId: string },+ messageId: QUESTION_MESSAGE_ID,+ answers,+ userWorkspaceId: 'user-workspace-id',+ workspaceId: WORKSPACE_ID,+ ...overrides,+ });++ beforeEach(() => {+ jest.clearAllMocks();+ permissionsService.userHasWorkspaceSettingPermission.mockResolvedValue(+ true,+ );+ agentChatService.resolvePendingQuestion.mockResolvedValue({+ answerText: 'Send the quote?\nSend it',+ turnId: 'turn-id',+ rollback: ROLLBACK,+ });+ agentChatService.addMessage.mockResolvedValue({ id: ANSWER_MESSAGE_ID });+ messageRepository.delete.mockResolvedValue(undefined);+ workflowRunnerWorkspaceService.resumeAgentStepWithAnswer.mockResolvedValue({+ status: 'AWAITING_ANSWER',+ stepId: 'agent-step-id',+ });+ });++ it('claims the question without a stream, records the answer and resumes the step', async () => {+ await answer();++ expect(agentChatService.resolvePendingQuestion).toHaveBeenCalledWith({+ threadId: THREAD_ID,+ messageId: QUESTION_MESSAGE_ID,+ answers,+ streamId: null,+ workspaceId: WORKSPACE_ID,+ });+ expect(agentChatService.addMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ threadId: THREAD_ID,+ uiMessage: {+ role: 'user',+ parts: [{ type: 'text', text: 'Send the quote?\nSend it' }],+ },+ }),+ );+ expect(+ workflowRunnerWorkspaceService.resumeAgentStepWithAnswer,+ ).toHaveBeenCalledWith({+ threadId: THREAD_ID,+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ });+ expect(messageRepository.delete).not.toHaveBeenCalled();+ expect(agentChatService.restorePendingQuestion).not.toHaveBeenCalled();+ });++ it('refuses an answer that says nothing', async () => {+ await expect(+ answer({+ answers: [+ { questionIndex: 0, selectedOptionIndices: [], freeText: ' ' },+ ],+ }),+ ).rejects.toMatchObject({ code: AiExceptionCode.INVALID_QUESTION_ANSWER });+ expect(agentChatService.resolvePendingQuestion).not.toHaveBeenCalled();+ });++ it('refuses attachments rather than dropping them', async () => {+ await expect(+ answer({+ fileAttachments: [{ id: 'file-id', filename: 'quote.pdf' }],+ }),+ ).rejects.toMatchObject({ code: AiExceptionCode.INVALID_QUESTION_ANSWER });+ expect(agentChatService.resolvePendingQuestion).not.toHaveBeenCalled();+ });++ it('refuses someone without the Workflows permission before claiming anything', async () => {+ permissionsService.userHasWorkspaceSettingPermission.mockResolvedValue(+ false,+ );++ await expect(answer()).rejects.toMatchObject({+ code: AiExceptionCode.WORKFLOW_RUN_QUESTION_FORBIDDEN,+ });+ expect(agentChatService.resolvePendingQuestion).not.toHaveBeenCalled();+ });++ it('gives the question back when the step has asked but is not parked yet', async () => {+ workflowRunnerWorkspaceService.resumeAgentStepWithAnswer.mockResolvedValue({+ status: 'NOT_YET_AWAITING',+ });++ await expect(answer()).rejects.toMatchObject({+ code: AiExceptionCode.QUESTION_NOT_PENDING,+ });+ expect(messageRepository.delete).toHaveBeenCalledWith(WORKSPACE_ID, {+ id: ANSWER_MESSAGE_ID,+ });+ expect(agentChatService.restorePendingQuestion).toHaveBeenCalledWith({+ threadId: THREAD_ID,+ messageId: QUESTION_MESSAGE_ID,+ streamId: null,+ workspaceId: WORKSPACE_ID,+ rollback: ROLLBACK,+ });+ expect(agentChatService.closePendingQuestion).not.toHaveBeenCalled();+ });++ it('closes a question nothing can resume any more', async () => {+ workflowRunnerWorkspaceService.resumeAgentStepWithAnswer.mockResolvedValue({+ status: 'NO_LONGER_AWAITING',+ });++ await expect(answer()).rejects.toMatchObject({+ code: AiExceptionCode.QUESTION_NOT_PENDING,+ });+ expect(messageRepository.delete).toHaveBeenCalled();+ expect(agentChatService.closePendingQuestion).toHaveBeenCalledWith({+ workspaceId: WORKSPACE_ID,+ rollback: ROLLBACK,+ });+ expect(agentChatService.restorePendingQuestion).not.toHaveBeenCalled();+ });++ it('gives the question back when the resume cannot be scheduled', async () => {+ workflowRunnerWorkspaceService.resumeAgentStepWithAnswer.mockRejectedValue(+ new Error('Queue unavailable'),+ );++ await expect(answer()).rejects.toThrow('Queue unavailable');+ expect(messageRepository.delete).toHaveBeenCalled();+ expect(agentChatService.restorePendingQuestion).toHaveBeenCalledWith(+ expect.objectContaining({+ streamId: null,+ messageId: QUESTION_MESSAGE_ID,+ }),+ );+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.resolve-pending-question.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.resolve-pending-question.spec.tsnew file mode 100644index 00000000000..2c750743d23--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.resolve-pending-question.spec.ts@@ -0,0 +1,115 @@+import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';+import { IsNull } from 'typeorm';++import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';++const WORKSPACE_ID = 'workspace-id';+const THREAD_ID = 'thread-id';+const QUESTION_MESSAGE_ID = 'question-message-id';++const QUESTIONS = [+ {+ header: 'Quote',+ question: 'Send the quote?',+ options: [{ label: 'Send it' }, { label: 'Hold it' }],+ },+];++const buildService = () => {+ const threadRepository = {+ update: jest.fn().mockResolvedValue({ affected: 1 }),+ };+ const messageRepository = {+ findOne: jest.fn().mockResolvedValue({+ id: QUESTION_MESSAGE_ID,+ turnId: 'turn-id',+ parts: [+ {+ id: 'part-id',+ toolName: ASK_QUESTIONS_TOOL_NAME,+ toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },+ },+ ],+ }),+ };+ const messagePartRepository = {+ update: jest.fn().mockResolvedValue({ affected: 1 }),+ };++ const service = new AgentChatService(+ threadRepository as never,+ {} as never,+ messageRepository as never,+ messagePartRepository as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ );++ return { service, threadRepository, messagePartRepository };+};++const resolveWithoutStream = (service: AgentChatService) =>+ service.resolvePendingQuestion({+ threadId: THREAD_ID,+ messageId: QUESTION_MESSAGE_ID,+ answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],+ streamId: null,+ workspaceId: WORKSPACE_ID,+ });++describe('AgentChatService resolvePendingQuestion without a stream', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it('claims the question by clearing its marker, leaving the thread free', async () => {+ const { service, threadRepository, messagePartRepository } = buildService();++ const resolved = await resolveWithoutStream(service);++ expect(threadRepository.update).toHaveBeenCalledTimes(1);+ expect(threadRepository.update).toHaveBeenCalledWith(+ WORKSPACE_ID,+ { id: THREAD_ID, pendingQuestionMessageId: QUESTION_MESSAGE_ID },+ { pendingQuestionMessageId: null },+ );+ expect(messagePartRepository.update).toHaveBeenCalledWith(+ WORKSPACE_ID,+ { id: 'part-id' },+ expect.objectContaining({+ toolOutput: expect.objectContaining({+ result: expect.objectContaining({ status: 'answered' }),+ }),+ }),+ );+ expect(resolved.answerText).toBe('Send the quote?\nSend it');+ });++ it('refuses an answer another one has already claimed', async () => {+ const { service, threadRepository, messagePartRepository } = buildService();++ threadRepository.update.mockResolvedValue({ affected: 0 });++ await expect(resolveWithoutStream(service)).rejects.toThrow(+ 'No pending question to answer',+ );+ expect(threadRepository.update).toHaveBeenCalledTimes(1);+ expect(messagePartRepository.update).not.toHaveBeenCalled();+ });++ it('puts the marker back when the question cannot be marked answered', async () => {+ const { service, threadRepository, messagePartRepository } = buildService();++ messagePartRepository.update.mockRejectedValue(new Error('write failed'));++ await expect(resolveWithoutStream(service)).rejects.toThrow('write failed');+ expect(threadRepository.update).toHaveBeenLastCalledWith(+ WORKSPACE_ID,+ { id: THREAD_ID, pendingQuestionMessageId: IsNull() },+ { pendingQuestionMessageId: QUESTION_MESSAGE_ID },+ );+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.tsindex 639007134da..8c322125b04 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts@@ -40,6 +40,7 @@ import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/aimport { AgentChatStreamHeartbeatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-heartbeat.service';import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';import { AiChatFileAttachment } from 'src/engine/metadata-modules/ai/ai-chat/types/ai-chat-file-attachment.type';+import { hasQuestionAnswerContent } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util';import { mapErrorToStreamError } from 'src/engine/metadata-modules/ai/ai-chat/utils/map-error-to-stream-error.util';import {AiException,@@ -550,11 +551,7 @@ export class AgentChatStreamingService {workspaceId: workspace.id,});if (- !answers.some(- (answer) =>- isNonEmptyString(answer.freeText?.trim()) ||- isNonEmptyArray(answer.selectedOptionIndices),- ) &&+ !hasQuestionAnswerContent(answers) &&!isNonEmptyArray(fileAttachments)) {throw new AiException(diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service.tsnew file mode 100644index 00000000000..f8ccaaec956--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service.ts@@ -0,0 +1,160 @@+import { Injectable } from '@nestjs/common';++import { isNonEmptyString } from '@sniptt/guards';+import { PermissionFlagType } from 'twenty-shared/constants';+import { type AskQuestionAnswer } from 'twenty-shared/ai';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';++import { type AgentMessageEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';+import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';+import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';+import { type AiChatFileAttachment } from 'src/engine/metadata-modules/ai/ai-chat/types/ai-chat-file-attachment.type';+import { hasQuestionAnswerContent } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util';+import { type WorkflowRunThreadFields } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.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 {+ AiException,+ AiExceptionCode,+} from 'src/engine/metadata-modules/ai/ai.exception';+import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';+import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';++// A workflow agent's question is answered in its run's conversation, but what+// the answer resumes is the run, not a chat stream: this records the answer in+// the conversation and hands the step back to the workflow runner, which+// continues the same conversation with it.+@Injectable()+export class AgentChatWorkflowQuestionService {+ constructor(+ @InjectAgentHistoryRepository('agentMessage')+ private readonly messageRepository: AgentHistoryRepository<AgentMessageEntity>,+ private readonly agentChatService: AgentChatService,+ private readonly permissionsService: PermissionsService,+ private readonly workflowRunnerWorkspaceService: WorkflowRunnerWorkspaceService,+ ) {}++ async answer({+ thread,+ messageId,+ answers,+ fileAttachments,+ userWorkspaceId,+ workspaceId,+ }: {+ thread: AgentChatThreadWorkspaceEntity & WorkflowRunThreadFields;+ messageId: string;+ answers: AskQuestionAnswer[];+ fileAttachments?: AiChatFileAttachment[];+ userWorkspaceId: string;+ workspaceId: string;+ }): Promise<void> {+ const { workflowRunId } = thread;++ if (!isNonEmptyString(workflowRunId)) {+ throw new AiException(+ 'This conversation does not belong to a workflow run',+ AiExceptionCode.QUESTION_NOT_PENDING,+ );+ }++ // Only the answer's text is recorded for the resumed agent, so an+ // attachment would be dropped without the agent ever seeing it.+ if (isNonEmptyArray(fileAttachments)) {+ throw new AiException(+ 'A workflow agent question cannot be answered with attachments',+ AiExceptionCode.INVALID_QUESTION_ANSWER,+ );+ }++ if (!hasQuestionAnswerContent(answers)) {+ throw new AiException(+ 'Provide an answer',+ AiExceptionCode.INVALID_QUESTION_ANSWER,+ );+ }++ // The same permission that lets someone submit a workflow's form.+ const canAnswer =+ await this.permissionsService.userHasWorkspaceSettingPermission({+ userWorkspaceId,+ workspaceId,+ setting: PermissionFlagType.WORKFLOWS,+ applicationId: undefined,+ });++ if (!canAnswer) {+ throw new AiException(+ 'Answering a workflow question requires the Workflows permission',+ AiExceptionCode.WORKFLOW_RUN_QUESTION_FORBIDDEN,+ );+ }++ // No chat stream continues a workflow conversation, so its question is+ // claimed by its marker alone and nothing is left holding the thread.+ const resolved = await this.agentChatService.resolvePendingQuestion({+ threadId: thread.id,+ messageId,+ answers,+ streamId: null,+ workspaceId,+ });++ let answerMessageId: string | undefined;+ let isNoLongerAwaited = false;++ try {+ const answerMessage = await this.agentChatService.addMessage({+ threadId: thread.id,+ uiMessage: {+ role: 'user',+ parts: [{ type: 'text', text: resolved.answerText }],+ },+ turnId: resolved.turnId ?? undefined,+ workspaceId,+ userWorkspaceId,+ });++ answerMessageId = answerMessage.id;++ const stepAwaitingAnswer =+ await this.workflowRunnerWorkspaceService.resumeAgentStepWithAnswer({+ threadId: thread.id,+ workflowRunId,+ workspaceId,+ });++ isNoLongerAwaited = stepAwaitingAnswer.status === 'NO_LONGER_AWAITING';++ if (stepAwaitingAnswer.status !== 'AWAITING_ANSWER') {+ throw new AiException(+ 'This workflow is no longer waiting for this answer',+ AiExceptionCode.QUESTION_NOT_PENDING,+ );+ }+ } catch (error) {+ if (isDefined(answerMessageId)) {+ await this.messageRepository+ .delete(workspaceId, { id: answerMessageId })+ .catch(() => {});+ }++ if (isNoLongerAwaited) {+ await this.agentChatService.closePendingQuestion({+ workspaceId,+ rollback: resolved.rollback,+ });+ } else {+ await this.agentChatService.restorePendingQuestion({+ threadId: thread.id,+ messageId,+ streamId: null,+ workspaceId,+ rollback: resolved.rollback,+ });+ }++ throw error;+ }+ }+}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.tsindex f3d9d446f39..fa8d5415653 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts@@ -29,8 +29,7 @@ import {} from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';import { AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';import { AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity';-import { finalizeDanglingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/finalize-dangling-tool-parts.util';-import { mapUIMessagePartsToDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts';+import { mapUIMessagePartsToPersistedDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util';import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';import {AiException,@@ -46,6 +45,11 @@ import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/aimport { AgentTitleGenerationService } from './agent-title-generation.service';import { AgentChatThreadDTO } from '../dtos/agent-chat-thread.dto';+type PendingQuestionRollback = {+ partId: string;+ previousOutput: Record<string, unknown> & { result?: AskQuestionsToolResult };+};+@Injectable()export class AgentChatService {private readonly logger = new Logger(AgentChatService.name);@@ -379,8 +383,8 @@ export class AgentChatService {const savedMessageId = (id ?? insertResult.identifiers[0].id) as string;if (uiMessage.parts && uiMessage.parts.length > 0) {- const dbParts = mapUIMessagePartsToDBParts(- finalizeDanglingToolParts(uiMessage.parts),+ const dbParts = mapUIMessagePartsToPersistedDBParts(+ uiMessage.parts,savedMessageId,workspaceId,);@@ -432,11 +436,7 @@ export class AgentChatService {await this.messagePartRepository.delete(workspaceId, { messageId: id });- const dbParts = mapUIMessagePartsToDBParts(- finalizeDanglingToolParts(parts),- id,- workspaceId,- );+ const dbParts = mapUIMessagePartsToPersistedDBParts(parts, id, workspaceId);if (dbParts.length > 0) {await this.messagePartRepository.insert(@@ -795,12 +795,14 @@ export class AgentChatService {threadId: string;messageId: string;answers: AskQuestionAnswer[];- streamId: string;+ // Null for a conversation no chat stream continues, such as a workflow+ // run's: its question is claimed by its marker alone.+ streamId: string | null;workspaceId: string;}): Promise<{answerText: string;turnId: string | null;- rollback: { partId: string; previousOutput: Record<string, unknown> };+ rollback: PendingQuestionRollback;}> {const message = await this.messageRepository.findOne(workspaceId, {where: { id: messageId, threadId },@@ -829,42 +831,27 @@ export class AgentChatService {}const previousOutput =- (pendingPart.toolOutput as Record<string, unknown> | null) ?? {};- const previousResult = previousOutput.result as- | AskQuestionsToolResult- | undefined;- const questions = previousResult?.questions ?? [];+ (pendingPart.toolOutput as+ | PendingQuestionRollback['previousOutput']+ | null) ?? {};+ const questions = previousOutput.result?.questions ?? [];this.validateQuestionAnswers(answers, questions);- const claim = await this.threadRepository.update(- workspaceId,- {- id: threadId,- pendingQuestionMessageId: messageId,- activeStreamId: IsNull(),- },- {- pendingQuestionMessageId: null,- activeStreamId: streamId,- lastStreamError: null,- },- );-- if ((claim.affected ?? 0) === 0) {- const adopted = await this.claimOrphanedQuestion({- threadId,- messageId,- streamId,- workspaceId,- });+ const isClaimed = isDefined(streamId)+ ? await this.claimQuestionForStream({+ threadId,+ messageId,+ streamId,+ workspaceId,+ })+ : await this.claimQuestionMarker({ threadId, messageId, workspaceId });- if (!adopted) {- throw new AiException(- 'No pending question to answer',- AiExceptionCode.QUESTION_NOT_PENDING,- );- }+ if (!isClaimed) {+ throw new AiException(+ 'No pending question to answer',+ AiExceptionCode.QUESTION_NOT_PENDING,+ );}try {@@ -885,13 +872,12 @@ export class AgentChatService {},);} catch (error) {- await this.threadRepository- .update(- workspaceId,- { id: threadId, activeStreamId: streamId },- { pendingQuestionMessageId: messageId, activeStreamId: null },- )- .catch(() => {});+ await this.releaseQuestionClaim({+ threadId,+ messageId,+ streamId,+ workspaceId,+ });throw error;}@@ -914,6 +900,90 @@ export class AgentChatService {};}+ private async claimQuestionForStream({+ threadId,+ messageId,+ streamId,+ workspaceId,+ }: {+ threadId: string;+ messageId: string;+ streamId: string;+ workspaceId: string;+ }): Promise<boolean> {+ const claim = await this.threadRepository.update(+ workspaceId,+ {+ id: threadId,+ pendingQuestionMessageId: messageId,+ activeStreamId: IsNull(),+ },+ {+ pendingQuestionMessageId: null,+ activeStreamId: streamId,+ lastStreamError: null,+ },+ );++ if ((claim.affected ?? 0) > 0) {+ return true;+ }++ return this.claimOrphanedQuestion({+ threadId,+ messageId,+ streamId,+ workspaceId,+ });+ }++ // Clearing the marker is the claim: of two concurrent answers only one+ // matches it. No orphan is adopted here, since without a stream an orphaned+ // question cannot be told apart from one another answer has just claimed.+ private async claimQuestionMarker({+ threadId,+ messageId,+ workspaceId,+ }: {+ threadId: string;+ messageId: string;+ workspaceId: string;+ }): Promise<boolean> {+ const claim = await this.threadRepository.update(+ workspaceId,+ { id: threadId, pendingQuestionMessageId: messageId },+ { pendingQuestionMessageId: null },+ );++ return (claim.affected ?? 0) > 0;+ }++ private async releaseQuestionClaim({+ threadId,+ messageId,+ streamId,+ workspaceId,+ }: {+ threadId: string;+ messageId: string;+ streamId: string | null;+ workspaceId: string;+ }): Promise<void> {+ const release = isDefined(streamId)+ ? this.threadRepository.update(+ workspaceId,+ { id: threadId, activeStreamId: streamId },+ { pendingQuestionMessageId: messageId, activeStreamId: null },+ )+ : this.threadRepository.update(+ workspaceId,+ { id: threadId, pendingQuestionMessageId: IsNull() },+ { pendingQuestionMessageId: messageId },+ );++ await release.catch(() => {});+ }+private async claimOrphanedQuestion({threadId,messageId,@@ -964,9 +1034,9 @@ export class AgentChatService {}: {threadId: string;messageId: string;- streamId: string;+ streamId: string | null;workspaceId: string;- rollback: { partId: string; previousOutput: Record<string, unknown> };+ rollback: PendingQuestionRollback;}): Promise<void> {await this.messagePartRepository.update(@@ -976,11 +1046,35 @@ export class AgentChatService {).catch(() => {});- await this.threadRepository+ await this.releaseQuestionClaim({+ threadId,+ messageId,+ streamId,+ workspaceId,+ });+ }++ // For a question nothing can consume any more: its run ended, or the step+ // moved on to another conversation. Restoring it would leave a card that+ // every answer is refused on, so it is closed instead. An ending run closes+ // its questions itself; this covers an answer that claimed one just before.+ async closePendingQuestion({+ workspaceId,+ rollback,+ }: {+ workspaceId: string;+ rollback: PendingQuestionRollback;+ }): Promise<void> {+ await this.messagePartRepository.update(workspaceId,- { id: threadId, activeStreamId: streamId },- { pendingQuestionMessageId: messageId, activeStreamId: null },+ { id: rollback.partId },+ {+ toolOutput: {+ ...rollback.previousOutput,+ result: { ...rollback.previousOutput.result, status: 'skipped' },+ },+ },).catch(() => {});}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-question-answer-content.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-question-answer-content.util.spec.tsnew file mode 100644index 00000000000..d4b840e1782--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-question-answer-content.util.spec.ts@@ -0,0 +1,25 @@+import { hasQuestionAnswerContent } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util';++describe('hasQuestionAnswerContent', () => {+ it('accepts a selected option or a written answer', () => {+ expect(+ hasQuestionAnswerContent([+ { questionIndex: 0, selectedOptionIndices: [1] },+ ]),+ ).toBe(true);+ expect(+ hasQuestionAnswerContent([+ { questionIndex: 0, selectedOptionIndices: [], freeText: 'Later' },+ ]),+ ).toBe(true);+ });++ it('rejects no answers, or answers that say nothing', () => {+ expect(hasQuestionAnswerContent([])).toBe(false);+ expect(+ hasQuestionAnswerContent([+ { questionIndex: 0, selectedOptionIndices: [], freeText: ' ' },+ ]),+ ).toBe(false);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util.tsnew file mode 100644index 00000000000..90b08fb6a20--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util.ts@@ -0,0 +1,12 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type AskQuestionAnswer } from 'twenty-shared/ai';+import { isNonEmptyArray } from 'twenty-shared/utils';++export const hasQuestionAnswerContent = (+ answers: AskQuestionAnswer[],+): boolean =>+ answers.some(+ (answer) =>+ isNonEmptyString(answer.freeText?.trim()) ||+ isNonEmptyArray(answer.selectedOptionIndices),+ );diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util.tsindex 5497e6dfe0d..f48c6f5f435 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util.ts@@ -1,6 +1,14 @@import { isDefined } from 'twenty-shared/utils';-// Agent history records carry every workspace column, including the run link-// the legacy thread entity type does not declare.-export const isWorkflowRunThread = (thread: object): boolean =>- 'workflowRunId' in thread && isDefined(thread.workflowRunId);+import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';++export type WorkflowRunThreadFields = {+ workflowRunId: string;+};++export const isWorkflowRunThread = <+ TThread extends Pick<AgentChatThreadWorkspaceEntity, 'workflowRunId'>,+>(+ thread: TThread,+): thread is TThread & WorkflowRunThreadFields =>+ isDefined(thread.workflowRunId);diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.tsindex 87c6b5dcfd3..116c649756c 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts@@ -21,7 +21,6 @@ export class AgentChatThreadWorkspaceEntity extends BaseWorkspaceEntity {workspaceMemberId: string | null;workflowRunId: string | null;- workflowStepId: string | null;title: string | null;totalInputTokens: number;totalOutputTokens: number;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.tsindex a371cc51420..6b900eaf452 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts@@ -31,6 +31,7 @@ export enum AiExceptionCode {EVALUATION_QUESTION_UNSUPPORTED = 'EVALUATION_QUESTION_UNSUPPORTED',INVALID_EVALUATION_REQUEST = 'INVALID_EVALUATION_REQUEST',WORKFLOW_RUN_THREAD_READ_ONLY = 'WORKFLOW_RUN_THREAD_READ_ONLY',+ WORKFLOW_RUN_QUESTION_FORBIDDEN = 'WORKFLOW_RUN_QUESTION_FORBIDDEN',}const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {@@ -87,6 +88,8 @@ const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {return msg`Invalid classification request.`;case AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY:return msg`This conversation belongs to a workflow run and can only be read.`;+ case AiExceptionCode.WORKFLOW_RUN_QUESTION_FORBIDDEN:+ return msg`You need the Workflows permission to answer a workflow's question.`;default:assertUnreachable(code);}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.ts b/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.tsindex 6d35fc01f01..6ce40b88462 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.ts@@ -41,6 +41,7 @@ export class AiRestApiExceptionFilter implements ExceptionFilter {503, // Service Unavailable - the AI service is not configured);case AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY:+ case AiExceptionCode.WORKFLOW_RUN_QUESTION_FORBIDDEN:return this.httpExceptionHandlerService.handleError(exception,response,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.tsindex 3243634d1d5..b2d607880df 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts@@ -40,6 +40,7 @@ export const aiGraphqlApiExceptionHandler = (error: Error) => {case AiExceptionCode.RUN_AS_WORKSPACE_MEMBER_NOT_ALLOWED:case AiExceptionCode.RUN_AGENT_NOT_ALLOWED:case AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY:+ case AiExceptionCode.WORKFLOW_RUN_QUESTION_FORBIDDEN:throw new ForbiddenError(error);case AiExceptionCode.AGENT_EXECUTION_FAILED:case AiExceptionCode.API_KEY_NOT_CONFIGURED:diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-agent-question.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-agent-question.workspace-service.tsnew file mode 100644index 00000000000..7c9294389f9--- /dev/null+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-agent-question.workspace-service.ts@@ -0,0 +1,304 @@+import { Injectable } from '@nestjs/common';++import {+ ASK_QUESTIONS_TOOL_NAME,+ type AskQuestionItem,+} from 'twenty-shared/ai';+import { type ActorMetadata, FieldActorSource } from 'twenty-shared/types';+import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';+import { v5 } from 'uuid';++import {+ WorkflowVersionEntity,+ WorkflowVersionStatus,+} from 'src/engine/core-modules/workflow/entities/workflow-version.entity';+import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';+import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';+import { type WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';+import {+ WorkflowStatus,+ type WorkflowWorkspaceEntity,+} from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';+import { type WorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';+import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';+import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';+import {+ type WorkflowManualTrigger,+ WorkflowTriggerType,+} from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';++const WORKFLOW_AGENT_QUESTION_SEED_NAMESPACE =+ '6f0a9a3e-2b1f-4c55-9f0b-7c1d2e3f4a5b';++const seedId = (name: string, workspaceId: string) =>+ v5(`${name}:${workspaceId}`, WORKFLOW_AGENT_QUESTION_SEED_NAMESPACE);++const WORKFLOW_NAME = 'Qualify inbound lead';++const SYSTEM_ACTOR: ActorMetadata = {+ source: FieldActorSource.SYSTEM,+ workspaceMemberId: null,+ name: 'System',+ context: {},+};++const PROMPT =+ 'Qualify the inbound lead from Figma and decide who should follow up.';++const QUESTIONS: AskQuestionItem[] = [+ {+ header: 'Budget',+ question: 'Which budget range did Figma mention on the demo call?',+ options: [+ { label: 'Under $10k' },+ { label: '$10k to $50k', isRecommended: true },+ { label: 'Over $50k' },+ ],+ },+ {+ header: 'Owner',+ question: 'Who should own the follow-up?',+ options: [+ { label: 'Tim', description: 'Account executive' },+ { label: 'Phil', description: 'Solutions engineer' },+ ],+ },+ {+ header: 'Channels',+ question: 'Which channels should the follow-up use?',+ allowMultiSelect: true,+ options: [+ { label: 'Email', isRecommended: true },+ { label: 'Call' },+ { label: 'LinkedIn' },+ ],+ },+];++// Seeds a workflow whose agent step is waiting on a person, so the run view,+// the paused conversation and its question card can be tried without calling+// a model.+@Injectable()+export class DevSeederWorkflowAgentQuestionWorkspaceService {+ constructor(+ private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,+ private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,+ private readonly workspaceOrmManager: WorkspaceOrmManager,+ @InjectWorkspaceScopedRepository(WorkflowEntity)+ private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,+ @InjectWorkspaceScopedRepository(WorkflowVersionEntity)+ private readonly coreWorkflowVersionRepository: WorkspaceScopedRepository<WorkflowVersionEntity>,+ ) {}++ async seed({+ workspaceId,+ applicationId,+ }: {+ workspaceId: string;+ applicationId: string;+ }): Promise<void> {+ const workspaceWorkflowId = seedId('workflow', workspaceId);+ const workspaceWorkflowVersionId = seedId('workflowVersion', workspaceId);+ const coreWorkflowId = seedId('coreWorkflow', workspaceId);+ const coreWorkflowVersionId = seedId('coreWorkflowVersion', workspaceId);++ const agentStep: WorkflowAiAgentAction = {+ id: seedId('agentStep', workspaceId),+ name: 'Qualify the lead',+ type: WorkflowActionType.AI_AGENT,+ valid: true,+ settings: {+ input: {+ prompt: PROMPT,+ canAskQuestions: true,+ },+ outputSchema: {},+ errorHandlingOptions: {+ retryOnFailure: { value: 0 },+ continueOnFailure: { value: false },+ },+ },+ nextStepIds: [],+ };++ const trigger: WorkflowManualTrigger = {+ name: 'Launch manually',+ type: WorkflowTriggerType.MANUAL,+ settings: {+ outputSchema: {},+ icon: 'IconUserCheck',+ availability: { type: 'GLOBAL', locations: undefined },+ },+ nextStepIds: [agentStep.id],+ };++ await this.insertWorkflow({+ workspaceId,+ applicationId,+ workspaceWorkflowId,+ workspaceWorkflowVersionId,+ coreWorkflowId,+ coreWorkflowVersionId,+ trigger,+ agentStep,+ });++ const workflowRunId = seedId('workflowRun', workspaceId);+ const toolCallId = seedId('toolCall', workspaceId);++ await this.workflowRunWorkspaceService.createCoreWorkflowRun({+ workflowRunId,+ coreWorkflowId,+ coreWorkflowVersionId,+ workspaceWorkflowId,+ workspaceWorkflowVersionId,+ workflowName: WORKFLOW_NAME,+ trigger,+ steps: [agentStep],+ createdBy: {+ source: FieldActorSource.MANUAL,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,+ name: 'Tim Apple',+ context: {},+ },+ status: WorkflowRunStatus.NOT_STARTED,+ triggerPayload: {},+ workspaceId,+ });++ await this.workflowRunWorkspaceService.startWorkflowRun({+ workflowRunId,+ workspaceId,+ });++ await this.workflowRunWorkspaceService.updateWorkflowRunStepInfo({+ stepId: agentStep.id,+ stepInfo: { status: StepStatus.PENDING },+ workflowRunId,+ workspaceId,+ });++ await this.workflowAgentConversationService.recordExecution({+ workspaceId,+ workflowRunId,+ stepId: agentStep.id,+ title: agentStep.name,+ agentId: null,+ prompt: PROMPT,+ initiatorUserWorkspaceId: null,+ executionResult: {+ isPaused: true,+ steps: [+ {+ content: [+ {+ type: 'tool-call',+ toolCallId,+ toolName: ASK_QUESTIONS_TOOL_NAME,+ input: { questions: QUESTIONS },+ },+ {+ type: 'tool-result',+ toolCallId,+ toolName: ASK_QUESTIONS_TOOL_NAME,+ input: { questions: QUESTIONS },+ output: {+ success: true,+ message:+ 'Questions presented to the user; awaiting their answer.',+ result: { questions: QUESTIONS, status: 'pending' },+ },+ },+ ],+ },+ ],+ },+ });+ }++ private async insertWorkflow({+ workspaceId,+ applicationId,+ workspaceWorkflowId,+ workspaceWorkflowVersionId,+ coreWorkflowId,+ coreWorkflowVersionId,+ trigger,+ agentStep,+ }: {+ workspaceId: string;+ applicationId: string;+ workspaceWorkflowId: string;+ workspaceWorkflowVersionId: string;+ coreWorkflowId: string;+ coreWorkflowVersionId: string;+ trigger: WorkflowManualTrigger;+ agentStep: WorkflowAiAgentAction;+ }): Promise<void> {+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {+ await this.workspaceOrmManager+ .getRepository<WorkflowWorkspaceEntity>(+ 'workflow',+ { shouldBypassPermissionChecks: true },+ { shouldSkipEventEmission: true },+ )+ .insert({+ id: workspaceWorkflowId,+ name: WORKFLOW_NAME,+ lastPublishedVersionId: workspaceWorkflowVersionId,+ statuses: [WorkflowStatus.ACTIVE],+ position: 3,+ createdBy: SYSTEM_ACTOR,+ updatedBy: SYSTEM_ACTOR,+ coreWorkflowId,+ });++ await this.workspaceOrmManager+ .getRepository<WorkflowVersionWorkspaceEntity>(+ 'workflowVersion',+ { shouldBypassPermissionChecks: true },+ { shouldSkipEventEmission: true },+ )+ .insert({+ id: workspaceWorkflowVersionId,+ name: 'v1',+ trigger,+ steps: [agentStep],+ status: WorkflowVersionStatus.ACTIVE,+ position: 1,+ workflowId: workspaceWorkflowId,+ coreWorkflowVersionId,+ });+ }, buildSystemAuthContext(workspaceId));++ await this.coreWorkflowRepository.insert(workspaceId, {+ id: coreWorkflowId,+ universalIdentifier: seedId('workflowUniversalIdentifier', workspaceId),+ applicationId,+ name: WORKFLOW_NAME,+ lastPublishedVersionId: workspaceWorkflowVersionId,+ workspaceWorkflowId,+ lastPublishedCoreWorkflowVersionId: coreWorkflowVersionId,+ });++ await this.coreWorkflowVersionRepository.insert(workspaceId, {+ id: coreWorkflowVersionId,+ universalIdentifier: seedId(+ 'workflowVersionUniversalIdentifier',+ workspaceId,+ ),+ applicationId,+ triggers: [trigger],+ steps: [agentStep],+ status: WorkflowVersionStatus.ACTIVE,+ workflowId: workspaceWorkflowId,+ coreWorkflowId,+ workspaceWorkflowVersionId,+ });+ }+}diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.tsindex 2142f9f3aef..feefba5df52 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts@@ -10,6 +10,8 @@ import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-import { SdkClientModule } from 'src/engine/core-modules/sdk-client/sdk-client.module';import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.module';import { FileStorageModule } from 'src/engine/core-modules/file-storage/file-storage.module';+import { WorkflowVersionEntity } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';+import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { FieldMetadataModule } from 'src/engine/metadata-modules/field-metadata/field-metadata.module';import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';@@ -28,13 +30,16 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheimport { WorkspaceDataSourceModule } from 'src/engine/workspace-datasource/workspace-datasource.module';import { DevSeederPermissionsService } from 'src/engine/workspace-manager/dev-seeder/core/services/dev-seeder-permissions.service';import { DevSeederDataService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-data.service';+import { DevSeederWorkflowAgentQuestionWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-agent-question.workspace-service';import { TimelineActivitySeederService } from 'src/engine/workspace-manager/dev-seeder/data/services/timeline-activity-seeder.service';import { TimelineActivityModule } from 'src/modules/timeline/timeline-activity.module';import { DevSeederMetadataService } from 'src/engine/workspace-manager/dev-seeder/metadata/services/dev-seeder-metadata.service';-import { DevSeederService } from 'src/engine/workspace-manager/dev-seeder/services/dev-seeder.service';+import { DevSeederWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/services/dev-seeder.workspace-service';import { StandardObjectsPrefillModule } from 'src/engine/workspace-manager/standard-objects-prefill-data/standard-objects-prefill.module';import { TwentyStandardApplicationModule } from 'src/engine/workspace-manager/twenty-standard-application/twenty-standard-application.module';import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';+import { WorkflowAgentConversationModule } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module';+import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';@Module({imports: [@@ -54,7 +59,12 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspaceApplicationRegistrationModule,FeatureFlagModule,FileStorageModule,- TypeOrmModule.forFeature([WorkspaceEntity, ObjectMetadataEntity]),+ TypeOrmModule.forFeature([+ WorkspaceEntity,+ ObjectMetadataEntity,+ WorkflowEntity,+ WorkflowVersionEntity,+ ]),ObjectPermissionModule,WorkspaceManyOrAllFlatEntityMapsCacheModule,StandardObjectsPrefillModule,@@ -64,16 +74,21 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspaceSdkClientModule,SecretEncryptionModule,UpgradeModule,+ WorkflowRunModule,+ WorkflowAgentConversationModule,],- exports: [DevSeederService],+ exports: [DevSeederWorkspaceService],providers: [- DevSeederService,+ DevSeederWorkspaceService,DevSeederMetadataService,DevSeederPermissionsService,DevSeederDataService,TimelineActivitySeederService,+ DevSeederWorkflowAgentQuestionWorkspaceService,provideWorkspaceScopedRepository(RoleEntity),provideWorkspaceScopedRepository(ObjectMetadataEntity),+ provideWorkspaceScopedRepository(WorkflowEntity),+ provideWorkspaceScopedRepository(WorkflowVersionEntity),],})export class DevSeederModule {}diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/services/dev-seeder.service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/services/dev-seeder.workspace-service.tssimilarity index 97%rename from packages/twenty-server/src/engine/workspace-manager/dev-seeder/services/dev-seeder.service.tsrename to packages/twenty-server/src/engine/workspace-manager/dev-seeder/services/dev-seeder.workspace-service.tsindex 7bdf00f4ffd..ba8788b7817 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/services/dev-seeder.service.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/services/dev-seeder.workspace-service.ts@@ -49,6 +49,7 @@ import { seedUserWorkspaces } from 'src/engine/workspace-manager/dev-seeder/coreimport { seedUsers } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';import { createWorkspace } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-workspace.util';import { DevSeederDataService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-data.service';+import { DevSeederWorkflowAgentQuestionWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-agent-question.workspace-service';import { DevSeederMetadataService } from 'src/engine/workspace-manager/dev-seeder/metadata/services/dev-seeder-metadata.service';import { PrefillFrontComponentService } from 'src/engine/workspace-manager/standard-objects-prefill-data/services/prefill-front-component.service';import { PrefillLogicFunctionService } from 'src/engine/workspace-manager/standard-objects-prefill-data/services/prefill-logic-function.service';@@ -59,7 +60,7 @@ import { TwentyStandardApplicationService } from 'src/engine/workspace-manager/timport { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';@Injectable()-export class DevSeederService {+export class DevSeederWorkspaceService {constructor(private readonly agentHistoryStorageService: AgentHistoryWorkspaceStorageService,private readonly workspaceCacheStorageService: WorkspaceCacheStorageService,@@ -69,6 +70,7 @@ export class DevSeederService {private readonly devSeederMetadataService: DevSeederMetadataService,private readonly devSeederPermissionsService: DevSeederPermissionsService,private readonly devSeederDataService: DevSeederDataService,+ private readonly devSeederWorkflowAgentQuestionService: DevSeederWorkflowAgentQuestionWorkspaceService,private readonly applicationService: ApplicationService,private readonly applicationRegistrationService: ApplicationRegistrationService,private readonly workspaceCacheService: WorkspaceCacheService,@@ -234,6 +236,11 @@ export class DevSeederService {},});+ await this.devSeederWorkflowAgentQuestionService.seed({+ workspaceId,+ applicationId: workspaceCustomFlatApplication.id,+ });+await this.workspaceCacheStorageService.flush(workspaceId);}diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snapindex 58dcaf18cf4..ecd11825ee0 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap@@ -11,7 +11,7 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"id": "00000000-0000-0000-0000-000000001018",},"attachments": {- "id": "00000000-0000-0000-0000-000000001037",+ "id": "00000000-0000-0000-0000-000000001036",},"contextWindowTokens": {"id": "00000000-0000-0000-0000-000000001024",@@ -29,16 +29,16 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"id": "00000000-0000-0000-0000-000000001014",},"lastStreamError": {- "id": "00000000-0000-0000-0000-000000001034",+ "id": "00000000-0000-0000-0000-000000001033",},"messages": {- "id": "00000000-0000-0000-0000-000000001036",+ "id": "00000000-0000-0000-0000-000000001035",},"pendingQuestionMessageId": {- "id": "00000000-0000-0000-0000-000000001033",+ "id": "00000000-0000-0000-0000-000000001032",},"recordTargets": {- "id": "00000000-0000-0000-0000-000000001038",+ "id": "00000000-0000-0000-0000-000000001037",},"title": {"id": "00000000-0000-0000-0000-000000001021",@@ -62,7 +62,7 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"id": "00000000-0000-0000-0000-000000001023",},"turns": {- "id": "00000000-0000-0000-0000-000000001035",+ "id": "00000000-0000-0000-0000-000000001034",},"updatedAt": {"id": "00000000-0000-0000-0000-000000001016",@@ -73,239 +73,236 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"workflowRun": {"id": "00000000-0000-0000-0000-000000001031",},- "workflowStepId": {- "id": "00000000-0000-0000-0000-000000001032",- },"workspaceMember": {"id": "00000000-0000-0000-0000-000000001020",},},- "id": "00000000-0000-0000-0000-000000001039",+ "id": "00000000-0000-0000-0000-000000001038","views": undefined,},"agentChatThreadTarget": {"fields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000001041",+ "id": "00000000-0000-0000-0000-000000001040",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001043",+ "id": "00000000-0000-0000-0000-000000001042",},"id": {- "id": "00000000-0000-0000-0000-000000001040",+ "id": "00000000-0000-0000-0000-000000001039",},"targetCompany": {- "id": "00000000-0000-0000-0000-000000001046",+ "id": "00000000-0000-0000-0000-000000001045",},"targetOpportunity": {- "id": "00000000-0000-0000-0000-000000001047",+ "id": "00000000-0000-0000-0000-000000001046",},"targetPerson": {- "id": "00000000-0000-0000-0000-000000001045",+ "id": "00000000-0000-0000-0000-000000001044",},"thread": {- "id": "00000000-0000-0000-0000-000000001044",+ "id": "00000000-0000-0000-0000-000000001043",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001042",+ "id": "00000000-0000-0000-0000-000000001041",},},- "id": "00000000-0000-0000-0000-000000001048",+ "id": "00000000-0000-0000-0000-000000001047","views": {},},"agentMessage": {"fields": {"agentId": {- "id": "00000000-0000-0000-0000-000000001062",+ "id": "00000000-0000-0000-0000-000000001061",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001059",+ "id": "00000000-0000-0000-0000-000000001058",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001061",+ "id": "00000000-0000-0000-0000-000000001060",},"id": {- "id": "00000000-0000-0000-0000-000000001058",+ "id": "00000000-0000-0000-0000-000000001057",},"isHidden": {- "id": "00000000-0000-0000-0000-000000001068",+ "id": "00000000-0000-0000-0000-000000001067",},"parts": {- "id": "00000000-0000-0000-0000-000000001072",+ "id": "00000000-0000-0000-0000-000000001071",},"processedAt": {- "id": "00000000-0000-0000-0000-000000001069",+ "id": "00000000-0000-0000-0000-000000001068",},"role": {- "id": "00000000-0000-0000-0000-000000001066",+ "id": "00000000-0000-0000-0000-000000001065",},"senderApplicationId": {- "id": "00000000-0000-0000-0000-000000001065",+ "id": "00000000-0000-0000-0000-000000001064",},"senderUserWorkspaceId": {- "id": "00000000-0000-0000-0000-000000001064",+ "id": "00000000-0000-0000-0000-000000001063",},"senderWorkspaceMember": {- "id": "00000000-0000-0000-0000-000000001063",+ "id": "00000000-0000-0000-0000-000000001062",},"status": {- "id": "00000000-0000-0000-0000-000000001067",+ "id": "00000000-0000-0000-0000-000000001066",},"thread": {- "id": "00000000-0000-0000-0000-000000001070",+ "id": "00000000-0000-0000-0000-000000001069",},"turn": {- "id": "00000000-0000-0000-0000-000000001071",+ "id": "00000000-0000-0000-0000-000000001070",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001060",+ "id": "00000000-0000-0000-0000-000000001059",},},- "id": "00000000-0000-0000-0000-000000001073",+ "id": "00000000-0000-0000-0000-000000001072","views": undefined,},"agentMessagePart": {"fields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000001075",+ "id": "00000000-0000-0000-0000-000000001074",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001077",+ "id": "00000000-0000-0000-0000-000000001076",},"errorDetails": {- "id": "00000000-0000-0000-0000-000000001089",+ "id": "00000000-0000-0000-0000-000000001088",},"errorMessage": {- "id": "00000000-0000-0000-0000-000000001088",+ "id": "00000000-0000-0000-0000-000000001087",},"fileFilename": {- "id": "00000000-0000-0000-0000-000000001097",+ "id": "00000000-0000-0000-0000-000000001096",},"fileId": {- "id": "00000000-0000-0000-0000-000000001098",+ "id": "00000000-0000-0000-0000-000000001097",},"id": {- "id": "00000000-0000-0000-0000-000000001074",+ "id": "00000000-0000-0000-0000-000000001073",},"message": {- "id": "00000000-0000-0000-0000-000000001100",+ "id": "00000000-0000-0000-0000-000000001099",},"orderIndex": {- "id": "00000000-0000-0000-0000-000000001078",+ "id": "00000000-0000-0000-0000-000000001077",},"providerExecuted": {- "id": "00000000-0000-0000-0000-000000001087",+ "id": "00000000-0000-0000-0000-000000001086",},"providerMetadata": {- "id": "00000000-0000-0000-0000-000000001099",+ "id": "00000000-0000-0000-0000-000000001098",},"reasoningContent": {- "id": "00000000-0000-0000-0000-000000001081",+ "id": "00000000-0000-0000-0000-000000001080",},"sourceDocumentFilename": {- "id": "00000000-0000-0000-0000-000000001096",+ "id": "00000000-0000-0000-0000-000000001095",},"sourceDocumentMediaType": {- "id": "00000000-0000-0000-0000-000000001094",+ "id": "00000000-0000-0000-0000-000000001093",},"sourceDocumentSourceId": {- "id": "00000000-0000-0000-0000-000000001093",+ "id": "00000000-0000-0000-0000-000000001092",},"sourceDocumentTitle": {- "id": "00000000-0000-0000-0000-000000001095",+ "id": "00000000-0000-0000-0000-000000001094",},"sourceUrlSourceId": {- "id": "00000000-0000-0000-0000-000000001090",+ "id": "00000000-0000-0000-0000-000000001089",},"sourceUrlTitle": {- "id": "00000000-0000-0000-0000-000000001092",+ "id": "00000000-0000-0000-0000-000000001091",},"sourceUrlUrl": {- "id": "00000000-0000-0000-0000-000000001091",+ "id": "00000000-0000-0000-0000-000000001090",},"state": {- "id": "00000000-0000-0000-0000-000000001086",+ "id": "00000000-0000-0000-0000-000000001085",},"textContent": {- "id": "00000000-0000-0000-0000-000000001080",+ "id": "00000000-0000-0000-0000-000000001079",},"toolCallId": {- "id": "00000000-0000-0000-0000-000000001083",+ "id": "00000000-0000-0000-0000-000000001082",},"toolInput": {- "id": "00000000-0000-0000-0000-000000001084",+ "id": "00000000-0000-0000-0000-000000001083",},"toolName": {- "id": "00000000-0000-0000-0000-000000001082",+ "id": "00000000-0000-0000-0000-000000001081",},"toolOutput": {- "id": "00000000-0000-0000-0000-000000001085",+ "id": "00000000-0000-0000-0000-000000001084",},"type": {- "id": "00000000-0000-0000-0000-000000001079",+ "id": "00000000-0000-0000-0000-000000001078",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001076",+ "id": "00000000-0000-0000-0000-000000001075",},},- "id": "00000000-0000-0000-0000-000000001101",+ "id": "00000000-0000-0000-0000-000000001100","views": undefined,},"agentTurn": {"fields": {"agentId": {- "id": "00000000-0000-0000-0000-000000001053",+ "id": "00000000-0000-0000-0000-000000001052",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001050",+ "id": "00000000-0000-0000-0000-000000001049",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001052",+ "id": "00000000-0000-0000-0000-000000001051",},"evaluations": {- "id": "00000000-0000-0000-0000-000000001056",+ "id": "00000000-0000-0000-0000-000000001055",},"id": {- "id": "00000000-0000-0000-0000-000000001049",+ "id": "00000000-0000-0000-0000-000000001048",},"messages": {- "id": "00000000-0000-0000-0000-000000001055",+ "id": "00000000-0000-0000-0000-000000001054",},"thread": {- "id": "00000000-0000-0000-0000-000000001054",+ "id": "00000000-0000-0000-0000-000000001053",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001051",+ "id": "00000000-0000-0000-0000-000000001050",},},- "id": "00000000-0000-0000-0000-000000001057",+ "id": "00000000-0000-0000-0000-000000001056","views": undefined,},"agentTurnEvaluation": {"fields": {"comment": {- "id": "00000000-0000-0000-0000-000000001107",+ "id": "00000000-0000-0000-0000-000000001106",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001103",+ "id": "00000000-0000-0000-0000-000000001102",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001105",+ "id": "00000000-0000-0000-0000-000000001104",},"id": {- "id": "00000000-0000-0000-0000-000000001102",+ "id": "00000000-0000-0000-0000-000000001101",},"score": {- "id": "00000000-0000-0000-0000-000000001106",+ "id": "00000000-0000-0000-0000-000000001105",},"turn": {- "id": "00000000-0000-0000-0000-000000001108",+ "id": "00000000-0000-0000-0000-000000001107",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001104",+ "id": "00000000-0000-0000-0000-000000001103",},},- "id": "00000000-0000-0000-0000-000000001109",+ "id": "00000000-0000-0000-0000-000000001108","views": undefined,},"attachment": {@@ -1063,64 +1060,64 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"campaignDelivery": {"fields": {"bouncedAt": {- "id": "00000000-0000-0000-0000-000000001125",+ "id": "00000000-0000-0000-0000-000000001124",},"campaignId": {- "id": "00000000-0000-0000-0000-000000001114",+ "id": "00000000-0000-0000-0000-000000001113",},"claimExpiresAt": {- "id": "00000000-0000-0000-0000-000000001121",+ "id": "00000000-0000-0000-0000-000000001120",},"claimToken": {- "id": "00000000-0000-0000-0000-000000001120",+ "id": "00000000-0000-0000-0000-000000001119",},"complainedAt": {- "id": "00000000-0000-0000-0000-000000001126",+ "id": "00000000-0000-0000-0000-000000001125",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001111",+ "id": "00000000-0000-0000-0000-000000001110",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001113",+ "id": "00000000-0000-0000-0000-000000001112",},"deliveredAt": {- "id": "00000000-0000-0000-0000-000000001124",+ "id": "00000000-0000-0000-0000-000000001123",},"failureReason": {- "id": "00000000-0000-0000-0000-000000001119",+ "id": "00000000-0000-0000-0000-000000001118",},"id": {- "id": "00000000-0000-0000-0000-000000001110",+ "id": "00000000-0000-0000-0000-000000001109",},"personId": {- "id": "00000000-0000-0000-0000-000000001115",+ "id": "00000000-0000-0000-0000-000000001114",},"providerMessageId": {- "id": "00000000-0000-0000-0000-000000001122",+ "id": "00000000-0000-0000-0000-000000001121",},"recipientEmail": {- "id": "00000000-0000-0000-0000-000000001116",+ "id": "00000000-0000-0000-0000-000000001115",},"rejectedAt": {- "id": "00000000-0000-0000-0000-000000001127",+ "id": "00000000-0000-0000-0000-000000001126",},"renderingFailedAt": {- "id": "00000000-0000-0000-0000-000000001128",+ "id": "00000000-0000-0000-0000-000000001127",},"sentAt": {- "id": "00000000-0000-0000-0000-000000001123",+ "id": "00000000-0000-0000-0000-000000001122",},"skipReason": {- "id": "00000000-0000-0000-0000-000000001118",+ "id": "00000000-0000-0000-0000-000000001117",},"state": {- "id": "00000000-0000-0000-0000-000000001117",+ "id": "00000000-0000-0000-0000-000000001116",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001112",+ "id": "00000000-0000-0000-0000-000000001111",},},- "id": "00000000-0000-0000-0000-000000001129",+ "id": "00000000-0000-0000-0000-000000001128","views": undefined,},"company": {@@ -2077,34 +2074,34 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"messageSuppression": {"fields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000001131",+ "id": "00000000-0000-0000-0000-000000001130",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001133",+ "id": "00000000-0000-0000-0000-000000001132",},"emailAddress": {- "id": "00000000-0000-0000-0000-000000001134",+ "id": "00000000-0000-0000-0000-000000001133",},"id": {- "id": "00000000-0000-0000-0000-000000001130",+ "id": "00000000-0000-0000-0000-000000001129",},"providerEventId": {- "id": "00000000-0000-0000-0000-000000001137",+ "id": "00000000-0000-0000-0000-000000001136",},"reason": {- "id": "00000000-0000-0000-0000-000000001135",+ "id": "00000000-0000-0000-0000-000000001134",},"source": {- "id": "00000000-0000-0000-0000-000000001136",+ "id": "00000000-0000-0000-0000-000000001135",},"unsubscribeTopicId": {- "id": "00000000-0000-0000-0000-000000001138",+ "id": "00000000-0000-0000-0000-000000001137",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001132",+ "id": "00000000-0000-0000-0000-000000001131",},},- "id": "00000000-0000-0000-0000-000000001139",+ "id": "00000000-0000-0000-0000-000000001138","views": undefined,},"messageThread": {diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.tsindex ed3cc497a5f..bb69278cb9c 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts@@ -567,31 +567,6 @@ export const buildAgentChatThreadStandardFlatFieldMetadatas = (writability: MetadataWritability.SYSTEM,isAuditLogged: false,},- workflowStepId: {- ...createStandardFieldFlatMetadata({- ...args,- context: {- fieldName: 'workflowStepId',- type: FieldMetadataType.TEXT,- label: i18nLabel(- msg({ message: 'Workflow Step ID', context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message:- 'Agent step of the workflow run that held this conversation',- context: 'fieldMetadata.description',- }),- ),- icon: 'IconId',- isSystem: true,- isUIEditable: false,- isNullable: true,- },- }),- writability: MetadataWritability.SYSTEM,- isAuditLogged: false,- },messages: {...createStandardRelationFieldFlatMetadata({...args,diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-input.type.tsindex 02bcc1f4d80..2f5597c3540 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-input.type.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-input.type.ts@@ -1,3 +1,5 @@+import { type WorkflowRunStepLog } from 'twenty-shared/workflow';+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';export type WorkflowRunInfo = {@@ -10,4 +12,8 @@ export type WorkflowActionInput = {steps: WorkflowAction[];context: Record<string, unknown>;runInfo: WorkflowRunInfo;+ // Set only when the step resumes after its question was answered: the+ // conversation it continues and the log of its execution so far.+ resumedThreadId?: string;+ previousStepLog?: WorkflowRunStepLog;};diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-executor-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-executor-input.type.tsindex 42266276800..4e051a69024 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-executor-input.type.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-executor-input.type.ts@@ -4,6 +4,9 @@ export type WorkflowExecutorInput = {workspaceId: string;shouldComputeWorkflowRunStatus?: boolean;executedStepsCount?: number;+ // Set only when stepIds is the one step resuming after its question was+ // answered, already claimed out of PENDING: the conversation it continues.+ resumedThreadId?: string;};export type WorkflowBranchExecutorInput = {@@ -12,4 +15,5 @@ export type WorkflowBranchExecutorInput = {workflowRunId: string;workspaceId: string;executedStepsCount?: number;+ resumedThreadId?: string;};diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/workflow-should-keep-running.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/workflow-should-keep-running.util.spec.tsindex 6aa42473bad..289c4d139f4 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/workflow-should-keep-running.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/workflow-should-keep-running.util.spec.ts@@ -99,6 +99,32 @@ describe('workflowShouldKeepRunning', () => {expect(workflowShouldKeepRunning({ steps, stepInfos })).toBeTruthy();});++ // The trigger is not a step, so nothing but the answered step's own+ // status can keep its run alive once a parallel branch has finished.+ it('an answered agent step right after the trigger waits for its resume while a parallel branch has finished', () => {+ const steps = [+ { id: 'agent' } as WorkflowAction,+ { id: 'parallel-branch' } as WorkflowAction,+ ];++ const stepInfos = {+ trigger: { status: StepStatus.SUCCESS },+ agent: { status: StepStatus.PENDING, threadId: 'thread' },+ 'parallel-branch': { status: StepStatus.SUCCESS },+ };++ expect(workflowShouldKeepRunning({ steps, stepInfos })).toBe(true);+ expect(+ workflowShouldKeepRunning({+ steps,+ stepInfos: {+ ...stepInfos,+ agent: { status: StepStatus.NOT_STARTED, threadId: 'thread' },+ },+ }),+ ).toBe(false);+ });});describe('should return false', () => {diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.tsindex 05970a3e76e..7132208e0ef 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts@@ -4,14 +4,12 @@ import { TypeOrmModule } from '@nestjs/typeorm';import { ApplicationModule } from 'src/engine/core-modules/application/application.module';import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';-import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';import { RoleModule } from 'src/engine/metadata-modules/role/role.module';import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';-import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';-import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';+import { WorkflowAgentConversationModule } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module';import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';import { AiAgentWorkflowAction } from './ai-agent.workflow-action';@@ -25,12 +23,10 @@ import { AiAgentWorkflowAction } from './ai-agent.workflow-action';UserWorkspaceModule,UserRoleModule,RoleModule,- AgentHistoryModule,- WorkspaceCacheModule,+ WorkflowAgentConversationModule,],providers: [WorkflowExecutionContextService,- WorkflowAgentConversationWorkspaceService,AiAgentWorkflowAction,provideWorkspaceScopedRepository(AgentEntity),],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.tsindex 5e2afd9d7bd..70995a96102 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@@ -1,12 +1,15 @@import { Injectable, Logger } from '@nestjs/common';-import { resolveInput } from 'twenty-shared/utils';+import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';+import { isDefined, resolveInput } from 'twenty-shared/utils';+import { type WorkflowRunStepLog } from 'twenty-shared/workflow';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';import { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';+import { createAskQuestionsTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';import { WORKFLOW_BASE_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/workflow-base-system-prompt.const';import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';@@ -19,7 +22,12 @@ import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-eimport { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';-import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';+import { WORKFLOW_AGENT_ASK_QUESTIONS_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-ask-questions-prompt.constant';+import {+ type RecordedConversation,+ WorkflowAgentConversationWorkspaceService,+} from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';+import { mergeAiAgentStepLogs } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/merge-ai-agent-step-logs.util';import { buildAiAgentStepLog } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util';import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';@@ -43,6 +51,8 @@ export class AiAgentWorkflowAction implements WorkflowAction {steps,context,runInfo,+ resumedThreadId,+ previousStepLog,}: WorkflowActionInput): Promise<WorkflowActionOutput> {const step = findStepOrThrow({stepId: currentStepId,@@ -56,7 +66,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {);}- const { agentId, prompt } = step.settings.input;+ const { agentId, prompt, canAskQuestions } = step.settings.input;const workspaceId = runInfo.workspaceId;let agent: AgentEntity | null = null;@@ -83,25 +93,66 @@ export class AiAgentWorkflowAction implements WorkflowAction {: null;const resolvedPrompt = resolveInput(prompt, context) as string;- const recordConversation = (executionResult?: AgentExecutionResult) =>- this.recordConversation({- workspaceId,- workflowRunId: runInfo.workflowRunId,- stepId: currentStepId,- title: step.name,- agentId: agent?.id ?? null,- prompt: resolvedPrompt,- initiatorUserWorkspaceId: userWorkspaceId,- executionResult,++ // The conversation is a record of the step, not part of its outcome, so a+ // failure to write it must not fail a step whose agent did its work.+ const recordConversation = (+ executionResult?: AgentExecutionResult,+ ): Promise<RecordedConversation | null> =>+ (isDefined(resumedThreadId)+ ? this.workflowAgentConversationService.recordContinuation({+ workspaceId,+ threadId: resumedThreadId,+ agentId: agent?.id ?? null,+ executionResult,+ })+ : this.workflowAgentConversationService.recordExecution({+ workspaceId,+ workflowRunId: runInfo.workflowRunId,+ stepId: currentStepId,+ title: step.name,+ agentId: agent?.id ?? null,+ prompt: resolvedPrompt,+ initiatorUserWorkspaceId: userWorkspaceId,+ executionResult,+ })+ ).catch((error: unknown) => {+ this.logger.warn(+ `Failed to record the conversation for workflowRun=${runInfo.workflowRunId} step=${currentStepId}: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );++ return null;});+ const isAskingQuestionsAllowed = canAskQuestions === true;+const startedAtMs = Date.now();const executionResult = await this.aiAgentExecutionService.executeAgent({agent,- messages: [{ role: 'user', content: resolvedPrompt }],- baseSystemPrompt: WORKFLOW_BASE_SYSTEM_PROMPT,+ ...(isDefined(resumedThreadId)+ ? {+ messages: [],+ priorModelMessages:+ await this.workflowAgentConversationService.loadModelMessages({+ workspaceId,+ threadId: resumedThreadId,+ }),+ }+ : { messages: [{ role: 'user', content: resolvedPrompt }] }),+ baseSystemPrompt: isAskingQuestionsAllowed+ ? `${WORKFLOW_BASE_SYSTEM_PROMPT}\n\n${WORKFLOW_AGENT_ASK_QUESTIONS_PROMPT}`+ : WORKFLOW_BASE_SYSTEM_PROMPT,+ pausingTools: isAskingQuestionsAllowed+ ? {+ [ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool({+ isWorkspaceSetupThread: false,+ }),+ }+ : {},actorContext: executionContext.isActingOnBehalfOfUser? executionContext.initiator: undefined,@@ -111,13 +162,21 @@ export class AiAgentWorkflowAction implements WorkflowAction {operationType: UsageOperationType.AI_WORKFLOW_TOKEN,}).catch(async (error: unknown) => {- await recordConversation();+ if (isDefined(resumedThreadId)) {+ await recordConversation();+ }throw error;});const durationMs = Date.now() - startedAtMs;- await recordConversation(executionResult);+ // A conversation only exists to be answered in: an execution that never+ // asks keeps its step log as its record, which saves a thread per+ // execution for agents running in loops or on busy triggers.+ const recordedConversation =+ isDefined(resumedThreadId) || executionResult.isPaused === true+ ? await recordConversation(executionResult)+ : null;await this.persistStepLog({workflowRunId: runInfo.workflowRunId,@@ -125,6 +184,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {stepId: currentStepId,executionResult,durationMs,+ previousStepLog,});if (executionResult.hasNoMoreAvailableCredits) {@@ -133,41 +193,37 @@ export class AiAgentWorkflowAction implements WorkflowAction {};}+ if (executionResult.isPaused === true) {+ // The conversation is where the question is answered, so without it the+ // run would wait for an answer nobody can give.+ if (recordedConversation?.isAwaitingAnswer !== true) {+ return {+ error: 'Agent asked a question that could not be recorded.',+ };+ }++ return { pendingEvent: true };+ }+return {result: executionResult.result,};}- // The conversation is a record of the step, not part of its outcome, so a- // failure to write it must not fail a step whose agent did its work.- private async recordConversation(- args: Parameters<- WorkflowAgentConversationWorkspaceService['recordExecution']- >[0],- ): Promise<void> {- try {- await this.workflowAgentConversationService.recordExecution(args);- } catch (error) {- this.logger.warn(- `Failed to record the conversation for workflowRun=${args.workflowRunId} step=${args.stepId}: ${- error instanceof Error ? error.message : String(error)- }`,- );- }- }-private async persistStepLog({workflowRunId,workspaceId,stepId,executionResult,durationMs,+ previousStepLog,}: {workflowRunId: string;workspaceId: string;stepId: string;executionResult: AgentExecutionResult;durationMs: number;+ previousStepLog?: WorkflowRunStepLog;}): Promise<void> {const stepLog = buildAiAgentStepLog({ executionResult, durationMs });@@ -180,7 +236,10 @@ export class AiAgentWorkflowAction implements WorkflowAction {workflowRunId,workspaceId,stepId,- stepLog,+ stepLog: mergeAiAgentStepLogs({+ previousStepLog,+ nextStepLog: stepLog,+ }),});} catch (error) {this.logger.warn(diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-ask-questions-prompt.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-ask-questions-prompt.constant.tsnew file mode 100644index 00000000000..b96bf6e4d94--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-ask-questions-prompt.constant.ts@@ -0,0 +1 @@+export const WORKFLOW_AGENT_ASK_QUESTIONS_PROMPT = `You run inside a workflow, with nobody watching as you work. When you need a decision or a fact that only a person can give, such as an approval or a choice with no safe default, call ask_questions: the workflow pauses until someone answers, then you continue with their answer. Ask everything you need in one call, and do not ask about anything you can find or decide yourself.`;diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.tsindex 7a46207cb2f..0fe0217d8e6 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts@@ -2,39 +2,55 @@ import { Injectable } from '@nestjs/common';import { randomUUID } from 'node:crypto';-import { type ExtendedUIMessagePart } from 'twenty-shared/ai';+import { convertToModelMessages, type ModelMessage } from 'ai';+import {+ type ExtendedUIMessage,+ type ExtendedUIMessagePart,+} from 'twenty-shared/ai';import { isDefined } from 'twenty-shared/utils';import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';import { type AgentMessagePartEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message-part.entity';-import {- type AgentMessageEntity,- AgentMessageRole,-} from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';import { type AgentTurnEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-turn.entity';+import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';+import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';+import { finalizeDanglingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/finalize-dangling-tool-parts.util';import { mapAiStepsToUiMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util';-import { mapUIMessagePartsToDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts';-import { type AgentChatThreadEntity } from 'src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity';+import { mapDBPartsToUIMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapDBPartsToUIMessageParts';+import { mapUIMessagePartsToPersistedDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util';+import { findPendingQuestionPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-pending-question-part.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 { hasWorkflowRunThreadFields } from 'src/engine/metadata-modules/ai/ai-history/utils/has-workflow-run-thread-fields.util';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';-// Each execution of an agent step gets its own conversation, so a loop-// iteration or a retry never reads or continues another one's messages. The-// conversation has no owner: it belongs to the run and is readable by whoever-// can read the run.+type RecordedExecutionResult = {+ steps?: Pick<NonNullable<AgentExecutionResult['steps']>[number], 'content'>[];+ isPaused?: boolean;+};++export type RecordedConversation = {+ threadId: string;+ isAwaitingAnswer: boolean;+};++// A conversation is recorded only for an execution of an agent step that asks+// a question, and continued when that execution resumes. Each gets its own, so+// a loop iteration or a retry never reads or continues another one's messages.+// The conversation has no owner: it belongs to the run and is readable by+// whoever can read the run.@Injectable()export class WorkflowAgentConversationWorkspaceService {constructor(@InjectAgentHistoryRepository('agentChatThread')- private readonly threadRepository: AgentHistoryRepository<AgentChatThreadEntity>,+ private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,@InjectAgentHistoryRepository('agentTurn')private readonly turnRepository: AgentHistoryRepository<AgentTurnEntity>,@InjectAgentHistoryRepository('agentMessage')- private readonly messageRepository: AgentHistoryRepository<AgentMessageEntity>,+ private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,@InjectAgentHistoryRepository('agentMessagePart')private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartEntity>,private readonly workspaceCacheService: WorkspaceCacheService,@@ -58,10 +74,8 @@ export class WorkflowAgentConversationWorkspaceService {agentId: string | null;prompt: string;initiatorUserWorkspaceId: string | null;- // Absent when the agent failed before replying; the prompt is still- // recorded so the run shows what the agent was asked.- executionResult?: Pick<AgentExecutionResult, 'steps'>;- }): Promise<string | null> {+ executionResult?: RecordedExecutionResult;+ }): Promise<RecordedConversation | null> {const { flatFieldMetadataMaps } =await this.workspaceCacheService.getOrRecompute(workspaceId, ['flatFieldMetadataMaps',@@ -71,21 +85,13 @@ export class WorkflowAgentConversationWorkspaceService {return null;}- const threadId = randomUUID();-- await this.threadRepository.query(workspaceId, ({ manager, table }) =>- manager.query(- `INSERT INTO ${table('agentChatThread')} (id, title, "workflowRunId", "workflowStepId")- VALUES ($1, $2, $3, $4)`,- [threadId, title, workflowRunId, stepId],- ),- );-- const turnInsertResult = await this.turnRepository.insert(workspaceId, {- threadId,- agentId,+ const threadInsertResult = await this.threadRepository.insert(workspaceId, {+ title,+ workflowRunId,});- const turnId = turnInsertResult.identifiers[0].id as string;+ const threadId = threadInsertResult.identifiers[0].id as string;++ const turnId = await this.insertTurn({ workspaceId, threadId, agentId });await this.insertMessage({workspaceId,@@ -97,28 +103,142 @@ export class WorkflowAgentConversationWorkspaceService {parts: [{ type: 'text', text: prompt }],});+ // Linked to its step before its question is offered: an answer is matched+ // to the step through this link, and one arriving before it would find+ // no step waiting and close the question the step is about to wait on.+ await this.workflowRunWorkspaceService.setStepThreadId({+ stepId,+ threadId,+ workflowRunId,+ workspaceId,+ });++ const isAwaitingAnswer = await this.recordReply({+ workspaceId,+ threadId,+ turnId,+ agentId,+ executionResult,+ });++ return { threadId, isAwaitingAnswer };+ }++ // Continues a conversation whose question has been answered: the answer is+ // already recorded as the last message, so only the agent's reply is added.+ async recordContinuation({+ workspaceId,+ threadId,+ agentId,+ executionResult,+ }: {+ workspaceId: string;+ threadId: string;+ agentId: string | null;+ executionResult?: RecordedExecutionResult;+ }): Promise<RecordedConversation> {+ const turnId = await this.insertTurn({ workspaceId, threadId, agentId });++ const isAwaitingAnswer = await this.recordReply({+ workspaceId,+ threadId,+ turnId,+ agentId,+ executionResult,+ });++ return { threadId, isAwaitingAnswer };+ }++ async loadModelMessages({+ workspaceId,+ threadId,+ }: {+ workspaceId: string;+ threadId: string;+ }): Promise<ModelMessage[]> {+ const messages = await this.messageRepository.find(workspaceId, {+ where: { threadId },+ order: {+ processedAt: { order: 'ASC', nulls: 'NULLS LAST' },+ createdAt: 'ASC',+ },+ relations: ['parts'],+ });++ const uiMessages: ExtendedUIMessage[] = messages.map((message) => ({+ id: message.id,+ role: message.role as ExtendedUIMessage['role'],+ parts: finalizeDanglingToolParts(+ mapDBPartsToUIMessageParts(message.parts ?? []),+ ),+ }));++ return convertToModelMessages(uiMessages);+ }++ private async recordReply({+ workspaceId,+ threadId,+ turnId,+ agentId,+ executionResult,+ }: {+ workspaceId: string;+ threadId: string;+ turnId: string;+ agentId: string | null;+ executionResult?: RecordedExecutionResult;+ }): Promise<boolean> {const replyParts = mapAiStepsToUiMessageParts(executionResult?.steps ?? []);- if (replyParts.length > 0) {- await this.insertMessage({- workspaceId,- threadId,- turnId,- role: AgentMessageRole.ASSISTANT,- agentId,- senderUserWorkspaceId: null,- parts: replyParts,- });+ if (replyParts.length === 0) {+ return false;}- await this.workflowRunWorkspaceService.setStepThreadId({- stepId,+ const messageId = await this.insertMessage({+ workspaceId,threadId,- workflowRunId,+ turnId,+ role: AgentMessageRole.ASSISTANT,+ agentId,+ senderUserWorkspaceId: null,+ parts: replyParts,+ });++ if (+ executionResult?.isPaused !== true ||+ !isDefined(findPendingQuestionPart(replyParts))+ ) {+ return false;+ }++ // The same marker a chat question sets, so the answer flow can claim the+ // question exactly once.+ await this.threadRepository.update(workspaceId,+ { id: threadId },+ { pendingQuestionMessageId: messageId },+ );++ return true;+ }++ private async insertTurn({+ workspaceId,+ threadId,+ agentId,+ }: {+ workspaceId: string;+ threadId: string;+ agentId: string | null;+ }): Promise<string> {+ const turnInsertResult = await this.turnRepository.insert(workspaceId, {+ threadId,+ agentId,});- return threadId;+ return turnInsertResult.identifiers[0].id as string;}private async insertMessage({@@ -137,7 +257,7 @@ export class WorkflowAgentConversationWorkspaceService {agentId: string | null;senderUserWorkspaceId: string | null;parts: ExtendedUIMessagePart[];- }): Promise<void> {+ }): Promise<string> {const messageId = randomUUID();await this.messageRepository.insert(workspaceId, {@@ -146,11 +266,15 @@ export class WorkflowAgentConversationWorkspaceService {turnId,role,agentId,- processedAt: new Date(),+ processedAt: new Date().toISOString(),...(isDefined(senderUserWorkspaceId) ? { senderUserWorkspaceId } : {}),});- const dbParts = mapUIMessagePartsToDBParts(parts, messageId, workspaceId);+ const dbParts = mapUIMessagePartsToPersistedDBParts(+ parts,+ messageId,+ workspaceId,+ );if (dbParts.length > 0) {await this.messagePartRepository.insert(@@ -158,5 +282,7 @@ export class WorkflowAgentConversationWorkspaceService {dbParts as QueryDeepPartialEntity<AgentMessagePartEntity>[],);}++ return messageId;}}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.tsindex e1157638e32..edc6e25907b 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts@@ -1,4 +1,5 @@export type WorkflowAiAgentActionInput = {agentId?: string;prompt?: string;+ canAskQuestions?: boolean;};diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/merge-ai-agent-step-logs.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/merge-ai-agent-step-logs.util.spec.tsnew file mode 100644index 00000000000..6a48d5475bc--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/merge-ai-agent-step-logs.util.spec.ts@@ -0,0 +1,84 @@+import { type WorkflowRunStepLog } from 'twenty-shared/workflow';++import { mergeAiAgentStepLogs } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/merge-ai-agent-step-logs.util';++const buildAgentStepLog = ({+ modelId,+ tokens,+ toolCallNames,+ durationMs,+}: {+ modelId: string;+ tokens: number;+ toolCallNames: string[];+ durationMs: number;+}): WorkflowRunStepLog => ({+ details: {+ type: 'AI_AGENT',+ modelId,+ usage: {+ inputTokens: tokens,+ outputTokens: tokens,+ reasoningTokens: tokens,+ totalTokens: tokens * 2,+ },+ cost: { totalCostInDollars: tokens / 100, creditsUsedMicro: tokens },+ nativeWebSearchCallCount: 1,+ toolCalls: toolCallNames.map((toolName) => ({+ toolName,+ toolCallId: `${toolName}-call`,+ state: 'success',+ })),+ durationMs,+ },+ entries: [],+ sizeBytes: 0,+});++describe('mergeAiAgentStepLogs', () => {+ it('adds the segment after an answer to the one before it', () => {+ const merged = mergeAiAgentStepLogs({+ previousStepLog: buildAgentStepLog({+ modelId: 'model-a',+ tokens: 10,+ toolCallNames: ['search', 'ask_questions'],+ durationMs: 100,+ }),+ nextStepLog: buildAgentStepLog({+ modelId: 'model-b',+ tokens: 5,+ toolCallNames: ['send_email'],+ durationMs: 50,+ }),+ });++ expect(merged.details).toMatchObject({+ modelId: 'model-b',+ usage: {+ inputTokens: 15,+ outputTokens: 15,+ reasoningTokens: 15,+ totalTokens: 30,+ },+ cost: { totalCostInDollars: expect.closeTo(0.15), creditsUsedMicro: 15 },+ nativeWebSearchCallCount: 2,+ durationMs: 150,+ });+ expect(+ merged.details.type === 'AI_AGENT'+ ? merged.details.toolCalls.map(({ toolName }) => toolName)+ : [],+ ).toEqual(['search', 'ask_questions', 'send_email']);+ });++ it('keeps the new log when there is nothing before it', () => {+ const nextStepLog = buildAgentStepLog({+ modelId: 'model-a',+ tokens: 5,+ toolCallNames: [],+ durationMs: 50,+ });++ expect(mergeAiAgentStepLogs({ nextStepLog })).toBe(nextStepLog);+ });+});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/merge-ai-agent-step-logs.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/merge-ai-agent-step-logs.util.tsnew file mode 100644index 00000000000..5471b74b025--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/merge-ai-agent-step-logs.util.ts@@ -0,0 +1,67 @@+import { isDefined } from 'twenty-shared/utils';+import { type WorkflowRunStepLog } from 'twenty-shared/workflow';++// An agent that asked a question runs again once it is answered, and the+// step's log has to account for every segment rather than the last one only.+export const mergeAiAgentStepLogs = ({+ previousStepLog,+ nextStepLog,+}: {+ previousStepLog?: WorkflowRunStepLog;+ nextStepLog: WorkflowRunStepLog;+}): WorkflowRunStepLog => {+ const previousDetails = previousStepLog?.details;+ const nextDetails = nextStepLog.details;++ if (previousDetails?.type !== 'AI_AGENT' || nextDetails.type !== 'AI_AGENT') {+ return nextStepLog;+ }++ const sumOptional = (+ previousValue: number | undefined,+ nextValue: number | undefined,+ ) =>+ !isDefined(previousValue) && !isDefined(nextValue)+ ? undefined+ : (previousValue ?? 0) + (nextValue ?? 0);++ return {+ ...nextStepLog,+ details: {+ ...nextDetails,+ usage: {+ inputTokens:+ previousDetails.usage.inputTokens + nextDetails.usage.inputTokens,+ outputTokens:+ previousDetails.usage.outputTokens + nextDetails.usage.outputTokens,+ reasoningTokens: sumOptional(+ previousDetails.usage.reasoningTokens,+ nextDetails.usage.reasoningTokens,+ ),+ cacheReadTokens: sumOptional(+ previousDetails.usage.cacheReadTokens,+ nextDetails.usage.cacheReadTokens,+ ),+ cacheCreationTokens: sumOptional(+ previousDetails.usage.cacheCreationTokens,+ nextDetails.usage.cacheCreationTokens,+ ),+ totalTokens:+ previousDetails.usage.totalTokens + nextDetails.usage.totalTokens,+ },+ cost: {+ totalCostInDollars:+ previousDetails.cost.totalCostInDollars ++ nextDetails.cost.totalCostInDollars,+ creditsUsedMicro:+ previousDetails.cost.creditsUsedMicro ++ nextDetails.cost.creditsUsedMicro,+ },+ nativeWebSearchCallCount:+ previousDetails.nativeWebSearchCallCount ++ nextDetails.nativeWebSearchCallCount,+ toolCalls: [...previousDetails.toolCalls, ...nextDetails.toolCalls],+ durationMs: previousDetails.durationMs + nextDetails.durationMs,+ },+ };+};diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.tsnew file mode 100644index 00000000000..1f69b334fe7--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts@@ -0,0 +1,13 @@+import { Module } from '@nestjs/common';++import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';+import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';+import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';++@Module({+ imports: [AgentHistoryModule, WorkspaceCacheModule, WorkflowRunModule],+ providers: [WorkflowAgentConversationWorkspaceService],+ exports: [WorkflowAgentConversationWorkspaceService],+})+export class WorkflowAgentConversationModule {}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/__tests__/workflow-executor.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/__tests__/workflow-executor.workspace-service.spec.tsnew file mode 100644index 00000000000..30f0bf29f43--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/__tests__/workflow-executor.workspace-service.spec.ts@@ -0,0 +1,169 @@+import {+ StepStatus,+ type WorkflowRunStepInfos,+ type WorkflowRunStepLog,+} from 'twenty-shared/workflow';++import { type WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';+import { type BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';+import { type ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';+import { type FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';+import { type MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';+import { type MetricsService } from 'src/engine/core-modules/metrics/metrics.service';+import { type UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';+import { type UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';+import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';+import { type WorkflowActionFactory } from 'src/modules/workflow/workflow-executor/factories/workflow-action.factory';+import { WorkflowExecutorWorkspaceService } from 'src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service';+import { type WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';++const WORKSPACE_ID = 'workspace-id';+const WORKFLOW_RUN_ID = 'workflow-run-id';+const AGENT_STEP_ID = 'agent-step-id';++describe('WorkflowExecutorWorkspaceService', () => {+ const workflowRunWorkspaceService = {+ getWorkflowRunOrFail: jest.fn(),+ updateWorkflowRunStepInfo: jest.fn(),+ endWorkflowRun: jest.fn(),+ };++ const workflowAction = { execute: jest.fn() };++ const billingUsageService = { assertUsageAllowed: jest.fn() };+ const usageLimitQuotaService = { consumeQuota: jest.fn() };+ const usageRecorderService = { record: jest.fn() };++ const service = new WorkflowExecutorWorkspaceService(+ {+ findCoreWorkflowById: jest.fn().mockResolvedValue({+ id: 'workflow-id',+ workspaceWorkflowId: 'workflow-id',+ applicationId: 'application-id',+ }),+ } as unknown as WorkflowCoreSyncService,+ {+ get: jest.fn().mockReturnValue(workflowAction),+ } as unknown as WorkflowActionFactory,+ usageRecorderService as unknown as UsageRecorderService,+ workflowRunWorkspaceService as unknown as WorkflowRunWorkspaceService,+ billingUsageService as unknown as BillingUsageService,+ usageLimitQuotaService as unknown as UsageLimitQuotaService,+ {+ isFeatureEnabled: jest.fn().mockResolvedValue(true),+ } as unknown as FeatureFlagService,+ {} as ExceptionHandlerService,+ {} as MetricsService,+ {} as MessageQueueService,+ );++ const previousStepLog = {+ status: 'SUCCESS',+ details: { type: 'AI_AGENT' },+ } as unknown as WorkflowRunStepLog;++ const mockWorkflowRun = (stepInfos: WorkflowRunStepInfos) =>+ workflowRunWorkspaceService.getWorkflowRunOrFail.mockResolvedValue({+ id: WORKFLOW_RUN_ID,+ status: WorkflowRunStatus.RUNNING,+ coreWorkflowId: 'workflow-id',+ stepLogs: { [AGENT_STEP_ID]: previousStepLog },+ state: {+ flow: {+ steps: [+ {+ id: AGENT_STEP_ID,+ type: 'AI_AGENT',+ nextStepIds: [],+ settings: {},+ },+ ],+ },+ stepInfos: {+ trigger: { status: StepStatus.SUCCESS, result: {} },+ ...stepInfos,+ },+ },+ });++ beforeEach(() => {+ jest.clearAllMocks();+ workflowAction.execute.mockResolvedValue({ result: { response: 'done' } });+ });++ describe('executeFromSteps', () => {+ it('runs a resumed step without charging it or checking the quota again', async () => {+ mockWorkflowRun({+ [AGENT_STEP_ID]: { status: StepStatus.RUNNING, threadId: 'thread' },+ });++ await service.executeFromSteps({+ stepIds: [AGENT_STEP_ID],+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ resumedThreadId: 'thread',+ });++ expect(workflowAction.execute).toHaveBeenCalledTimes(1);+ expect(workflowAction.execute).toHaveBeenCalledWith(+ expect.objectContaining({+ currentStepId: AGENT_STEP_ID,+ resumedThreadId: 'thread',+ previousStepLog,+ }),+ );+ expect(+ workflowRunWorkspaceService.updateWorkflowRunStepInfo,+ ).toHaveBeenLastCalledWith({+ stepId: AGENT_STEP_ID,+ stepInfo: { status: StepStatus.SUCCESS, result: { response: 'done' } },+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ });+ expect(billingUsageService.assertUsageAllowed).not.toHaveBeenCalled();+ expect(usageLimitQuotaService.consumeQuota).not.toHaveBeenCalled();+ expect(usageRecorderService.record).not.toHaveBeenCalled();+ });++ it('charges a step it runs, whatever conversation it holds', async () => {+ mockWorkflowRun({+ [AGENT_STEP_ID]: { status: StepStatus.NOT_STARTED, threadId: 'thread' },+ });++ await service.executeFromSteps({+ stepIds: [AGENT_STEP_ID],+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ });++ expect(workflowAction.execute).toHaveBeenCalledTimes(1);+ expect(workflowAction.execute).toHaveBeenCalledWith(+ expect.objectContaining({+ resumedThreadId: undefined,+ previousStepLog: undefined,+ }),+ );+ expect(billingUsageService.assertUsageAllowed).toHaveBeenCalledTimes(1);+ expect(usageLimitQuotaService.consumeQuota).toHaveBeenCalledTimes(1);+ expect(usageRecorderService.record).toHaveBeenCalledTimes(1);+ });++ it('leaves a step waiting for its answer to the resume', async () => {+ mockWorkflowRun({+ [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: 'thread' },+ });++ await service.executeFromSteps({+ stepIds: [AGENT_STEP_ID],+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ });++ expect(workflowAction.execute).not.toHaveBeenCalled();+ expect(+ workflowRunWorkspaceService.updateWorkflowRunStepInfo,+ ).not.toHaveBeenCalled();+ expect(workflowRunWorkspaceService.endWorkflowRun).not.toHaveBeenCalled();+ });+ });+});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.tsindex f67b0fe3e2f..681594c8ea9 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts@@ -8,6 +8,7 @@ import {StepStatus,WorkflowRunStepInfo,WorkflowRunStepInfos,+ type WorkflowRunStepLog,} from 'twenty-shared/workflow';import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';@@ -82,6 +83,7 @@ export class WorkflowExecutorWorkspaceService {workspaceId,shouldComputeWorkflowRunStatus = true,executedStepsCount = 0,+ resumedThreadId,}: WorkflowExecutorInput) {await Promise.all(stepIds.map(async (stepIdToExecute) => {@@ -90,6 +92,7 @@ export class WorkflowExecutorWorkspaceService {workflowRunId,workspaceId,executedStepsCount,+ resumedThreadId,});}),);@@ -107,6 +110,7 @@ export class WorkflowExecutorWorkspaceService {workflowRunId,workspaceId,executedStepsCount,+ resumedThreadId,}: WorkflowBranchExecutorInput): Promise<void> {const workflowRun =await this.workflowRunWorkspaceService.getWorkflowRunOrFail({@@ -152,7 +156,9 @@ export class WorkflowExecutorWorkspaceService {let actionOutput: WorkflowActionOutput;+ // A resumed step was claimed as started, which shouldExecuteStep refuses.if (+ isDefined(resumedThreadId) ||shouldExecuteStep({step: stepToExecute,steps,@@ -167,6 +173,10 @@ export class WorkflowExecutorWorkspaceService {workflowRunId,workspaceId,billingSpenders,+ resumedThreadId,+ previousStepLog: isDefined(resumedThreadId)+ ? workflowRun.stepLogs?.[stepId]+ : undefined,});if (isDefined(actionOutput.error) && !actionOutput.isUserError) {@@ -228,10 +238,12 @@ export class WorkflowExecutorWorkspaceService {const isError =isDefined(actionOutput.error) && !actionOutput.shouldFailSafely;+ // A resumed step's node run was charged when it first ran and paused.if (!isError &&!actionOutput.shouldFailSafely &&- !actionOutput.shouldSkipStepExecution+ !actionOutput.shouldSkipStepExecution &&+ !isDefined(resumedThreadId)) {await this.sendWorkflowNodeRunEvent(workspaceId, billingSpenders);}@@ -507,6 +519,8 @@ export class WorkflowExecutorWorkspaceService {workflowRunId,workspaceId,billingSpenders,+ resumedThreadId,+ previousStepLog,}: {step: WorkflowAction;steps: WorkflowAction[];@@ -514,6 +528,8 @@ export class WorkflowExecutorWorkspaceService {workflowRunId: string;workspaceId: string;billingSpenders: WorkflowBillingSpenders;+ resumedThreadId?: string;+ previousStepLog?: WorkflowRunStepLog;}) {const stepId = step.id;@@ -530,10 +546,10 @@ export class WorkflowExecutorWorkspaceService {});try {- const nodeRunRefusal = await this.getNodeRunRefusal({- workspaceId,- billingSpenders,- });+ // A resumed step's quota was checked when it first ran and paused.+ const nodeRunRefusal = isDefined(resumedThreadId)+ ? undefined+ : await this.getNodeRunRefusal({ workspaceId, billingSpenders });if (isDefined(nodeRunRefusal)) {return nodeRunRefusal;@@ -547,6 +563,8 @@ export class WorkflowExecutorWorkspaceService {workflowRunId,workspaceId,},+ resumedThreadId,+ previousStepLog,});} catch (error) {const isUserError = isUserFacingWorkflowExecutorError(error);diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/__tests__/run-workflow.job.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/__tests__/run-workflow.job.spec.tsnew file mode 100644index 00000000000..b5a337520cf--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/__tests__/run-workflow.job.spec.ts@@ -0,0 +1,93 @@+import { StepStatus } from 'twenty-shared/workflow';++import { type MetricsService } from 'src/engine/core-modules/metrics/metrics.service';+import { type WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';+import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';+import { type CodeStepBuildService } from 'src/modules/workflow/workflow-builder/workflow-version-step/code-step/services/code-step-build.service';+import { type WorkflowExecutorWorkspaceService } from 'src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service';+import { RunWorkflowJob } from 'src/modules/workflow/workflow-runner/jobs/run-workflow.job';+import { type WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';++const WORKSPACE_ID = 'workspace-id';+const WORKFLOW_RUN_ID = 'workflow-run-id';+const AGENT_STEP_ID = 'agent-step-id';+const THREAD_ID = 'thread-id';++describe('RunWorkflowJob', () => {+ const workflowRunWorkspaceService = {+ updateStepInfoIfPending: jest.fn(),+ updateWorkflowRunStepInfos: jest.fn(),+ endWorkflowRun: jest.fn(),+ };++ const workflowExecutorWorkspaceService = {+ executeFromSteps: jest.fn(),+ };++ const workspaceOrmManager = {+ executeInWorkspaceContext: jest.fn((callback: () => Promise<void>) =>+ callback(),+ ),+ };++ const job = new RunWorkflowJob(+ {} as WorkflowVersionCoreSyncService,+ {} as CodeStepBuildService,+ workflowExecutorWorkspaceService as unknown as WorkflowExecutorWorkspaceService,+ workflowRunWorkspaceService as unknown as WorkflowRunWorkspaceService,+ {} as MetricsService,+ workspaceOrmManager as unknown as WorkspaceOrmManager,+ );++ const resume = () =>+ job.handle({+ workspaceId: WORKSPACE_ID,+ workflowRunId: WORKFLOW_RUN_ID,+ stepToResume: { stepId: AGENT_STEP_ID, threadId: THREAD_ID },+ });++ beforeEach(() => {+ jest.clearAllMocks();+ workflowRunWorkspaceService.updateStepInfoIfPending.mockResolvedValue(true);+ });++ describe('resuming an answered step', () => {+ it('claims the step out of PENDING in its conversation and resumes it', async () => {+ await resume();++ expect(+ workflowRunWorkspaceService.updateStepInfoIfPending,+ ).toHaveBeenCalledWith({+ stepId: AGENT_STEP_ID,+ stepInfo: { status: StepStatus.RUNNING },+ expectedThreadId: THREAD_ID,+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ });+ expect(+ workflowExecutorWorkspaceService.executeFromSteps,+ ).toHaveBeenCalledWith({+ stepIds: [AGENT_STEP_ID],+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ resumedThreadId: THREAD_ID,+ });+ expect(+ workflowRunWorkspaceService.updateWorkflowRunStepInfos,+ ).not.toHaveBeenCalled();+ });++ it('does nothing when the step can no longer be claimed', async () => {+ workflowRunWorkspaceService.updateStepInfoIfPending.mockResolvedValue(+ false,+ );++ await resume();++ expect(+ workflowExecutorWorkspaceService.executeFromSteps,+ ).not.toHaveBeenCalled();+ expect(workflowRunWorkspaceService.endWorkflowRun).not.toHaveBeenCalled();+ });+ });+});diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.tsindex ab346f1b393..64a7514f255 100644--- a/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.ts@@ -43,6 +43,7 @@ export class RunWorkflowJob {workflowRunId,lastExecutedStepId,stepIdsToRetry,+ stepToResume,workspaceId,}: RunWorkflowJobData): Promise<void> {this.logger.log(@@ -52,7 +53,13 @@ export class RunWorkflowJob {await this.workspaceOrmManager.executeInWorkspaceContext(async () => {try {- if (isDefined(stepIdsToRetry)) {+ if (isDefined(stepToResume)) {+ await this.resumeAnsweredStep({+ workspaceId,+ workflowRunId,+ stepToResume,+ });+ } else if (isDefined(stepIdsToRetry)) {await this.retryWorkflowExecution({workspaceId,workflowRunId,@@ -215,6 +222,39 @@ export class RunWorkflowJob {});}+ // An answered step stays PENDING until here, which keeps its run from+ // completing while the resume waits in the queue. Claiming it out of PENDING+ // is what makes a second resume of the same step do nothing.+ private async resumeAnsweredStep({+ workflowRunId,+ stepToResume: { stepId, threadId },+ workspaceId,+ }: {+ workflowRunId: string;+ stepToResume: { stepId: string; threadId: string };+ workspaceId: string;+ }): Promise<void> {+ const isClaimed =+ await this.workflowRunWorkspaceService.updateStepInfoIfPending({+ stepId,+ stepInfo: { status: StepStatus.RUNNING },+ expectedThreadId: threadId,+ workflowRunId,+ workspaceId,+ });++ if (!isClaimed) {+ return;+ }++ await this.workflowExecutorWorkspaceService.executeFromSteps({+ stepIds: [stepId],+ workflowRunId,+ workspaceId,+ resumedThreadId: threadId,+ });+ }+private async resumeWorkflowExecution({workflowRunId,lastExecutedStepId,diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/types/run-workflow-job-data.type.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/types/run-workflow-job-data.type.tsindex 00df174bb36..b945a6ac352 100644--- a/packages/twenty-server/src/modules/workflow/workflow-runner/types/run-workflow-job-data.type.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/types/run-workflow-job-data.type.ts@@ -3,4 +3,5 @@ export type RunWorkflowJobData = {workflowRunId: string;lastExecutedStepId?: string;stepIdsToRetry?: string[];+ stepToResume?: { stepId: string; threadId: string };};diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.spec.tsnew file mode 100644index 00000000000..dd0d3e9c9dd--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.spec.ts@@ -0,0 +1,264 @@+import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';+import { StepStatus, type WorkflowRunStepInfos } from 'twenty-shared/workflow';++import { type AgentMessagePartEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message-part.entity';+import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';+import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';+import { type MetricsService } from 'src/engine/core-modules/metrics/metrics.service';+import { type RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';+import { type WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';+import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';+import {+ WorkflowRunStatus,+ type WorkflowRunWorkspaceEntity,+} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';+import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';++const WORKSPACE_ID = 'workspace-id';+const WORKFLOW_RUN_ID = 'workflow-run-id';+const AGENT_STEP_ID = 'agent-step-id';+const THREAD_ID = 'thread-id';++describe('WorkflowRunWorkspaceService', () => {+ const threadRepository = { find: jest.fn(), update: jest.fn() };+ const messagePartRepository = { find: jest.fn(), update: jest.fn() };++ const service = Object.assign(+ new WorkflowRunWorkspaceService(+ {} as WorkspaceOrmManager,+ {} as RecordPositionService,+ {+ incrementCounterForEvent: jest.fn(),+ } as unknown as MetricsService,+ {} as WorkflowRunRecordShareService,+ threadRepository as unknown as AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,+ messagePartRepository as unknown as AgentHistoryRepository<AgentMessagePartEntity>,+ ),+ {+ cacheLockService: {+ withLock: (callback: () => Promise<unknown>) => callback(),+ },+ },+ );++ const getWorkflowRunOrFail = jest.spyOn(service, 'getWorkflowRunOrFail');+ const updateWorkflowRun = jest.spyOn(service, 'updateWorkflowRun');++ const mockWorkflowRun = ({+ status = WorkflowRunStatus.RUNNING,+ stepInfos,+ }: {+ status?: WorkflowRunStatus;+ stepInfos: WorkflowRunStepInfos;+ }) =>+ getWorkflowRunOrFail.mockResolvedValue({+ id: WORKFLOW_RUN_ID,+ status,+ state: { stepInfos },+ } as unknown as WorkflowRunWorkspaceEntity);++ const findStepAwaitingAnswer = () =>+ service.findStepAwaitingAnswer({+ threadId: THREAD_ID,+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ });++ beforeEach(() => {+ jest.clearAllMocks();+ updateWorkflowRun.mockResolvedValue(undefined);+ });++ describe('findStepAwaitingAnswer', () => {+ it('finds the PENDING step holding the conversation and leaves it PENDING', async () => {+ mockWorkflowRun({+ stepInfos: {+ [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: THREAD_ID },+ },+ });++ expect(await findStepAwaitingAnswer()).toEqual({+ status: 'AWAITING_ANSWER',+ stepId: AGENT_STEP_ID,+ });+ expect(updateWorkflowRun).not.toHaveBeenCalled();+ });++ it('asks to wait out a step that has asked but is not parked yet', async () => {+ mockWorkflowRun({+ stepInfos: {+ [AGENT_STEP_ID]: { status: StepStatus.RUNNING, threadId: THREAD_ID },+ },+ });++ expect(await findStepAwaitingAnswer()).toEqual({+ status: 'NOT_YET_AWAITING',+ });+ });++ it.each([+ [+ 'the run is no longer running',+ WorkflowRunStatus.STOPPED,+ { status: StepStatus.PENDING, threadId: THREAD_ID },+ ],+ [+ 'the step moved on',+ WorkflowRunStatus.RUNNING,+ { status: StepStatus.SUCCESS, threadId: THREAD_ID },+ ],+ [+ 'a retry replaced the conversation',+ WorkflowRunStatus.RUNNING,+ { status: StepStatus.PENDING, error: 'failed' },+ ],+ ])('reports no longer awaiting when %s', async (_, status, stepInfo) => {+ mockWorkflowRun({ status, stepInfos: { [AGENT_STEP_ID]: stepInfo } });++ expect(await findStepAwaitingAnswer()).toEqual({+ status: 'NO_LONGER_AWAITING',+ });+ expect(updateWorkflowRun).not.toHaveBeenCalled();+ });+ });++ describe('updateStepInfoIfPending', () => {+ const claimInConversation = () =>+ service.updateStepInfoIfPending({+ stepId: AGENT_STEP_ID,+ stepInfo: { status: StepStatus.RUNNING },+ expectedThreadId: THREAD_ID,+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ });++ it('claims a PENDING step still holding the expected conversation', async () => {+ mockWorkflowRun({+ stepInfos: {+ [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: THREAD_ID },+ },+ });++ expect(await claimInConversation()).toBe(true);+ expect(updateWorkflowRun).toHaveBeenCalledWith({+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ partialUpdate: {+ state: {+ stepInfos: {+ [AGENT_STEP_ID]: {+ status: StepStatus.RUNNING,+ threadId: THREAD_ID,+ },+ },+ },+ },+ });+ });++ it.each([+ [+ 'the run is no longer running',+ WorkflowRunStatus.STOPPED,+ { status: StepStatus.PENDING, threadId: THREAD_ID },+ ],+ [+ 'the step already resumed',+ WorkflowRunStatus.RUNNING,+ { status: StepStatus.RUNNING, threadId: THREAD_ID },+ ],+ [+ 'the step waits on something other than a question',+ WorkflowRunStatus.RUNNING,+ { status: StepStatus.PENDING },+ ],+ [+ 'the step holds another conversation',+ WorkflowRunStatus.RUNNING,+ { status: StepStatus.PENDING, threadId: 'other-thread-id' },+ ],+ ])('claims nothing when %s', async (_, status, stepInfo) => {+ mockWorkflowRun({ status, stepInfos: { [AGENT_STEP_ID]: stepInfo } });++ expect(await claimInConversation()).toBe(false);+ expect(updateWorkflowRun).not.toHaveBeenCalled();+ });+ });++ describe('endWorkflowRun', () => {+ it('closes the question a conversation of the run still offers', async () => {+ mockWorkflowRun({+ stepInfos: {+ [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: THREAD_ID },+ other: { status: StepStatus.SUCCESS },+ },+ });+ threadRepository.find.mockResolvedValue([+ { id: THREAD_ID, pendingQuestionMessageId: 'question-message-id' },+ ]);+ threadRepository.update.mockResolvedValue({ affected: 1 });+ messagePartRepository.find.mockResolvedValue([+ {+ id: 'part-id',+ toolName: ASK_QUESTIONS_TOOL_NAME,+ toolOutput: { result: { questions: [], status: 'pending' } },+ },+ ]);++ await service.endWorkflowRun({+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ status: WorkflowRunStatus.STOPPED,+ });++ expect(threadRepository.update).toHaveBeenCalledWith(+ WORKSPACE_ID,+ { id: THREAD_ID, pendingQuestionMessageId: 'question-message-id' },+ { pendingQuestionMessageId: null },+ );+ expect(messagePartRepository.update).toHaveBeenCalledWith(+ WORKSPACE_ID,+ { id: 'part-id' },+ { toolOutput: { result: { questions: [], status: 'skipped' } } },+ );+ });++ it('leaves a question an answer has just claimed to that answer', async () => {+ mockWorkflowRun({+ stepInfos: {+ [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: THREAD_ID },+ },+ });+ threadRepository.find.mockResolvedValue([+ { id: THREAD_ID, pendingQuestionMessageId: 'question-message-id' },+ ]);+ threadRepository.update.mockResolvedValue({ affected: 0 });++ await service.endWorkflowRun({+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ status: WorkflowRunStatus.STOPPED,+ });++ expect(messagePartRepository.update).not.toHaveBeenCalled();+ });++ it('still ends the run when its questions cannot be closed', async () => {+ mockWorkflowRun({+ stepInfos: {+ [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: THREAD_ID },+ },+ });+ threadRepository.find.mockRejectedValue(new Error('storage down'));++ await expect(+ service.endWorkflowRun({+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ status: WorkflowRunStatus.STOPPED,+ }),+ ).resolves.toBeUndefined();+ expect(updateWorkflowRun).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.tsindex 1ec53c7afbb..b48a7ade21a 100644--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts@@ -1,6 +1,7 @@import { Module } from '@nestjs/common';import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';+import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';@@ -13,6 +14,7 @@ import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runne@Module({imports: [+ AgentHistoryModule,WorkflowCommonModule,RecordPositionModule,CacheLockModule,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.tsindex 2005a2b6a53..804ce850c4a 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@@ -1,8 +1,13 @@-import { Injectable } from '@nestjs/common';+import { Injectable, Logger } from '@nestjs/common';+import {+ ASK_QUESTIONS_TOOL_NAME,+ type AskQuestionsToolResult,+} from 'twenty-shared/ai';import { type ActorMetadata } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { StepStatus, type WorkflowRunStepInfo } from 'twenty-shared/workflow';+import { In, IsNull, Not } from 'typeorm';import { v4 } from 'uuid';import { WithLock } from 'src/engine/core-modules/cache-lock/with-lock.decorator';@@ -10,6 +15,10 @@ import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service'import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';import { RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';+import { type AgentMessagePartEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message-part.entity';+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 { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import {@@ -27,13 +36,23 @@ import {WorkflowRunExceptionCode,} from 'src/modules/workflow/workflow-runner/exceptions/workflow-run.exception';+export type StepAwaitingAnswer =+ | { status: 'AWAITING_ANSWER'; stepId: string }+ | { status: 'NOT_YET_AWAITING' | 'NO_LONGER_AWAITING' };+@Injectable()export class WorkflowRunWorkspaceService {+ private readonly logger = new Logger(WorkflowRunWorkspaceService.name);+constructor(private readonly workspaceOrmManager: WorkspaceOrmManager,private readonly recordPositionService: RecordPositionService,private readonly metricsService: MetricsService,private readonly workflowRunRecordShareService: WorkflowRunRecordShareService,+ @InjectAgentHistoryRepository('agentChatThread')+ private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,+ @InjectAgentHistoryRepository('agentMessagePart')+ private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartEntity>,) {}async createCoreWorkflowRun({@@ -195,6 +214,11 @@ export class WorkflowRunWorkspaceService {await this.updateWorkflowRun({ workflowRunId, workspaceId, partialUpdate });+ await this.closeQuestionsOfEndedRun({+ stepInfos: workflowRunToUpdate.state?.stepInfos ?? {},+ workspaceId,+ });+const metricKey =status === WorkflowRunStatus.COMPLETED? MetricsKeys.WorkflowRunCompleted@@ -394,15 +418,19 @@ export class WorkflowRunWorkspaceService {// the step no longer PENDING. A stop is refused too: endWorkflowRun turns a// pending step into FAILED, and a stop still waiting on another branch// leaves the run STOPPING with the step PENDING but nothing left to resume.+ // An expected conversation must still be the step's: a retry or another loop+ // iteration replaces it.@WithLock('workflowRunId')async updateStepInfoIfPending({stepId,stepInfo,+ expectedThreadId,workflowRunId,workspaceId,}: {stepId: string;stepInfo: Partial<WorkflowRunStepInfo>;+ expectedThreadId?: string;workflowRunId: string;workspaceId: string;}): Promise<boolean> {@@ -415,7 +443,9 @@ export class WorkflowRunWorkspaceService {if (workflowRunToUpdate.status !== WorkflowRunStatus.RUNNING ||- currentStepInfo?.status !== StepStatus.PENDING+ currentStepInfo?.status !== StepStatus.PENDING ||+ (isDefined(expectedThreadId) &&+ currentStepInfo.threadId !== expectedThreadId)) {return false;}@@ -437,6 +467,55 @@ export class WorkflowRunWorkspaceService {return true;}+ // Finds the step whose agent asked a question in this conversation and is+ // still waiting for its answer: a stop, a retry or another loop iteration+ // has moved the step on or replaced its conversation. A step still RUNNING+ // has asked but not yet been parked, which an answer only has to wait out.+ // Nothing is written: the step stays PENDING, which keeps its run alive,+ // until the resume job claims it.+ @WithLock('workflowRunId')+ async findStepAwaitingAnswer({+ threadId,+ workflowRunId,+ workspaceId,+ }: {+ threadId: string;+ workflowRunId: string;+ workspaceId: string;+ }): Promise<StepAwaitingAnswer> {+ const workflowRun = await this.getWorkflowRunOrFail({+ workflowRunId,+ workspaceId,+ });++ // A run conversation names no step: it belongs to the step whose current+ // execution recorded it, so one replaced by a retry or a later loop+ // iteration belongs to no step anymore.+ const [stepId, currentStepInfo] =+ Object.entries(workflowRun.state?.stepInfos ?? {}).find(+ ([, stepInfo]) => stepInfo?.threadId === threadId,+ ) ?? [];++ if (+ workflowRun.status !== WorkflowRunStatus.RUNNING ||+ !isDefined(stepId) ||+ !isDefined(currentStepInfo) ||+ isDefined(currentStepInfo.error)+ ) {+ return { status: 'NO_LONGER_AWAITING' };+ }++ if (currentStepInfo.status === StepStatus.RUNNING) {+ return { status: 'NOT_YET_AWAITING' };+ }++ if (currentStepInfo.status !== StepStatus.PENDING) {+ return { status: 'NO_LONGER_AWAITING' };+ }++ return { status: 'AWAITING_ANSWER', stepId };+ }+@WithLock('workflowRunId')async setStepThreadId({stepId,@@ -624,6 +703,91 @@ export class WorkflowRunWorkspaceService {};}+ // An ended run resumes nothing, so a question still offered in one of its+ // conversations is closed rather than left to refuse every answer. Clearing+ // the marker is the same claim an answer makes, so the two never both win.+ // Closing is cosmetic and must not fail ending the run.+ private async closeQuestionsOfEndedRun({+ stepInfos,+ workspaceId,+ }: {+ stepInfos: Record<string, WorkflowRunStepInfo>;+ workspaceId: string;+ }): Promise<void> {+ const threadIds = Object.values(stepInfos)+ .map((stepInfo) => stepInfo.threadId)+ .filter(isDefined);++ if (threadIds.length === 0) {+ return;+ }++ try {+ const threadsAwaitingAnswer = await this.threadRepository.find(+ workspaceId,+ {+ where: { id: In(threadIds), pendingQuestionMessageId: Not(IsNull()) },+ },+ );++ for (const {+ id: threadId,+ pendingQuestionMessageId,+ } of threadsAwaitingAnswer) {+ if (!isDefined(pendingQuestionMessageId)) {+ continue;+ }++ const claim = await this.threadRepository.update(+ workspaceId,+ { id: threadId, pendingQuestionMessageId },+ { pendingQuestionMessageId: null },+ );++ if ((claim.affected ?? 0) === 0) {+ continue;+ }++ const questionParts = await this.messagePartRepository.find(+ workspaceId,+ {+ where: {+ messageId: pendingQuestionMessageId,+ toolName: ASK_QUESTIONS_TOOL_NAME,+ },+ },+ );++ for (const questionPart of questionParts) {+ const toolOutput = questionPart.toolOutput as {+ result?: AskQuestionsToolResult;+ } | null;++ if (toolOutput?.result?.status !== 'pending') {+ continue;+ }++ await this.messagePartRepository.update(+ workspaceId,+ { id: questionPart.id },+ {+ toolOutput: {+ ...toolOutput,+ result: { ...toolOutput.result, status: 'skipped' },+ },+ },+ );+ }+ }+ } catch (error) {+ this.logger.warn(+ `Failed to close the questions of an ended workflow run in workspace ${workspaceId}: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ }+ }+private markRunningStepsAsFailed({stepInfosToUpdate,}: {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.tsnew file mode 100644index 00000000000..88999c914a1--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts@@ -0,0 +1,86 @@+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 { 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';+import { type 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';++const WORKSPACE_ID = 'workspace-id';+const WORKFLOW_RUN_ID = 'workflow-run-id';+const THREAD_ID = 'thread-id';++describe('WorkflowRunnerWorkspaceService', () => {+ const workflowRunWorkspaceService = { findStepAwaitingAnswer: jest.fn() };+ const messageQueueService = { add: jest.fn() };++ const service = new WorkflowRunnerWorkspaceService(+ workflowRunWorkspaceService as unknown as WorkflowRunWorkspaceService,+ messageQueueService as unknown as MessageQueueService,+ {} as WorkflowVersionStepOperationsWorkspaceService,+ {} as WorkflowThrottlingWorkspaceService,+ {} as CoreWorkflowRunnerService,+ {} as WorkflowVersionCoreSyncService,+ );++ const resumeAgentStepWithAnswer = () =>+ service.resumeAgentStepWithAnswer({+ threadId: THREAD_ID,+ workflowRunId: WORKFLOW_RUN_ID,+ workspaceId: WORKSPACE_ID,+ });++ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe('resumeAgentStepWithAnswer', () => {+ it('schedules an explicit resume of the step awaiting the answer', async () => {+ workflowRunWorkspaceService.findStepAwaitingAnswer.mockResolvedValue({+ status: 'AWAITING_ANSWER',+ stepId: 'agent-step-id',+ });++ expect(await resumeAgentStepWithAnswer()).toEqual({+ status: 'AWAITING_ANSWER',+ stepId: 'agent-step-id',+ });+ expect(messageQueueService.add).toHaveBeenCalledWith(+ RUN_WORKFLOW_JOB_NAME,+ {+ workspaceId: WORKSPACE_ID,+ workflowRunId: WORKFLOW_RUN_ID,+ stepToResume: { stepId: 'agent-step-id', threadId: THREAD_ID },+ },+ expect.objectContaining({ id: WORKFLOW_RUN_ID }),+ );+ });++ it.each(['NOT_YET_AWAITING', 'NO_LONGER_AWAITING'])(+ 'schedules nothing when the step is %s',+ async (status) => {+ workflowRunWorkspaceService.findStepAwaitingAnswer.mockResolvedValue({+ status,+ });++ expect(await resumeAgentStepWithAnswer()).toEqual({ status });+ expect(messageQueueService.add).not.toHaveBeenCalled();+ },+ );++ it('lets a failure to schedule the resume reach the caller', async () => {+ workflowRunWorkspaceService.findStepAwaitingAnswer.mockResolvedValue({+ status: 'AWAITING_ANSWER',+ stepId: 'agent-step-id',+ });+ messageQueueService.add.mockRejectedValueOnce(+ new Error('Queue unavailable'),+ );++ await expect(resumeAgentStepWithAnswer()).rejects.toThrow(+ 'Queue unavailable',+ );+ });+ });+});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.tsindex 205ae641d37..0ad5941b86a 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@@ -26,7 +26,10 @@ import { buildRetryStepInfos } from 'src/modules/workflow/workflow-runner/utils/import { buildRunWorkflowJobOptions } from 'src/modules/workflow/workflow-runner/utils/build-run-workflow-job-options.util';import { getRunnableStepIds } from 'src/modules/workflow/workflow-runner/utils/get-runnable-step-ids.util';import { WorkflowThrottlingWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run-queue/workspace-services/workflow-throttling.workspace-service';-import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';+import {+ type StepAwaitingAnswer,+ WorkflowRunWorkspaceService,+} from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';import { CoreWorkflowRunnerService } from 'src/modules/workflow/workflow-runner/services/core-workflow-runner.service';import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';@@ -172,6 +175,39 @@ export class WorkflowRunnerWorkspaceService {});}+ // The answer is already recorded in the step's conversation. The step stays+ // PENDING, which keeps its run alive, until the resume job claims it.+ async resumeAgentStepWithAnswer({+ threadId,+ workflowRunId,+ workspaceId,+ }: {+ threadId: string;+ workflowRunId: string;+ workspaceId: string;+ }): Promise<StepAwaitingAnswer> {+ const stepAwaitingAnswer =+ await this.workflowRunWorkspaceService.findStepAwaitingAnswer({+ threadId,+ workflowRunId,+ workspaceId,+ });++ if (stepAwaitingAnswer.status === 'AWAITING_ANSWER') {+ await this.messageQueueService.add<RunWorkflowJobData>(+ RunWorkflowJob.name,+ {+ workspaceId,+ workflowRunId,+ stepToResume: { stepId: stepAwaitingAnswer.stepId, threadId },+ },+ buildRunWorkflowJobOptions(workflowRunId),+ );+ }++ return stepAwaitingAnswer;+ }+async stopWorkflowRun(workspaceId: string, workflowRunId: string) {const workflowRun =await this.workflowRunWorkspaceService.getWorkflowRunOrFail({diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.tsindex f3db538b2d0..d6b6a5d12a5 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts@@ -16,6 +16,9 @@ import {import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';import { type MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';import { getQueueToken } from 'src/engine/core-modules/message-queue/utils/get-queue-token.util';+import { RUN_WORKFLOW_JOB_NAME } from 'src/modules/workflow/workflow-runner/constants/run-workflow-job-name';+import { type RunWorkflowJobData } from 'src/modules/workflow/workflow-runner/types/run-workflow-job-data.type';+import { buildRunWorkflowJobOptions } from 'src/modules/workflow/workflow-runner/utils/build-run-workflow-job-options.util';import { type CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';@@ -30,6 +33,8 @@ import { type CoreWorkflowVersionWriteService } from 'src/engine/core-modules/woimport { WORKFLOW_CRON_TRIGGER_CACHE_KEY } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/constants/workflow-cron-trigger-cache-key.constant';import { type CodeStepBuildService } from 'src/modules/workflow/workflow-builder/workflow-version-step/code-step/services/code-step-build.service';+import { type AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';import { type WorkflowActionFactory } from 'src/modules/workflow/workflow-executor/factories/workflow-action.factory';const workspaceId = SEED_APPLE_WORKSPACE_ID;@@ -68,11 +73,13 @@ describe('core workflow execution and queue compatibility (e2e)', () => {triggerType = 'MANUAL',triggerSettings = {},steps = [emptyStep()],+ triggerNextStepIds = steps.length > 0 ? [steps[0].id] : [],}: {mirrorless?: boolean;triggerType?: string;triggerSettings?: object;steps?: WorkflowAction[];+ triggerNextStepIds?: string[];} = {}): Promise<Fixture> => {let coreWorkflowId = randomUUID();let coreWorkflowVersionId = randomUUID();@@ -82,7 +89,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {name: 'B-Async trigger',type: triggerType,settings: { outputSchema: {}, ...triggerSettings },- nextStepIds: steps.length > 0 ? [steps[0].id] : [],+ nextStepIds: triggerNextStepIds,};if (mirrorless) {@@ -879,6 +886,372 @@ describe('core workflow execution and queue compatibility (e2e)', () => {);});+ describe('an agent step that asks a question', () => {+ const QUESTIONS = [+ {+ header: 'Quote',+ question: 'Send the quote to the customer?',+ options: [{ label: 'Send it' }, { label: 'Hold it' }],+ },+ ];++ const agentStep = (nextStepIds: string[]): WorkflowAction =>+ ({+ ...emptyStep(),+ name: 'Draft the quote',+ type: WorkflowActionType.AI_AGENT,+ nextStepIds,+ settings: {+ ...settings,+ input: { prompt: 'Draft the quote', canAskQuestions: true },+ },+ }) as WorkflowAction;++ const agentResult = (+ overrides: Partial<AgentExecutionResult>,+ ): AgentExecutionResult =>+ ({+ result: { response: '' },+ usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },+ cacheCreationTokens: 0,+ nativeWebSearchCallCount: 0,+ hasNoMoreAvailableCredits: false,+ modelId: 'test-model',+ ...overrides,+ }) as AgentExecutionResult;++ const askingResult = agentResult({+ isPaused: true,+ steps: [+ {+ content: [+ {+ type: 'tool-call',+ toolCallId: 'ask-1',+ toolName: 'ask_questions',+ input: { questions: QUESTIONS },+ },+ {+ type: 'tool-result',+ toolCallId: 'ask-1',+ toolName: 'ask_questions',+ input: { questions: QUESTIONS },+ output: {+ success: true,+ message:+ 'Questions presented to the user; awaiting their answer.',+ result: { questions: QUESTIONS, status: 'pending' },+ },+ },+ ],+ },+ ] as AgentExecutionResult['steps'],+ });++ const replyingResult = agentResult({+ result: { response: 'Quote sent' },+ steps: [+ { content: [{ type: 'text', text: 'Quote sent' }] },+ ] as AgentExecutionResult['steps'],+ });++ const mockAgent = () =>+ jest+ .spyOn(+ getAppProviderByClassName<AgentAsyncExecutorService>(+ 'AgentAsyncExecutorService',+ ),+ 'executeAgent',+ )+ .mockResolvedValueOnce(askingResult)+ .mockResolvedValueOnce(replyingResult);++ const getConversation = async (threadId: string) => {+ const [thread] = await global.testDataSource.query(+ `SELECT "pendingQuestionMessageId" FROM "${schema}"."agentChatThread" WHERE id = $1`,+ [threadId],+ );+ const messages = await global.testDataSource.query(+ `SELECT id, role FROM "${schema}"."agentMessage" WHERE "threadId" = $1 ORDER BY "processedAt", "createdAt"`,+ [threadId],+ );++ return { thread, messages };+ };++ const startAskingRun = async () => {+ const finalStep = emptyStep();+ const agent = agentStep([finalStep.id]);+ // A run reads through its workspace workflow record, which a+ // mirrorless fixture does not have.+ const fixture = await createFixture({ steps: [agent, finalStep] });+ const runId = await runFixture(fixture);+ const run = await waitForStep(runId, agent.id, 'PENDING');+ const threadId: string = run.state.stepInfos[agent.id].threadId;+ const { thread } = await getConversation(threadId);++ return {+ runId,+ agent,+ finalStep,+ threadId,+ questionMessageId: thread.pendingQuestionMessageId as string,+ };+ };++ const answer = ({+ threadId,+ messageId,+ }: {+ threadId: string;+ messageId: string;+ }) =>+ request(`http://localhost:${APP_PORT}`)+ .post('/metadata')+ .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)+ .send({+ query: `mutation Answer($threadId: UUID!, $messageId: UUID!, $answers: [AgentChatQuestionAnswerInput!]!) {+ answerAgentChatQuestion(threadId: $threadId, messageId: $messageId, answers: $answers) { messageId streamId }+ }`,+ variables: {+ threadId,+ messageId,+ answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],+ },+ });++ it('records no conversation for an agent that answers without asking', async () => {+ jest+ .spyOn(+ getAppProviderByClassName<AgentAsyncExecutorService>(+ 'AgentAsyncExecutorService',+ ),+ 'executeAgent',+ )+ .mockResolvedValueOnce(replyingResult);+ const finalStep = emptyStep();+ const agent = agentStep([finalStep.id]);+ const fixture = await createFixture({ steps: [agent, finalStep] });+ const runId = await runFixture(fixture);++ const run = await waitForRun(runId, 'COMPLETED');++ expect(run.state.stepInfos[agent.id]).toMatchObject({+ status: 'SUCCESS',+ result: { response: 'Quote sent' },+ });+ expect(run.state.stepInfos[agent.id].threadId).toBeUndefined();++ const threads = await global.testDataSource.query(+ `SELECT id FROM "${schema}"."agentChatThread" WHERE "workflowRunId" = $1`,+ [runId],+ );++ expect(threads).toEqual([]);+ });++ it('pauses the run on the question and resumes the same conversation with the answer', async () => {+ const executeAgent = mockAgent();+ const { runId, agent, finalStep, threadId, questionMessageId } =+ await startAskingRun();++ expect(questionMessageId).toBeDefined();+ expect((await getRun(runId)).state.stepInfos[finalStep.id].status).toBe(+ 'NOT_STARTED',+ );++ const response = await answer({ threadId, messageId: questionMessageId });++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.answerAgentChatQuestion.streamId).toBeNull();++ const run = await waitForRun(runId, 'COMPLETED');++ expect(run.state.stepInfos[agent.id]).toMatchObject({+ status: 'SUCCESS',+ result: { response: 'Quote sent' },+ threadId,+ });+ expect(run.state.stepInfos[finalStep.id].status).toBe('SUCCESS');++ const resumedWith = executeAgent.mock.calls[1][0];++ expect(resumedWith.messages).toEqual([]);+ expect(JSON.stringify(resumedWith.priorModelMessages)).toContain(+ 'Send it',+ );++ const { thread, messages } = await getConversation(threadId);++ expect(thread.pendingQuestionMessageId).toBeNull();+ expect(messages.map(({ role }: { role: string }) => role)).toEqual([+ 'user',+ 'assistant',+ 'user',+ 'assistant',+ ]);+ });++ it('refuses a second answer to the same question', async () => {+ mockAgent();+ const { runId, threadId, questionMessageId } = await startAskingRun();++ expect(+ (await answer({ threadId, messageId: questionMessageId })).body.errors,+ ).toBeUndefined();+ await waitForRun(runId, 'COMPLETED');++ const second = await answer({ threadId, messageId: questionMessageId });++ expect(JSON.stringify(second.body.errors)).toContain(+ 'QUESTION_NOT_PENDING',+ );+ });++ it('closes the question when the run is stopped and refuses a later answer', async () => {+ mockAgent();+ const { runId, agent, threadId, questionMessageId } =+ await startAskingRun();++ await workflowGraphqlRequest(+ 'mutation Stop($id: UUID!) { stopWorkflowRun(workflowRunId: $id) { id status } }',+ { id: runId },+ );+ await waitForRun(runId, 'STOPPED');++ expect(+ (await getConversation(threadId)).thread.pendingQuestionMessageId,+ ).toBeNull();++ const response = await answer({ threadId, messageId: questionMessageId });++ expect(JSON.stringify(response.body.errors)).toContain(+ 'QUESTION_NOT_PENDING',+ );++ const { thread, messages } = await getConversation(threadId);+ const [questionPart] = await global.testDataSource.query(+ `SELECT "toolOutput" FROM "${schema}"."agentMessagePart" WHERE "messageId" = $1 AND "toolName" = 'ask_questions'`,+ [questionMessageId],+ );++ // Nothing can resume a stopped run, so the question stops being offered+ // rather than coming back after every refused answer.+ expect(thread.pendingQuestionMessageId).toBeNull();+ expect(questionPart.toolOutput.result.status).toBe('skipped');+ expect(messages).toHaveLength(2);+ expect((await getRun(runId)).state.stepInfos[agent.id].status).toBe(+ 'FAILED',+ );+ });++ it('keeps the run alive while the resume is queued, even once a parallel branch has finished', async () => {+ const executeAgent = mockAgent();+ const agent = agentStep([]);+ const parallelBranch = emptyStep();+ const fixture = await createFixture({+ steps: [agent, parallelBranch],+ triggerNextStepIds: [agent.id, parallelBranch.id],+ });+ const runId = await runFixture(fixture);+ const pausedRun = await waitForStep(runId, agent.id, 'PENDING');++ await waitForStep(runId, parallelBranch.id, 'SUCCESS');++ const threadId: string = pausedRun.state.stepInfos[agent.id].threadId;+ const { thread } = await getConversation(threadId);+ const queue = global.app.get<MessageQueueService>(+ getQueueToken(MessageQueue.workflowQueue),+ );++ // Holds the resume back, so the run's fate can be decided while it is+ // still queued.+ const enqueue = jest.spyOn(queue, 'add').mockResolvedValueOnce(undefined);++ const response = await answer({+ threadId,+ messageId: thread.pendingQuestionMessageId,+ });+ const [[resumeJobName, resumeJobData, resumeJobOptions]] =+ enqueue.mock.calls;++ enqueue.mockRestore();++ expect(response.body.errors).toBeUndefined();+ expect(resumeJobData).toMatchObject({+ stepToResume: { stepId: agent.id, threadId },+ });++ // The decision a parallel branch finishing in that window takes.+ await queue.add<RunWorkflowJobData>(+ RUN_WORKFLOW_JOB_NAME,+ {+ workspaceId,+ workflowRunId: runId,+ lastExecutedStepId: parallelBranch.id,+ },+ buildRunWorkflowJobOptions(runId),+ );+ await new Promise((resolve) => setTimeout(resolve, 1000));++ const queuedRun = await getRun(runId);++ expect(queuedRun.status).toBe('RUNNING');+ expect(queuedRun.state.stepInfos[agent.id].status).toBe('PENDING');++ // Delivered twice: the second finds the step already claimed.+ await queue.add(resumeJobName, resumeJobData, resumeJobOptions);+ await queue.add(resumeJobName, resumeJobData, resumeJobOptions);++ const run = await waitForRun(runId, 'COMPLETED');++ expect(run.state.stepInfos[agent.id]).toMatchObject({+ status: 'SUCCESS',+ result: { response: 'Quote sent' },+ threadId,+ });+ expect(executeAgent).toHaveBeenCalledTimes(2);+ });++ it('keeps the question open when the resume cannot be scheduled, so it can be answered again', async () => {+ mockAgent();+ const { runId, agent, threadId, questionMessageId } =+ await startAskingRun();++ const enqueue = jest+ .spyOn(+ global.app.get<MessageQueueService>(+ getQueueToken(MessageQueue.workflowQueue),+ ),+ 'add',+ )+ .mockRejectedValueOnce(new Error('Queue unavailable'));++ const failedAnswer = await answer({+ threadId,+ messageId: questionMessageId,+ });++ enqueue.mockRestore();++ expect(failedAnswer.body.errors).toBeDefined();+ expect((await getRun(runId)).state.stepInfos[agent.id]).toMatchObject({+ status: 'PENDING',+ threadId,+ });++ const { thread, messages } = await getConversation(threadId);++ expect(thread.pendingQuestionMessageId).toBe(questionMessageId);+ expect(messages).toHaveLength(2);++ expect(+ (await answer({ threadId, messageId: questionMessageId })).body.errors,+ ).toBeUndefined();+ await waitForRun(runId, 'COMPLETED');+ });+ });+it('stops a pending delay and ignores its later resume job', async () => {const finalStep = emptyStep();const delay: WorkflowAction = {diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.tsindex 11f28daad5a..e7e15d6cf57 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts@@ -832,7 +832,7 @@ describe('core workflow visibility (e2e)', () => {'WorkflowAgentConversationWorkspaceService',);- const recordedThreadId = await conversationService.recordExecution({+ const recordedConversation = await conversationService.recordExecution({workspaceId: SEED_APPLE_WORKSPACE_ID,workflowRunId,stepId: 'trigger',@@ -847,8 +847,8 @@ describe('core workflow visibility (e2e)', () => {},});- expect(recordedThreadId).not.toBeNull();- threadId = recordedThreadId!;+ expect(recordedConversation).not.toBeNull();+ threadId = recordedConversation!.threadId;});afterAll(async () => {diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.tsindex 30645b1b90d..73ae9add70d 100644--- a/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts+++ b/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts@@ -130,6 +130,11 @@ describe('versioned agent history upgrade (integration)', () => {dataSource = owners.manager.connection;const owner = await owners.findOneByOrFail({ workspaceId: WORKSPACE_ID });+ // Threads a workflow run owns arrived with 2.44 and have no member to own+ // them in the core tables 2.42 moves history back to.+ await dataSource.query(+ `DELETE FROM "${SCHEMA}"."agentChatThread" WHERE "workflowRunId" IS NOT NULL`,+ );await runCommand('down');await dataSource.query('INSERT INTO core."agentChatThread" (id, "workspaceId", "userWorkspaceId", title, "activeStreamId") VALUES ($1, $2, $3, $4, $5)',diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.tsindex dc20d2c79aa..559c2acb548 100644--- a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts+++ b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts@@ -11,6 +11,7 @@ import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-mimport { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';import { type WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';@@ -23,7 +24,6 @@ const RUN_ON_WORKSPACE_ARGS = {const FIELD_UNIVERSAL_IDENTIFIERS = [STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier,- STANDARD_OBJECTS.agentChatThread.fields.workflowStepId.universalIdentifier,STANDARD_OBJECTS.workflowRun.fields.agentChatThreads.universalIdentifier,];@@ -125,6 +125,12 @@ describe('2-44 workspace command 1790607161319 - AddWorkflowRunToChatThreadsComm],},});+ // Run conversations only exist from 2.44 on; dropping their run link+ // would leave them ownerless and unlinked, which no earlier version can+ // hold (2.42's reverse copy, for one, requires an owner).+ await global.testDataSource.query(+ `DELETE FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."agentChatThread" WHERE "workflowRunId" IS NOT NULL`,+ );await run({fieldMetadata: {flatEntityToCreate: [],diff --git a/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap b/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snapindex d2d3eadb0bc..58a3ed0441b 100644--- a/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap+++ b/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap@@ -73,9 +73,6 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e"workflowRun": {"universalIdentifier": "2187f4c6-bff3-4b80-8585-c82965faf79b",},- "workflowStepId": {- "universalIdentifier": "ba4091ef-dfa2-4a99-bfb3-322ef9a745ab",- },"workspaceMember": {"universalIdentifier": "6f3ed3b5-0642-4a2a-9558-98376adb60f4",},diff --git a/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.tsindex d4687482d36..9b566e650e5 100644--- a/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts+++ b/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts@@ -63,9 +63,6 @@ export const STANDARD_OBJECT_FIELDS = {workflowRun: {universalIdentifier: '2187f4c6-bff3-4b80-8585-c82965faf79b',},- workflowStepId: {- universalIdentifier: 'ba4091ef-dfa2-4a99-bfb3-322ef9a745ab',- },pendingQuestionMessageId: {universalIdentifier: '51a9b421-7d90-4a59-9712-036ea9721e65',},diff --git a/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.tsindex 085cbb645a3..efc0688d745 100644--- a/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts+++ b/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts@@ -6,5 +6,8 @@ export const workflowAiAgentActionSettingsSchema =input: z.object({agentId: z.string().optional(),prompt: z.string().optional(),+ // Off by default: an agent that can ask pauses its run until someone+ // answers, which existing workflows were not built to expect.+ canAskQuestions: z.boolean().optional(),}),});