Skip to content

The open alternative to Salesforce, designed for AI.

feat(workflow): a form step opens an Ask that its submission answers (#26768)

Félix Malfaitac3cecffe3ca
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.ts
index af22a6eae52..8d8b60f6e4a 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
@@ -49,6 +49,7 @@ 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 { InputAskModule } from 'src/modules/input-ask/input-ask.module';
import { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workflow-runner.module';
@Module({
@@ -82,6 +83,7 @@ import { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workf
DashboardToolsModule,
WorkflowToolsModule,
WorkflowRunnerModule,
+ InputAskModule,
],
providers: [
AgentChatActorService,
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.ts
index a88591f61ab..27275cc6a94 100644
--- 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.ts
@@ -8,6 +8,7 @@ import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-h
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 InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
import { type WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';
const WORKSPACE_ID = 'workspace-id';
@@ -36,11 +37,14 @@ describe('AgentChatWorkflowQuestionService', () => {
resumeAgentStepWithAnswer: jest.fn(),
};
+ const inputAskWorkspaceService = { answerForToolCall: 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,
+ inputAskWorkspaceService as unknown as InputAskWorkspaceService,
);
const answers: AskQuestionAnswer[] = [
@@ -73,6 +77,7 @@ describe('AgentChatWorkflowQuestionService', () => {
agentChatService.resolvePendingQuestion.mockResolvedValue({
answerText: 'Send the quote?\nSend it',
turnId: 'turn-id',
+ toolCallId: 'tool-call-id',
rollback: ROLLBACK,
});
agentChatService.addMessage.mockResolvedValue({ id: ANSWER_MESSAGE_ID });
@@ -111,6 +116,12 @@ describe('AgentChatWorkflowQuestionService', () => {
});
expect(messageRepository.delete).not.toHaveBeenCalled();
expect(agentChatService.restorePendingQuestion).not.toHaveBeenCalled();
+ expect(inputAskWorkspaceService.answerForToolCall).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ threadId: THREAD_ID,
+ toolCallId: 'tool-call-id',
+ response: { answers, answerText: 'Send the quote?\nSend it' },
+ });
});
it('refuses an answer that says nothing', async () => {
@@ -194,5 +205,6 @@ describe('AgentChatWorkflowQuestionService', () => {
messageId: QUESTION_MESSAGE_ID,
}),
);
+ expect(inputAskWorkspaceService.answerForToolCall).not.toHaveBeenCalled();
});
});
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.ts
index f8ccaaec956..5a2dd287caa 100644
--- 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.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
import { isNonEmptyString } from '@sniptt/guards';
import { PermissionFlagType } from 'twenty-shared/constants';
@@ -18,6 +18,7 @@ import {
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
+import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-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
@@ -26,12 +27,15 @@ import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-ru
// continues the same conversation with it.
@Injectable()
export class AgentChatWorkflowQuestionService {
+ private readonly logger = new Logger(AgentChatWorkflowQuestionService.name);
+
constructor(
@InjectAgentHistoryRepository('agentMessage')
private readonly messageRepository: AgentHistoryRepository<AgentMessageEntity>,
private readonly agentChatService: AgentChatService,
private readonly permissionsService: PermissionsService,
private readonly workflowRunnerWorkspaceService: WorkflowRunnerWorkspaceService,
+ private readonly inputAskWorkspaceService: InputAskWorkspaceService,
) {}
async answer({
@@ -156,5 +160,20 @@ export class AgentChatWorkflowQuestionService {
throw error;
}
+
+ // Only once the run has taken the answer: the Ask mirrors it and gates
+ // nothing, so a failure here must not undo an accepted answer.
+ try {
+ await this.inputAskWorkspaceService.answerForToolCall({
+ workspaceId,
+ threadId: thread.id,
+ toolCallId: resolved.toolCallId,
+ response: { answers, answerText: resolved.answerText },
+ });
+ } catch (error) {
+ this.logger.warn(
+ `Failed to record the answer to Ask of tool call ${resolved.toolCallId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(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.ts
index fa8d5415653..73a844e9446 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
@@ -801,6 +801,7 @@ export class AgentChatService {
workspaceId: string;
}): Promise<{
answerText: string;
+ toolCallId: string | null;
turnId: string | null;
rollback: PendingQuestionRollback;
}> {
@@ -895,6 +896,7 @@ export class AgentChatService {
return {
answerText,
+ toolCallId: pendingPart.toolCallId,
turnId: message.turnId,
rollback: { partId: pendingPart.id, previousOutput },
};
diff --git a/packages/twenty-server/src/modules/input-ask/input-ask.module.ts b/packages/twenty-server/src/modules/input-ask/input-ask.module.ts
new file mode 100644
index 00000000000..2a1375558b1
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/input-ask.module.ts
@@ -0,0 +1,12 @@
+import { Module } from '@nestjs/common';
+
+import { RecordPositionModule } from 'src/engine/core-modules/record-position/record-position.module';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
+
+@Module({
+ imports: [RecordPositionModule, WorkspaceCacheModule],
+ providers: [InputAskWorkspaceService],
+ exports: [InputAskWorkspaceService],
+})
+export class InputAskModule {}
diff --git a/packages/twenty-server/src/modules/input-ask/workspace-services/input-ask.workspace-service.ts b/packages/twenty-server/src/modules/input-ask/workspace-services/input-ask.workspace-service.ts
new file mode 100644
index 00000000000..6866503b517
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/workspace-services/input-ask.workspace-service.ts
@@ -0,0 +1,315 @@
+import { Injectable } from '@nestjs/common';
+
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+import { StepStatus, type WorkflowRunStepInfo } from 'twenty-shared/workflow';
+import { IsNull, Not } from 'typeorm';
+
+import { RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';
+import {
+ TwentyOrmException,
+ TwentyOrmExceptionCode,
+} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { InputAskStatus } from 'src/modules/input-ask/enums/input-ask-status.enum';
+import { type InputAskWorkspaceEntity } from 'src/modules/input-ask/standard-objects/input-ask.workspace-entity';
+import { type FormFieldMetadata } from 'src/modules/workflow/workflow-executor/workflow-actions/form/types/workflow-form-action-settings.type';
+
+const isDuplicateEntry = (error: unknown): boolean =>
+ error instanceof TwentyOrmException &&
+ error.code === TwentyOrmExceptionCode.DUPLICATE_ENTRY_DETECTED;
+
+@Injectable()
+export class InputAskWorkspaceService {
+ constructor(
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly recordPositionService: RecordPositionService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ ) {}
+
+ // A run can re-enter a form it already asked about (a retried worker, a
+ // retried run, the next item of an iterator): the previous answer belonged
+ // to the previous execution, while a question still pending may be one
+ // someone is looking at.
+ async openForFormStep({
+ workspaceId,
+ workflowRunId,
+ stepId,
+ stepName,
+ fields,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ stepId: string;
+ stepName: string;
+ fields: FormFieldMetadata[];
+ }): Promise<void> {
+ if (!(await this.hasInputAskObject(workspaceId))) {
+ return;
+ }
+
+ await this.executeAsSystem(workspaceId, async (inputAskRepository) => {
+ const reopenResult = await inputAskRepository.update(
+ {
+ workflowRunId,
+ stepId,
+ toolCallId: IsNull(),
+ status: Not(InputAskStatus.PENDING),
+ },
+ {
+ name: stepName,
+ status: InputAskStatus.PENDING,
+ form: { fields },
+ response: null,
+ answeredAt: null,
+ },
+ );
+
+ if ((reopenResult.affected ?? 0) > 0) {
+ return;
+ }
+
+ const existingInputAsk = await inputAskRepository.findOne({
+ where: { workflowRunId, stepId, toolCallId: IsNull() },
+ });
+
+ if (isDefined(existingInputAsk)) {
+ return;
+ }
+
+ const position = await this.recordPositionService.buildRecordPosition({
+ value: 'first',
+ objectMetadata: { isCustom: false, nameSingular: 'inputAsk' },
+ workspaceId,
+ });
+
+ try {
+ await inputAskRepository.insert({
+ name: stepName,
+ status: InputAskStatus.PENDING,
+ form: { fields },
+ workflowRunId,
+ stepId,
+ position,
+ });
+ } catch (error) {
+ // Two workers can clear the read above at the same time, and the loser
+ // of that race wants the winner's row rather than a failed step.
+ if (!isDuplicateEntry(error)) {
+ throw error;
+ }
+ }
+ });
+ }
+
+ // Records the answer the run has already accepted. The run's own step
+ // transition is what refuses a second submission, so nothing here gates
+ // anything: a row that is missing, canceled or already answered simply has
+ // nothing left to record.
+ async answerForFormStep({
+ workspaceId,
+ workflowRunId,
+ stepId,
+ response,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ stepId: string;
+ response: Record<string, unknown>;
+ }): Promise<void> {
+ if (!(await this.hasInputAskObject(workspaceId))) {
+ return;
+ }
+
+ await this.executeAsSystem(workspaceId, async (inputAskRepository) => {
+ await inputAskRepository.update(
+ {
+ workflowRunId,
+ stepId,
+ toolCallId: IsNull(),
+ status: InputAskStatus.PENDING,
+ },
+ {
+ status: InputAskStatus.ANSWERED,
+ response,
+ answeredAt: new Date().toISOString(),
+ },
+ );
+ });
+ }
+
+ // An agent can ask several times in one conversation, each question its own
+ // Ask keyed on the tool call that asked it. The conversation's pending
+ // marker and the run's step stay what gate the answer; this only records
+ // the question where people can find it.
+ async openForAgentQuestion({
+ workspaceId,
+ workflowRunId,
+ stepId,
+ threadId,
+ toolCallId,
+ name,
+ questions,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ stepId: string;
+ threadId: string;
+ toolCallId: string;
+ name: string;
+ questions: unknown[];
+ }): Promise<void> {
+ if (!(await this.hasInputAskObject(workspaceId))) {
+ return;
+ }
+
+ await this.executeAsSystem(workspaceId, async (inputAskRepository) => {
+ const position = await this.recordPositionService.buildRecordPosition({
+ value: 'first',
+ objectMetadata: { isCustom: false, nameSingular: 'inputAsk' },
+ workspaceId,
+ });
+
+ try {
+ await inputAskRepository.insert({
+ name,
+ status: InputAskStatus.PENDING,
+ form: { questions },
+ workflowRunId,
+ stepId,
+ threadId,
+ toolCallId,
+ position,
+ });
+ } catch (error) {
+ // A retried recording of the same question wants the existing row.
+ if (!isDuplicateEntry(error)) {
+ throw error;
+ }
+ }
+ });
+ }
+
+ // An agent can ask several times in one conversation, so the answer is
+ // matched to its question by tool call, never to whichever Ask is pending.
+ async answerForToolCall({
+ workspaceId,
+ threadId,
+ toolCallId,
+ response,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ toolCallId: string | null;
+ response: Record<string, unknown>;
+ }): Promise<void> {
+ if (
+ !isDefined(toolCallId) ||
+ !(await this.hasInputAskObject(workspaceId))
+ ) {
+ return;
+ }
+
+ await this.executeAsSystem(workspaceId, async (inputAskRepository) => {
+ await inputAskRepository.update(
+ { threadId, toolCallId, status: InputAskStatus.PENDING },
+ {
+ status: InputAskStatus.ANSWERED,
+ response,
+ answeredAt: new Date().toISOString(),
+ },
+ );
+ });
+ }
+
+ // A run that ends before its answer arrives leaves the question unanswerable,
+ // and an unanswerable question left PENDING sits in someone's list forever.
+ // A form whose step completed was answered even if recording the answer
+ // failed at submission, so it closes as answered from the step's result.
+ async cancelPendingForWorkflowRun({
+ workspaceId,
+ workflowRunId,
+ stepInfos,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ stepInfos: Record<string, WorkflowRunStepInfo>;
+ }): Promise<void> {
+ if (!(await this.hasInputAskObject(workspaceId))) {
+ return;
+ }
+
+ await this.executeAsSystem(workspaceId, async (inputAskRepository) => {
+ const pendingFormInputAsks = await inputAskRepository.find({
+ where: {
+ workflowRunId,
+ status: InputAskStatus.PENDING,
+ toolCallId: IsNull(),
+ },
+ select: { id: true, stepId: true },
+ });
+
+ for (const pendingFormInputAsk of pendingFormInputAsks) {
+ const stepInfo = isDefined(pendingFormInputAsk.stepId)
+ ? stepInfos[pendingFormInputAsk.stepId]
+ : undefined;
+
+ if (stepInfo?.status !== StepStatus.SUCCESS) {
+ continue;
+ }
+
+ await inputAskRepository.update(
+ { id: pendingFormInputAsk.id, status: InputAskStatus.PENDING },
+ {
+ status: InputAskStatus.ANSWERED,
+ response: isPlainObject(stepInfo.result) ? stepInfo.result : null,
+ answeredAt: new Date().toISOString(),
+ },
+ );
+ }
+
+ await inputAskRepository.update(
+ { workflowRunId, status: InputAskStatus.PENDING },
+ { status: InputAskStatus.CANCELED },
+ );
+ });
+ }
+
+ // The object reaches existing workspaces through a workspace upgrade command,
+ // which runs per workspace while this code is already serving — and an
+ // interrupted upgrade leaves the rest without it indefinitely. Until a
+ // workspace has the object, a form step behaves exactly as it did before.
+ private async hasInputAskObject(workspaceId: string): Promise<boolean> {
+ const { flatObjectMetadataMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatObjectMetadataMaps',
+ ]);
+
+ return isDefined(
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.inputAsk.universalIdentifier
+ ],
+ );
+ }
+
+ private async executeAsSystem<TResult>(
+ workspaceId: string,
+ execute: (
+ inputAskRepository: WorkspaceRepository<InputAskWorkspaceEntity>,
+ ) => Promise<TResult>,
+ ): Promise<TResult> {
+ return this.workspaceOrmManager.executeInWorkspaceContext(
+ async () =>
+ execute(
+ this.workspaceOrmManager.getRepository<InputAskWorkspaceEntity>(
+ 'inputAsk',
+ { shouldBypassPermissionChecks: true },
+ ),
+ ),
+ buildSystemAuthContext(workspaceId),
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
index 70995a96102..3c1e2eb2929 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
@@ -102,6 +102,8 @@ export class AiAgentWorkflowAction implements WorkflowAction {
(isDefined(resumedThreadId)
? this.workflowAgentConversationService.recordContinuation({
workspaceId,
+ workflowRunId: runInfo.workflowRunId,
+ stepId: currentStepId,
threadId: resumedThreadId,
agentId: agent?.id ?? null,
executionResult,
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.ts
index 0fe0217d8e6..b61ba87963f 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
@@ -1,3 +1,4 @@
+import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
import { Injectable } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
@@ -55,6 +56,7 @@ export class WorkflowAgentConversationWorkspaceService {
private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartEntity>,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
+ private readonly inputAskWorkspaceService: InputAskWorkspaceService,
) {}
async recordExecution({
@@ -115,6 +117,8 @@ export class WorkflowAgentConversationWorkspaceService {
const isAwaitingAnswer = await this.recordReply({
workspaceId,
+ workflowRunId,
+ stepId,
threadId,
turnId,
agentId,
@@ -128,11 +132,15 @@ export class WorkflowAgentConversationWorkspaceService {
// already recorded as the last message, so only the agent's reply is added.
async recordContinuation({
workspaceId,
+ workflowRunId,
+ stepId,
threadId,
agentId,
executionResult,
}: {
workspaceId: string;
+ workflowRunId: string;
+ stepId: string;
threadId: string;
agentId: string | null;
executionResult?: RecordedExecutionResult;
@@ -141,6 +149,8 @@ export class WorkflowAgentConversationWorkspaceService {
const isAwaitingAnswer = await this.recordReply({
workspaceId,
+ workflowRunId,
+ stepId,
threadId,
turnId,
agentId,
@@ -179,12 +189,16 @@ export class WorkflowAgentConversationWorkspaceService {
private async recordReply({
workspaceId,
+ workflowRunId,
+ stepId,
threadId,
turnId,
agentId,
executionResult,
}: {
workspaceId: string;
+ workflowRunId: string;
+ stepId: string;
threadId: string;
turnId: string;
agentId: string | null;
@@ -206,13 +220,29 @@ export class WorkflowAgentConversationWorkspaceService {
parts: replyParts,
});
- if (
- executionResult?.isPaused !== true ||
- !isDefined(findPendingQuestionPart(replyParts))
- ) {
+ const pendingQuestionPart = executionResult?.isPaused
+ ? findPendingQuestionPart(replyParts)
+ : undefined;
+
+ if (!isDefined(pendingQuestionPart)) {
return false;
}
+ const questions = pendingQuestionPart.output?.result?.questions ?? [];
+
+ // Opened before the marker: a question pending without its Ask is one
+ // nobody can find, while an Ask whose marker failed ends canceled with the
+ // run that step then fails.
+ await this.inputAskWorkspaceService.openForAgentQuestion({
+ workspaceId,
+ workflowRunId,
+ stepId,
+ threadId,
+ toolCallId: pendingQuestionPart.toolCallId,
+ name: questions[0]?.question ?? 'Question',
+ questions,
+ });
+
// The same marker a chat question sets, so the answer flow can claim the
// question exactly once.
await this.threadRepository.update(
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.ts
index 1f69b334fe7..e7cfc6e18bd 100644
--- 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.ts
@@ -2,11 +2,17 @@ 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 { InputAskModule } from 'src/modules/input-ask/input-ask.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],
+ imports: [
+ AgentHistoryModule,
+ WorkspaceCacheModule,
+ WorkflowRunModule,
+ InputAskModule,
+ ],
providers: [WorkflowAgentConversationWorkspaceService],
exports: [WorkflowAgentConversationWorkspaceService],
})
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form-action.module.ts
index 1600d235b9c..c538dceb41c 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form-action.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form-action.module.ts
@@ -1,8 +1,10 @@
import { Module } from '@nestjs/common';
+import { InputAskModule } from 'src/modules/input-ask/input-ask.module';
import { FormWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action';
@Module({
+ imports: [InputAskModule],
providers: [FormWorkflowAction],
exports: [FormWorkflowAction],
})
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts
index 07f857cbcbd..2a79339874b 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts
@@ -2,6 +2,8 @@ import { Injectable } from '@nestjs/common';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
+import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
+
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
@@ -13,9 +15,14 @@ import { isWorkflowFormAction } from 'src/modules/workflow/workflow-executor/wor
@Injectable()
export class FormWorkflowAction implements WorkflowAction {
+ constructor(
+ private readonly inputAskWorkspaceService: InputAskWorkspaceService,
+ ) {}
+
async execute({
currentStepId,
steps,
+ runInfo,
}: WorkflowActionInput): Promise<WorkflowActionOutput> {
const step = findStepOrThrow({
stepId: currentStepId,
@@ -29,6 +36,17 @@ export class FormWorkflowAction implements WorkflowAction {
);
}
+ // Written before the step reports itself pending: a run parked without its
+ // Ask is a question nobody can find, while an early Ask is only briefly
+ // unanswerable and is canceled if the run dies before parking.
+ await this.inputAskWorkspaceService.openForFormStep({
+ workspaceId: runInfo.workspaceId,
+ workflowRunId: runInfo.workflowRunId,
+ stepId: step.id,
+ stepName: step.name,
+ fields: step.settings.input,
+ });
+
return {
pendingEvent: true,
};
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.ts
index dd0d3e9c9dd..6c17e683b46 100644
--- 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.ts
@@ -8,6 +8,7 @@ import { type MetricsService } from 'src/engine/core-modules/metrics/metrics.ser
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 { type InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
import {
WorkflowRunStatus,
type WorkflowRunWorkspaceEntity,
@@ -30,6 +31,7 @@ describe('WorkflowRunWorkspaceService', () => {
{
incrementCounterForEvent: jest.fn(),
} as unknown as MetricsService,
+ {} as InputAskWorkspaceService,
{} as WorkflowRunRecordShareService,
threadRepository as unknown as AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
messagePartRepository as unknown as AgentHistoryRepository<AgentMessagePartEntity>,
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.ts
index b48a7ade21a..63940b18599 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
@@ -7,6 +7,7 @@ import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
import { RecordPositionModule } from 'src/engine/core-modules/record-position/record-position.module';
import { WorkflowRunRecordShareModule } from 'src/engine/core-modules/workflow/workflow-run-record-share.module';
+import { InputAskModule } from 'src/modules/input-ask/input-ask.module';
import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';
import { DeleteWorkflowRunsCommand } from 'src/modules/workflow/workflow-runner/workflow-run/command/delete-workflow-runs.command';
import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';
@@ -22,6 +23,7 @@ import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runne
WorkspaceIteratorModule,
FeatureFlagModule,
WorkflowRunRecordShareModule,
+ InputAskModule,
],
providers: [
WorkflowRunWorkspaceService,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
index 804ce850c4a..9b284963bcf 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
@@ -21,6 +21,7 @@ import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-
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 { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
import {
WorkflowRunStatus,
type WorkflowRunState,
@@ -48,6 +49,7 @@ export class WorkflowRunWorkspaceService {
private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly recordPositionService: RecordPositionService,
private readonly metricsService: MetricsService,
+ private readonly inputAskWorkspaceService: InputAskWorkspaceService,
private readonly workflowRunRecordShareService: WorkflowRunRecordShareService,
@InjectAgentHistoryRepository('agentChatThread')
private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
@@ -219,6 +221,22 @@ export class WorkflowRunWorkspaceService {
workspaceId,
});
+ // A run that ends can no longer consume an answer, so an Ask still
+ // waiting on one stops being actionable here rather than outliving it.
+ // The run has ended either way: a failure here only leaves a stale Ask,
+ // and must not turn the run's outcome into a failure.
+ try {
+ await this.inputAskWorkspaceService.cancelPendingForWorkflowRun({
+ workspaceId,
+ workflowRunId,
+ stepInfos: updatedStepInfos,
+ });
+ } catch (error) {
+ this.logger.error(
+ `Failed to close the Asks of workflow run ${workflowRunId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+
const metricKey =
status === WorkflowRunStatus.COMPLETED
? MetricsKeys.WorkflowRunCompleted
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-runner.module.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-runner.module.ts
index 1a80e5b9aa9..e4ae1139221 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-runner.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-runner.module.ts
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
+import { InputAskModule } from 'src/modules/input-ask/input-ask.module';
import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';
import { CodeStepBuildModule } from 'src/modules/workflow/workflow-builder/workflow-version-step/code-step/code-step-build.module';
import { WorkflowVersionStepModule } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module';
@@ -26,6 +27,7 @@ import { WorkflowVersionCoreModule } from 'src/engine/core-modules/workflow/work
CodeStepBuildModule,
WorkflowCoreModule,
WorkflowVersionCoreModule,
+ InputAskModule,
],
providers: [
WorkflowRunnerWorkspaceService,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
index 88999c914a1..e89b96fc976 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
@@ -1,5 +1,6 @@
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 InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-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';
@@ -22,6 +23,7 @@ describe('WorkflowRunnerWorkspaceService', () => {
{} as WorkflowThrottlingWorkspaceService,
{} as CoreWorkflowRunnerService,
{} as WorkflowVersionCoreSyncService,
+ {} as InputAskWorkspaceService,
);
const resumeAgentStepWithAnswer = () =>
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
index 0ad5941b86a..57987ef6c66 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
@@ -1,4 +1,4 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
import { msg } from '@lingui/core/macro';
import { type ActorMetadata } from 'twenty-shared/types';
@@ -8,6 +8,7 @@ import { StepStatus } from 'twenty-shared/workflow';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
import {
WorkflowVersionStepException,
WorkflowVersionStepExceptionCode,
@@ -35,6 +36,8 @@ import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow
@Injectable()
export class WorkflowRunnerWorkspaceService {
+ private readonly logger = new Logger(WorkflowRunnerWorkspaceService.name);
+
constructor(
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
@InjectMessageQueue(MessageQueue.workflowQueue)
@@ -43,6 +46,7 @@ export class WorkflowRunnerWorkspaceService {
private readonly workflowThrottlingWorkspaceService: WorkflowThrottlingWorkspaceService,
private readonly coreWorkflowRunnerService: CoreWorkflowRunnerService,
private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,
+ private readonly inputAskWorkspaceService: InputAskWorkspaceService,
) {}
async run({
@@ -168,6 +172,24 @@ export class WorkflowRunnerWorkspaceService {
);
}
+ // Recorded before the run is resumed: the resumed run can reach its end,
+ // and ending a run cancels whatever is still pending, so an Ask answered
+ // afterwards would read as canceled on a form somebody did answer. The
+ // submission is already accepted, so a failure here must not keep the run
+ // from resuming; the run's end records the answer from the step instead.
+ try {
+ await this.inputAskWorkspaceService.answerForFormStep({
+ workspaceId,
+ workflowRunId,
+ stepId,
+ response: enrichedResponse,
+ });
+ } catch (error) {
+ this.logger.warn(
+ `Could not record the answer to form step ${stepId} of workflow run ${workflowRunId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+
await this.resume({
workspaceId,
workflowRunId,
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.ts
index d6b6a5d12a5..58504d87161 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
@@ -26,6 +26,7 @@ import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/ge
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { type InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
import { type ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
import { type AutomatedTriggerWorkspaceService } from 'src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.workspace-service';
@@ -855,6 +856,253 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
expect(run.state.stepInfos[finalStep.id].status).toBe('NOT_STARTED');
});
+ describe('the Ask a form step opens', () => {
+ const getInputAsks = async (runId: string) =>
+ global.testDataSource.query(
+ `SELECT name, "stepId", status, form, response, "answeredAt" FROM "${schema}"."inputAsk" WHERE "workflowRunId" = $1`,
+ [runId],
+ );
+
+ const approvalForm = (nextStepIds: string[]): WorkflowAction => ({
+ ...formStep(nextStepIds),
+ name: 'Approve the discount',
+ });
+
+ it('opens while the form waits and is answered on submit', async () => {
+ const finalStep = emptyStep();
+ const form = approvalForm([finalStep.id]);
+ const fixture = await createFixture({
+ mirrorless: true,
+ steps: [form, finalStep],
+ });
+ const runId = await runFixture(fixture);
+
+ await waitForStep(runId, form.id, 'PENDING');
+
+ const [pendingInputAsk] = await getInputAsks(runId);
+
+ expect(pendingInputAsk).toMatchObject({
+ name: 'Approve the discount',
+ stepId: form.id,
+ status: 'PENDING',
+ response: null,
+ answeredAt: null,
+ });
+ expect(pendingInputAsk.form).toEqual({ fields: form.settings.input });
+
+ const response = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'Approved',
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ await waitForRun(runId, 'COMPLETED');
+
+ const answeredInputAsks = await getInputAsks(runId);
+
+ expect(answeredInputAsks).toHaveLength(1);
+ expect(answeredInputAsks[0]).toMatchObject({
+ stepId: form.id,
+ status: 'ANSWERED',
+ response: { answer: 'Approved' },
+ });
+ expect(answeredInputAsks[0].answeredAt).not.toBeNull();
+ });
+
+ it('resumes the run when recording the answer fails and records it once the run ends', async () => {
+ const finalStep = emptyStep();
+ const form = approvalForm([finalStep.id]);
+ const fixture = await createFixture({
+ mirrorless: true,
+ steps: [form, finalStep],
+ });
+ const runId = await runFixture(fixture);
+
+ await waitForStep(runId, form.id, 'PENDING');
+
+ const answerForFormStep = jest
+ .spyOn(
+ getAppProviderByClassName<InputAskWorkspaceService>(
+ 'InputAskWorkspaceService',
+ ),
+ 'answerForFormStep',
+ )
+ .mockRejectedValueOnce(new Error('Ask write failed'));
+
+ const response = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'Approved',
+ });
+
+ answerForFormStep.mockRestore();
+
+ expect(response.body.errors).toBeUndefined();
+ await waitForRun(runId, 'COMPLETED');
+
+ expect(await getInputAsks(runId)).toMatchObject([
+ { status: 'ANSWERED', response: { answer: 'Approved' } },
+ ]);
+ });
+
+ it('completes the run even when its Asks cannot be closed', async () => {
+ const finalStep = emptyStep();
+ const form = approvalForm([finalStep.id]);
+ const fixture = await createFixture({
+ mirrorless: true,
+ steps: [form, finalStep],
+ });
+ const runId = await runFixture(fixture);
+
+ await waitForStep(runId, form.id, 'PENDING');
+
+ const cancelPending = jest
+ .spyOn(
+ getAppProviderByClassName<InputAskWorkspaceService>(
+ 'InputAskWorkspaceService',
+ ),
+ 'cancelPendingForWorkflowRun',
+ )
+ .mockRejectedValueOnce(new Error('Ask write failed'));
+
+ const response = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'Approved',
+ });
+
+ expect(response.body.errors).toBeUndefined();
+
+ const run = await waitForRun(runId, 'COMPLETED');
+
+ cancelPending.mockRestore();
+
+ expect(run.status).toBe('COMPLETED');
+ expect(run.state.stepInfos[finalStep.id].status).toBe('SUCCESS');
+ });
+
+ it('keeps the first answer when a second submission is refused', async () => {
+ const finalStep = emptyStep();
+ const form = approvalForm([finalStep.id]);
+ const fixture = await createFixture({
+ mirrorless: true,
+ steps: [form, finalStep],
+ });
+ const runId = await runFixture(fixture);
+
+ await waitForStep(runId, form.id, 'PENDING');
+ await submitForm({ runId, stepId: form.id, answer: 'Approved' });
+ await waitForRun(runId, 'COMPLETED');
+
+ const second = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'Approved again',
+ });
+
+ expect(second.body.errors).toBeDefined();
+ expect(await getInputAsks(runId)).toMatchObject([
+ { status: 'ANSWERED', response: { answer: 'Approved' } },
+ ]);
+ });
+
+ // Every iteration of a loop re-executes the same step in the same run, so
+ // the Ask keyed on the run and the step is reused. Without reopening it,
+ // the first iteration's answer would stand for the second.
+ it('reopens for each iteration of a form inside a loop', async () => {
+ const afterLoop = emptyStep();
+ const form = approvalForm([]);
+ const iterator: WorkflowAction = {
+ ...emptyStep(),
+ type: WorkflowActionType.ITERATOR,
+ settings: {
+ ...settings,
+ input: {
+ items: ['first', 'second'],
+ initialLoopStepIds: [form.id],
+ },
+ },
+ nextStepIds: [afterLoop.id],
+ };
+
+ form.nextStepIds = [iterator.id];
+
+ const fixture = await createFixture({
+ mirrorless: true,
+ steps: [iterator, form, afterLoop],
+ });
+ const runId = await runFixture(fixture);
+
+ await waitForStep(runId, form.id, 'PENDING');
+ expect(await getInputAsks(runId)).toMatchObject([{ status: 'PENDING' }]);
+
+ const first = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'First item',
+ });
+
+ expect(first.body.errors).toBeUndefined();
+ await waitForStep(runId, form.id, 'PENDING');
+
+ const reopenedInputAsks = await getInputAsks(runId);
+
+ expect(reopenedInputAsks).toHaveLength(1);
+ expect(reopenedInputAsks[0]).toMatchObject({
+ stepId: form.id,
+ status: 'PENDING',
+ response: null,
+ answeredAt: null,
+ });
+
+ const second = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'Second item',
+ });
+
+ expect(second.body.errors).toBeUndefined();
+ await waitForRun(runId, 'COMPLETED');
+ expect(await getInputAsks(runId)).toMatchObject([
+ { status: 'ANSWERED', response: { answer: 'Second item' } },
+ ]);
+ });
+
+ it('is canceled when its run ends before anyone answers, and stays canceled', async () => {
+ const finalStep = emptyStep();
+ const form = approvalForm([finalStep.id]);
+ const fixture = await createFixture({
+ mirrorless: true,
+ steps: [form, finalStep],
+ });
+ const runId = await runFixture(fixture);
+
+ await waitForStep(runId, form.id, 'PENDING');
+ expect(await getInputAsks(runId)).toMatchObject([{ status: 'PENDING' }]);
+
+ const response = await workflowGraphqlRequest(
+ 'mutation Stop($id: UUID!) { stopWorkflowRun(workflowRunId: $id) { id status } }',
+ { id: runId },
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ await waitForRun(runId, 'STOPPED');
+ expect(await getInputAsks(runId)).toMatchObject([{ status: 'CANCELED' }]);
+
+ const late = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'Too late',
+ });
+
+ expect(late.body.errors).toBeDefined();
+ expect(await getInputAsks(runId)).toMatchObject([
+ { status: 'CANCELED', response: null },
+ ]);
+ });
+ });
+
// A stop waiting on a step still running on another branch parks the run in
// STOPPING with the form still PENDING; nothing would resume an answer.
it('refuses a submission while its run is stopping', async () => {
@@ -966,6 +1214,12 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
.mockResolvedValueOnce(askingResult)
.mockResolvedValueOnce(replyingResult);
+ const getThreadInputAsks = async (threadId: string) =>
+ global.testDataSource.query(
+ `SELECT name, status, "toolCallId", "stepId", "workflowRunId", form, response FROM "${schema}"."inputAsk" WHERE "threadId" = $1`,
+ [threadId],
+ );
+
const getConversation = async (threadId: string) => {
const [thread] = await global.testDataSource.query(
`SELECT "pendingQuestionMessageId" FROM "${schema}"."agentChatThread" WHERE id = $1`,
@@ -1059,6 +1313,17 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
expect((await getRun(runId)).state.stepInfos[finalStep.id].status).toBe(
'NOT_STARTED',
);
+ expect(await getThreadInputAsks(threadId)).toEqual([
+ {
+ name: 'Send the quote to the customer?',
+ status: 'PENDING',
+ toolCallId: 'ask-1',
+ stepId: agent.id,
+ workflowRunId: runId,
+ form: { questions: QUESTIONS },
+ response: null,
+ },
+ ]);
const response = await answer({ threadId, messageId: questionMessageId });
@@ -1084,6 +1349,14 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
const { thread, messages } = await getConversation(threadId);
expect(thread.pendingQuestionMessageId).toBeNull();
+ expect(await getThreadInputAsks(threadId)).toMatchObject([
+ {
+ status: 'ANSWERED',
+ response: {
+ answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],
+ },
+ },
+ ]);
expect(messages.map(({ role }: { role: string }) => role)).toEqual([
'user',
'assistant',
@@ -1140,6 +1413,9 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
expect(thread.pendingQuestionMessageId).toBeNull();
expect(questionPart.toolOutput.result.status).toBe('skipped');
expect(messages).toHaveLength(2);
+ expect(await getThreadInputAsks(threadId)).toMatchObject([
+ { status: 'CANCELED', response: null },
+ ]);
expect((await getRun(runId)).state.stepInfos[agent.id].status).toBe(
'FAILED',
);
@@ -1244,11 +1520,39 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
expect(thread.pendingQuestionMessageId).toBe(questionMessageId);
expect(messages).toHaveLength(2);
+ expect(await getThreadInputAsks(threadId)).toMatchObject([
+ { status: 'PENDING', response: null },
+ ]);
expect(
(await answer({ threadId, messageId: questionMessageId })).body.errors,
).toBeUndefined();
await waitForRun(runId, 'COMPLETED');
+
+ expect(await getThreadInputAsks(threadId)).toMatchObject([
+ { status: 'ANSWERED' },
+ ]);
+ });
+
+ it('resumes the run when the Ask cannot record the answer', async () => {
+ mockAgent();
+ const { runId, threadId, questionMessageId } = await startAskingRun();
+
+ const answerForToolCall = jest
+ .spyOn(
+ getAppProviderByClassName<InputAskWorkspaceService>(
+ 'InputAskWorkspaceService',
+ ),
+ 'answerForToolCall',
+ )
+ .mockRejectedValueOnce(new Error('Ask write failed'));
+
+ const response = await answer({ threadId, messageId: questionMessageId });
+
+ answerForToolCall.mockRestore();
+
+ expect(response.body.errors).toBeUndefined();
+ await waitForRun(runId, 'COMPLETED');
});
});
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.ts
index e7e15d6cf57..2ef66603884 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
@@ -992,6 +992,142 @@ describe('core workflow visibility (e2e)', () => {
});
});
+ // An Ask has no grants of its own either: whoever reads the run reads its
+ // questions, and nobody else.
+ describe('the Ask an agent question records on a run', () => {
+ let askCoreWorkflowId: string;
+ let askWorkspaceWorkflowId: string;
+ let threadId: string;
+
+ const QUESTIONS = [
+ {
+ header: 'Quote',
+ question: 'Send the quote to the customer?',
+ options: [{ label: 'Send it' }, { label: 'Hold it' }],
+ },
+ ];
+
+ const readAsks = async (
+ requester: (query: string, variables?: object) => request.Test,
+ ) => {
+ const response = await requester(
+ `
+ query ReadAsks($threadId: UUID!) {
+ inputAsks(filter: { threadId: { eq: $threadId } }) {
+ edges {
+ node {
+ id
+ status
+ }
+ }
+ }
+ }
+ `,
+ { threadId },
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.inputAsks.edges;
+ };
+
+ beforeAll(async () => {
+ let workspaceWorkflowVersionId: string;
+
+ ({
+ coreWorkflowId: askCoreWorkflowId,
+ workspaceWorkflowId: askWorkspaceWorkflowId,
+ workspaceWorkflowVersionId,
+ } = await createActiveManualWorkflow('Workflow With A Question'));
+
+ const runResponse = await workflowGraphqlRequest(LEGACY_RUN_MUTATION, {
+ input: { workflowVersionId: workspaceWorkflowVersionId },
+ });
+
+ expect(runResponse.body.errors).toBeUndefined();
+
+ const askRunId: string =
+ runResponse.body.data.runWorkflowVersion.workflowRunId;
+ const [{ state }] = await global.testDataSource.query(
+ `SELECT state FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."workflowRun" WHERE id = $1`,
+ [askRunId],
+ );
+ const askStepId = state.flow.steps[0].id as string;
+
+ const conversationService =
+ getAppProviderByClassName<WorkflowAgentConversationWorkspaceService>(
+ 'WorkflowAgentConversationWorkspaceService',
+ );
+
+ const recordedConversation = await conversationService.recordExecution({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workflowRunId: askRunId,
+ stepId: askStepId,
+ title: 'Draft the quote',
+ agentId: null,
+ prompt: 'Draft the quote',
+ initiatorUserWorkspaceId: null,
+ executionResult: {
+ 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: 'Awaiting an answer.',
+ result: { questions: QUESTIONS, status: 'pending' },
+ },
+ },
+ ],
+ },
+ ] as AgentExecutionResult['steps'],
+ },
+ });
+
+ expect(recordedConversation?.isAwaitingAnswer).toBe(true);
+ threadId = recordedConversation!.threadId;
+ });
+
+ afterAll(async () => {
+ if (isDefined(askWorkspaceWorkflowId)) {
+ await setVisibility(askCoreWorkflowId, WorkflowVisibility.WORKSPACE);
+ await workflowGraphqlRequest(DESTROY_WORKFLOW_MUTATION, {
+ id: askWorkspaceWorkflowId,
+ });
+ }
+ });
+
+ it('is readable by another member while the workflow is visible to the workspace', async () => {
+ expect(
+ (await setVisibility(askCoreWorkflowId, WorkflowVisibility.WORKSPACE))
+ .body.errors,
+ ).toBeUndefined();
+ // Its status depends on whether the run has finished meanwhile, which
+ // has nothing to do with who may read it.
+ expect(await readAsks(asOtherMember)).toHaveLength(1);
+ });
+
+ it('is hidden from another member once the workflow is private, but not from its creator', async () => {
+ expect(
+ (await setVisibility(askCoreWorkflowId, WorkflowVisibility.PRIVATE))
+ .body.errors,
+ ).toBeUndefined();
+ expect(await readAsks(asOtherMember)).toEqual([]);
+ expect(await readAsks(workflowGraphqlRequest)).toHaveLength(1);
+ });
+ });
+
// Removing a member deletes their membership, and the database then clears
// the creator of every workflow they created.
describe('the runs of a private workflow whose creator is removed from the workspace', () => {