Skip to content

The open alternative to Salesforce, designed for AI.

feat(workflow): human input instructions for agent steps, routed to the creator's inbox (#27190)

Félix Malfait6f13adf4017f
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index 83a52b81b74..a620e20a1f2 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -84,7 +84,8 @@ When adding AI behavior:
- `workspaceMemberId` is the member who receives it, and `text` is the message, in markdown.
- `threadKey` picks the conversation per app and member: a new key starts one titled `title`, a known key adds to it. `idempotencyKey` identifies the message in it, so sending again with the same keys writes nothing and retries never duplicate it.
-- `toolCall` (optional) ends the message on `ask_questions`, `request_form` or `propose_tool_call` with a `send_email` or `draft_email` call (`input`: `toolName`, `arguments` with `recipients`, `subject` and an HTML `body`, and a `summary`), which pause the conversation until the member answers, or on one of the app's own tools by `logicFunctionUniversalIdentifier`, rendered by its front component without pausing.
+- `toolCall` (optional) ends the message on `ask_questions`, `request_form` or `propose_tool_call`, which pause the conversation until the member answers, or on one of the app's own tools by `logicFunctionUniversalIdentifier`, rendered by its front component without pausing.
+- `propose_tool_call` takes `toolName`, `arguments` and a one-sentence `summary`. The tool must be one the app's default role could run itself, such as `create_one_person` or `update_one_opportunity` (with `id`), or `send_email` / `draft_email` (`recipients`, `subject` and an HTML `body`), which need no permission of the app. The member reviews the call, edits it if they want, and the approved call runs with their own access.
- Only one call the member answers (`ask_questions`, `request_form`, `propose_tool_call`) can wait at a time; another fails with `THREAD_AWAITING_ANSWER` until they answer. Plain messages and app tool calls are still accepted.
- A conversation the member deleted is not recreated.
- The app's default role needs `SystemPermissionFlag.AI`, and the member needs the AI permission.
diff --git a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
index d92eb8becd7..c7bcc9a1316 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
@@ -293,12 +293,14 @@ Key points:
- `toolCall` (optional) ends the message on one of:
- a call the member answers, which pauses the conversation: `ask_questions`
(1 to 4 multiple-choice questions), `request_form` (fields to fill in) or
- `propose_tool_call` with a `send_email` or `draft_email` call (an email to
- review, then send, save as a draft or discard). Its `input` takes the
- `toolName`, the `arguments` you would send the email with (`recipients`,
- `subject`, and a `body` in HTML) and a one-sentence `summary`. The member
- reviews it in the same email editor as an email the assistant proposes, and
- the action they choose (send or save as a draft) runs with their own access;
+ `propose_tool_call` (a call to approve). Its `input` takes the `toolName`,
+ the `arguments` you would call the tool with and a one-sentence `summary`.
+ The tool must be one your app's default role could run itself, such as
+ `create_one_person` or `update_one_opportunity` (with the record `id`); an
+ email (`send_email` or `draft_email`, with `recipients`, `subject` and a
+ `body` in HTML) needs no permission of your app. The member reviews the call
+ in the same card as a call the assistant proposes, edits it if they want, and
+ the approved call runs with their own access;
- one of your app's own tools, by `logicFunctionUniversalIdentifier`, rendered
by its front component with the `input` and `output` you pass. It does not
pause the conversation.
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx
index d792929baae..60f238068f3 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx
@@ -4,6 +4,7 @@ import { CoreObjectNameSingular } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { useApplyAgentChatThreadUpdate } from '@/ai/hooks/useApplyAgentChatThreadUpdate';
+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
import { useLeaveRemovedAiChatThread } from '@/ai/hooks/useLeaveRemovedAiChatThread';
import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';
import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';
@@ -73,8 +74,12 @@ export const AgentChatThreadRecordOperationsEffect = () => {
const createdThread =
operation.createdRecord as AgentChatThreadRecord;
- // Workflow run conversations are listed with the run, not in the chat list.
- if (!isDefined(createdThread.workflowRunId)) {
+ // a workflow run's conversation is listed only for the member it is routed to
+ if (
+ !isDefined(createdThread.workflowRunId) ||
+ createdThread.workspaceMemberId ===
+ store.get(currentWorkspaceMemberState.atom)?.id
+ ) {
addAgentChatThread(createdThread);
}
return;
diff --git a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts
index dc1423f01fe..c7bc6f56da1 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts
@@ -64,6 +64,12 @@ export const useRefreshAgentChatThreads = () => {
return undefined;
}
+ const listFilter = buildAgentChatThreadListFilter({
+ chatObjectMetadataItem,
+ currentWorkspaceMemberId: store.get(currentWorkspaceMemberState.atom)
+ ?.id,
+ });
+
const result = await apolloCoreClient
.query<RecordGqlOperationFindManyResult>({
query: generateFindManyRecordsQuery({
@@ -74,13 +80,8 @@ export const useRefreshAgentChatThreads = () => {
}),
variables: {
filter: isDefined(threadIdFilter)
- ? {
- and: [
- buildAgentChatThreadListFilter(chatObjectMetadataItem),
- threadIdFilter,
- ],
- }
- : buildAgentChatThreadListFilter(chatObjectMetadataItem),
+ ? { and: [listFilter, threadIdFilter] }
+ : listFilter,
orderBy: [
{
[getAgentChatThreadLastActivityFieldName(
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/buildAgentChatThreadListFilter.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/buildAgentChatThreadListFilter.test.ts
index a9a4c701464..d6bf59fb428 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/buildAgentChatThreadListFilter.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/buildAgentChatThreadListFilter.test.ts
@@ -12,16 +12,44 @@ const buildChatObject = (fieldNames: string[]) =>
describe('buildAgentChatThreadListFilter', () => {
it('lists deleted chats so they can be restored', () => {
- expect(buildAgentChatThreadListFilter(buildChatObject(['title']))).toEqual(
- INCLUDE_DELETED_FILTER,
- );
+ expect(
+ buildAgentChatThreadListFilter({
+ chatObjectMetadataItem: buildChatObject(['title']),
+ currentWorkspaceMemberId: 'member-id',
+ }),
+ ).toEqual(INCLUDE_DELETED_FILTER);
+ });
+
+ it('lists only the workflow run conversations routed to the member', () => {
+ expect(
+ buildAgentChatThreadListFilter({
+ chatObjectMetadataItem: buildChatObject(['title', 'workflowRun']),
+ currentWorkspaceMemberId: 'member-id',
+ }),
+ ).toEqual({
+ and: [
+ {
+ or: [
+ { workflowRunId: { is: 'NULL' } },
+ { workspaceMemberId: { eq: 'member-id' } },
+ ],
+ },
+ INCLUDE_DELETED_FILTER,
+ ],
+ });
});
- it('leaves workflow run conversations out once chats can name a run', () => {
+ it('leaves workflow run conversations out without a current member', () => {
expect(
- buildAgentChatThreadListFilter(buildChatObject(['title', 'workflowRun'])),
+ buildAgentChatThreadListFilter({
+ chatObjectMetadataItem: buildChatObject(['title', 'workflowRun']),
+ currentWorkspaceMemberId: undefined,
+ }),
).toEqual({
- and: [{ workflowRunId: { is: 'NULL' } }, INCLUDE_DELETED_FILTER],
+ and: [
+ { or: [{ workflowRunId: { is: 'NULL' } }] },
+ INCLUDE_DELETED_FILTER,
+ ],
});
});
});
diff --git a/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts b/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts
index 175155b7b03..2d173adf064 100644
--- a/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts
+++ b/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts
@@ -1,10 +1,15 @@
import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
import { type RecordGqlOperationFilter } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
-// Deleted chats stay listed for restore; workflow run conversations belong to the run, not the list.
-export const buildAgentChatThreadListFilter = (
- chatObjectMetadataItem: Pick<EnrichedObjectMetadataItem, 'fields'>,
-): RecordGqlOperationFilter => {
+// Deleted chats stay listed for restore; a workflow run's conversation is listed for the member it is routed to.
+export const buildAgentChatThreadListFilter = ({
+ chatObjectMetadataItem,
+ currentWorkspaceMemberId,
+}: {
+ chatObjectMetadataItem: Pick<EnrichedObjectMetadataItem, 'fields'>;
+ currentWorkspaceMemberId: string | undefined;
+}): RecordGqlOperationFilter => {
const includeDeletedFilter: RecordGqlOperationFilter = {
or: [{ deletedAt: { is: 'NULL' } }, { deletedAt: { is: 'NOT_NULL' } }],
};
@@ -12,7 +17,21 @@ export const buildAgentChatThreadListFilter = (
({ name }) => name === 'workflowRun',
);
- return canNameWorkflowRun
- ? { and: [{ workflowRunId: { is: 'NULL' } }, includeDeletedFilter] }
- : includeDeletedFilter;
+ if (!canNameWorkflowRun) {
+ return includeDeletedFilter;
+ }
+
+ return {
+ and: [
+ {
+ or: [
+ { workflowRunId: { is: 'NULL' } },
+ ...(isDefined(currentWorkspaceMemberId)
+ ? [{ workspaceMemberId: { eq: currentWorkspaceMemberId } }]
+ : []),
+ ],
+ },
+ includeDeletedFilter,
+ ],
+ };
};
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.tsx
index 25f45c66930..11f269068ba 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,7 +5,6 @@ import { agentResponseSchemaToOutputSchema } from '@/ai/utils/agentResponseSchem
import { 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';
@@ -30,6 +29,8 @@ type WorkflowAiAgentPromptTabProps = {
prompt: string;
readonly: boolean;
onPromptChange: (value: string) => void;
+ humanInputInstructions: string;
+ onHumanInputInstructionsChange: (value: string) => void;
onActionUpdate?: (action: WorkflowAiAgentAction) => void;
};
@@ -38,6 +39,8 @@ export const WorkflowAiAgentPromptTab = ({
prompt,
readonly,
onPromptChange,
+ humanInputInstructions,
+ onHumanInputInstructionsChange,
onActionUpdate,
}: WorkflowAiAgentPromptTabProps) => {
const [workflowAiAgentActionAgent, setWorkflowAiAgentActionAgent] =
@@ -126,19 +129,6 @@ 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));
@@ -162,11 +152,13 @@ export const WorkflowAiAgentPromptTab = ({
readonly={readonly}
/>
- <FormBooleanFieldInput
- label={t`Can ask for input or approval`}
- defaultValue={action.settings.input.canAskQuestions === true}
+ <FormTextFieldInput
+ multiline
+ label={t`Ask for human input`}
+ placeholder={t`When should the agent stop and ask you? E.g. before sending any email or changing a deal's amount. Leave empty to never stop.`}
+ defaultValue={humanInputInstructions}
+ onChange={onHumanInputInstructionsChange}
readonly={readonly}
- onChange={handleCanAskQuestionsChange}
/>
<SettingsAgentModelCapabilities
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx
index 97659c388e1..dc65d262b74 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx
@@ -75,10 +75,13 @@ export const WorkflowEditActionAiAgent = ({
}, [agentData, setWorkflowAiAgentActionAgent]);
useResetWorkflowAiAgentPermissionsStateOnSidePanelClose();
- const actionPrompt = action.settings.input.prompt || '';
- const [prompt, setPrompt] = useState(actionPrompt);
+ const [prompt, setPrompt] = useState(action.settings.input.prompt ?? '');
+ const [humanInputInstructions, setHumanInputInstructions] = useState(
+ action.settings.input.humanInputInstructions ?? '',
+ );
- const savePrompt = useDebouncedCallback((newPrompt: string) => {
+ // saves both texts from the latest render, so editing one does not drop a pending edit of the other
+ const saveTexts = useDebouncedCallback(() => {
if (actionOptions.readonly === true) {
return;
}
@@ -89,7 +92,8 @@ export const WorkflowEditActionAiAgent = ({
...action.settings,
input: {
...action.settings.input,
- prompt: newPrompt,
+ prompt,
+ humanInputInstructions,
},
},
});
@@ -97,7 +101,12 @@ export const WorkflowEditActionAiAgent = ({
const handleAgentPromptChange = (newPrompt: string) => {
setPrompt(newPrompt);
- savePrompt(newPrompt);
+ saveTexts();
+ };
+
+ const handleHumanInputInstructionsChange = (newInstructions: string) => {
+ setHumanInputInstructions(newInstructions);
+ saveTexts();
};
const tabs: SingleTabProps[] = [
@@ -202,6 +211,10 @@ export const WorkflowEditActionAiAgent = ({
prompt={prompt}
readonly={actionOptions.readonly === true}
onPromptChange={handleAgentPromptChange}
+ humanInputInstructions={humanInputInstructions}
+ onHumanInputInstructionsChange={
+ handleHumanInputInstructionsChange
+ }
onActionUpdate={
actionOptions.readonly === true
? undefined
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts
index 5585ca2c779..b6a5d598488 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts
@@ -224,6 +224,31 @@ export class WorkflowRunRecordShareService {
}
}
+ // a run's conversation goes to this member's inbox, until a workflow can name a team inbox
+ async findCreatorWorkspaceMemberId({
+ workspaceId,
+ coreWorkflowId,
+ }: {
+ workspaceId: string;
+ coreWorkflowId: string;
+ }): Promise<string | null> {
+ const coreWorkflow = await this.coreWorkflowRepository.findOne(
+ workspaceId,
+ {
+ where: { id: coreWorkflowId },
+ select: { id: true, createdByUserWorkspaceId: true },
+ withDeleted: true,
+ },
+ );
+
+ return isDefined(coreWorkflow?.createdByUserWorkspaceId)
+ ? this.resolveWorkspaceMemberId({
+ workspaceId,
+ userWorkspaceId: coreWorkflow.createdByUserWorkspaceId,
+ })
+ : null;
+ }
+
private async resolveAccess({
workspaceId,
coreWorkflowId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-email-tool-name.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-email-tool-name.util.ts
new file mode 100644
index 00000000000..65b76d0f6ff
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-email-tool-name.util.ts
@@ -0,0 +1,6 @@
+import { EMAIL_TOOL_APPROVALS } from 'src/engine/core-modules/tool-provider/constants/email-tool-approvals.constant';
+
+export const isEmailToolName = (
+ toolName: string,
+): toolName is keyof typeof EMAIL_TOOL_APPROVALS =>
+ Object.prototype.hasOwnProperty.call(EMAIL_TOOL_APPROVALS, toolName);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util.ts
index 5c66021d220..15e5992ec86 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util.ts
@@ -2,14 +2,10 @@ import { type ProposeToolCallToolInput } from 'twenty-shared/ai';
import { ACTION_TOOL_LABELS } from 'src/engine/core-modules/tool-provider/constants/action-tool-label.constant';
import { EMAIL_TOOL_APPROVALS } from 'src/engine/core-modules/tool-provider/constants/email-tool-approvals.constant';
+import { isEmailToolName } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-email-tool-name.util';
import { buildEmailProposal } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/build-email-proposal.util';
import { type ProposedToolCallResolution } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/proposed-tool-call-resolution.type';
-const isEmailToolName = (
- toolName: string,
-): toolName is keyof typeof EMAIL_TOOL_APPROVALS =>
- Object.prototype.hasOwnProperty.call(EMAIL_TOOL_APPROVALS, toolName);
-
// for proposers without registry tools (apps posting to the inbox, workflow steps without an agent):
// an email runs only once approved, with the approver's own permissions, so nothing is looked up here
export const resolveEmailToolCallProposal = (
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 fdc6773862d..c1f89afece9 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
@@ -31,6 +31,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
import { DashboardToolsModule } from 'src/modules/dashboard/tools/dashboard-tools.module';
import { WorkflowToolsModule } from 'src/modules/workflow/workflow-tools/workflow-tools.module';
+import { AgentInboxProposalService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox-proposal.service';
import { StreamAgentChatJob } from 'src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job';
import { AgentChatResolver } from 'src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver';
import { AgentChatThreadParticipantResolver } from 'src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-thread-participant.resolver';
@@ -84,6 +85,7 @@ import { SystemPromptBuilderService } from 'src/engine/metadata-modules/ai/ai-ch
AgentChatSubscriptionResolver,
WorkspaceSetupChatResolver,
AgentInboxResolver,
+ AgentInboxProposalService,
AgentChatService,
AgentChatThreadTargetService,
AgentChatStreamingService,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
index d47679f7522..f8f6e154e34 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
@@ -1,4 +1,5 @@
import { AgentChatActorService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service';
+import { findLastMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util';
import { updateAgentChatThreadUsage } from 'src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.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';
@@ -702,14 +703,7 @@ export class StreamAgentChatJob {
turnModelId: string;
turnId: string;
}): Promise<AgentChatTurnOutcome | null> {
- const replyText =
- responseMessage.parts
- .flatMap((part) =>
- part.type === 'text' && isNonEmptyString(part.text.trim())
- ? [part.text]
- : [],
- )
- .pop() ?? null;
+ const replyText = findLastMessageText(responseMessage.parts);
const hasText = responseMessage.parts.some(
(part) => part.type === 'text' && isNonEmptyString(part.text),
);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-inbox.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-inbox.resolver.ts
index 4fb337ab0d7..6d287a1f5a5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-inbox.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-inbox.resolver.ts
@@ -19,6 +19,7 @@ import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
import { SendInboxMessageResultDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/send-inbox-message-result.dto';
import { SendInboxMessageInputDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/send-inbox-message.input';
+import { AgentInboxProposalService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox-proposal.service';
import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';
@@ -36,7 +37,10 @@ import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai
@UsePipes(ResolverValidationPipe)
@MetadataResolver()
export class AgentInboxResolver {
- constructor(private readonly agentInboxService: AgentInboxService) {}
+ constructor(
+ private readonly agentInboxService: AgentInboxService,
+ private readonly agentInboxProposalService: AgentInboxProposalService,
+ ) {}
@Mutation(() => SendInboxMessageResultDTO)
async sendInboxMessage(
@@ -48,6 +52,12 @@ export class AgentInboxResolver {
workspaceId: workspace.id,
sender: { type: 'application', application },
input,
+ resolveProposal: (proposeToolCallInput) =>
+ this.agentInboxProposalService.resolveApplicationProposal({
+ workspaceId: workspace.id,
+ application,
+ input: proposeToolCallInput,
+ }),
});
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
index 2ed95cb6353..36149e5a1c8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
@@ -125,11 +125,13 @@ export class AgentChatSharingService {
workspaceMemberId: string;
id?: string;
title?: string;
+ workflowRunId?: string;
}): Promise<AgentChatThreadWorkspaceEntity> {
const authContext = await this.getAuthContext(args);
const objectMetadata = await this.getThreadObjectMetadata(args.workspaceId);
const hasInboxState = await this.hasInboxState(args.workspaceId);
+ // workflowRunId is set by the server for a run conversation, never written by the member
await this.workspaceOrmManager.executeInWorkspaceContext(
() =>
this.workspaceOrmManager
@@ -146,11 +148,12 @@ export class AgentChatSharingService {
args.workspaceId,
async ({ manager, table }) => {
const records = await manager.query<AgentChatThreadWorkspaceEntity[]>(
- `INSERT INTO ${table('agentChatThread')} (id, title, "workspaceMemberId", "userWorkspaceId"${hasInboxState ? ', "lastActivityAt"' : ''})
- VALUES ($1, $2, $3, $4${hasInboxState ? ', clock_timestamp()' : ''}) RETURNING *`,
+ `INSERT INTO ${table('agentChatThread')} (id, title, "workflowRunId", "workspaceMemberId", "userWorkspaceId"${hasInboxState ? ', "lastActivityAt"' : ''})
+ VALUES ($1, $2, $3, $4, $5${hasInboxState ? ', clock_timestamp()' : ''}) RETURNING *`,
[
args.id ?? randomUUID(),
args.title ?? null,
+ args.workflowRunId ?? null,
authContext.workspaceMemberId,
authContext.userWorkspaceId,
],
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts
index f51cd8c510d..eaad1b6c975 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts
@@ -28,26 +28,13 @@ export class AgentChatThreadService {
private readonly participantService: AgentChatThreadParticipantService,
) {}
- async createThread({
- workspaceMemberId,
- workspaceId,
- id,
- title,
- }: {
- workspaceMemberId: string;
- workspaceId: string;
- id?: string;
- title?: string;
- }) {
- const savedThread = await this.sharingService.createThread({
- workspaceId,
- workspaceMemberId,
- id,
- title,
- });
+ async createThread(
+ args: Parameters<AgentChatSharingService['createThread']>[0],
+ ) {
+ const savedThread = await this.sharingService.createThread(args);
await this.threadRecordEventService.emitThreadCreated({
- workspaceId,
+ workspaceId: args.workspaceId,
threadId: savedThread.id,
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox-proposal.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox-proposal.service.ts
new file mode 100644
index 00000000000..ab879f82e9e
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox-proposal.service.ts
@@ -0,0 +1,77 @@
+import { Injectable } from '@nestjs/common';
+
+import { type ProposeToolCallToolInput } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { workspaceAuthContextStorage } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
+import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
+import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/tool-context.type';
+import { type ProposedToolCallResolution } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/proposed-tool-call-resolution.type';
+import { isEmailToolName } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-email-tool-name.util';
+import { resolveEmailToolCallProposal } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util';
+import { resolveProposedToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-proposed-tool-call.util';
+import { resolveRolePermissionConfig } from 'src/engine/twenty-orm/utils/resolve-role-permission-config.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+// An app proposes only calls it could run itself, checked with its own role; once
+// approved, the call runs with the member's access. An email needs none of the app's tools.
+@Injectable()
+export class AgentInboxProposalService {
+ constructor(
+ private readonly toolRegistryService: ToolRegistryService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ ) {}
+
+ async resolveApplicationProposal({
+ workspaceId,
+ application,
+ input,
+ }: {
+ workspaceId: string;
+ application: FlatApplication;
+ input: ProposeToolCallToolInput;
+ }): Promise<ProposedToolCallResolution> {
+ if (isEmailToolName(input.toolName)) {
+ return resolveEmailToolCallProposal(input);
+ }
+
+ const authContext = workspaceAuthContextStorage.getStore();
+ const { userWorkspaceRoleMap } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'userWorkspaceRoleMap',
+ ]);
+ const rolePermissionConfig = isDefined(authContext)
+ ? resolveRolePermissionConfig({
+ authContext,
+ userWorkspaceRoleMap,
+ apiKeyRoleMap: {},
+ })
+ : null;
+
+ if (
+ !isDefined(rolePermissionConfig) ||
+ !isDefined(application.defaultRoleId)
+ ) {
+ return {
+ error: `The application needs a default role to propose "${input.toolName}".`,
+ };
+ }
+
+ const toolContext: ToolContext = {
+ workspaceId,
+ roleId: application.defaultRoleId,
+ rolePermissionConfig,
+ authContext,
+ application,
+ };
+
+ return resolveProposedToolCall({
+ input,
+ findTool: (toolName) =>
+ this.toolRegistryService.findCatalogEntry(toolName, toolContext),
+ executeTool: ({ toolName, args }) =>
+ this.toolRegistryService.resolveAndExecute(toolName, args, toolContext),
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts
index 49cfedb8fc6..ba804829387 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts
@@ -10,9 +10,11 @@ import { isDefined } from 'twenty-shared/utils';
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
import { type AgentInboxSender } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type';
+import { resolveEmailToolCallProposal } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util';
import { buildInboxMessageIds } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util';
import { buildInboxMessageToolCallPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util';
import { buildToolPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-tool-part.util';
+import { type ResolveInboxProposal } from 'src/engine/metadata-modules/ai/ai-chat/types/resolve-inbox-proposal.type';
import { getAgentInboxSenderDetails } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-agent-inbox-sender-details.util';
import { isUniqueViolationError } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-unique-violation-error.util';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
@@ -44,10 +46,14 @@ export class AgentInboxService {
sender,
input,
awaitingToolCall,
+ resolveProposal = async (proposeToolCallInput) =>
+ resolveEmailToolCallProposal(proposeToolCallInput),
}: {
workspaceId: string;
sender: AgentInboxSender;
input: Omit<SendInboxMessageInput, 'toolCall'> & { toolCall?: unknown };
+ // without a resolver, only emails can be proposed: they need no tool of the sender's
+ resolveProposal?: ResolveInboxProposal;
// a pausing call the server already resolved, with its pending output
awaitingToolCall?: {
toolName: string;
@@ -84,6 +90,7 @@ export class AgentInboxService {
? await buildInboxMessageToolCallPart({
toolCall: input.toolCall,
toolCallId,
+ resolveProposal,
findApplicationTool: (logicFunctionUniversalIdentifier) =>
this.findApplicationTool({
workspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/resolve-inbox-proposal.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/resolve-inbox-proposal.type.ts
new file mode 100644
index 00000000000..e2e049db89c
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/resolve-inbox-proposal.type.ts
@@ -0,0 +1,7 @@
+import { type ProposeToolCallToolInput } from 'twenty-shared/ai';
+
+import { type ProposedToolCallResolution } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/proposed-tool-call-resolution.type';
+
+export type ResolveInboxProposal = (
+ input: ProposeToolCallToolInput,
+) => Promise<ProposedToolCallResolution>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts
index cdb8cf43811..1fecf43b048 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts
@@ -1,3 +1,4 @@
+import { resolveEmailToolCallProposal } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util';
import { buildInboxMessageToolCallPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util';
import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
@@ -19,6 +20,7 @@ const build = (toolCall: unknown) =>
SHARE_RECORDING_TOOL.universalIdentifier
? SHARE_RECORDING_TOOL
: undefined,
+ resolveProposal: async (input) => resolveEmailToolCallProposal(input),
});
describe('buildInboxMessageToolCallPart', () => {
@@ -95,6 +97,38 @@ describe('buildInboxMessageToolCallPart', () => {
});
});
+ it('proposes any call the resolver resolves for the sender', async () => {
+ const updateCall = {
+ toolName: 'update_one_opportunity',
+ arguments: { id: 'deal-1', stage: 'WON' },
+ summary: 'Mark the deal as won',
+ };
+ const proposal = {
+ ...updateCall,
+ toolLabel: 'Update Opportunity',
+ template: 'recordUpdate' as const,
+ objectNameSingular: 'opportunity',
+ recordId: 'deal-1',
+ currentValues: { stage: 'PROPOSAL' },
+ };
+
+ await expect(
+ buildInboxMessageToolCallPart({
+ toolCall: { toolName: 'propose_tool_call', input: updateCall },
+ toolCallId: TOOL_CALL_ID,
+ findApplicationTool: async () => undefined,
+ resolveProposal: async () => ({ proposal }),
+ }),
+ ).resolves.toEqual({
+ isAwaitingAnswer: true,
+ part: expect.objectContaining({
+ output: expect.objectContaining({
+ result: { status: 'pending', proposal },
+ }),
+ }),
+ });
+ });
+
it('renders an application tool with its front component without pausing', async () => {
await expect(
build({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-last-message-text.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-last-message-text.util.spec.ts
new file mode 100644
index 00000000000..aead6c4eab1
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-last-message-text.util.spec.ts
@@ -0,0 +1,40 @@
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
+
+import { findLastMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util';
+
+const textPart = (text: string) =>
+ ({ type: 'text', text }) as ExtendedUIMessagePart;
+
+describe('findLastMessageText', () => {
+ it('returns null without any text', () => {
+ expect(findLastMessageText([])).toBeNull();
+ });
+
+ it('ignores text that is only whitespace', () => {
+ expect(findLastMessageText([textPart(' \n ')])).toBeNull();
+ });
+
+ it('ignores parts that are not text', () => {
+ expect(
+ findLastMessageText([
+ textPart('Draft ready'),
+ {
+ type: 'tool-ask_questions',
+ toolCallId: 'ask-1',
+ state: 'input-available',
+ input: {},
+ } as ExtendedUIMessagePart,
+ ]),
+ ).toBe('Draft ready');
+ });
+
+ it('returns the last text of several', () => {
+ expect(
+ findLastMessageText([
+ textPart('Reading the deal'),
+ textPart('Which plan should I quote?'),
+ textPart(' '),
+ ]),
+ ).toBe('Which plan should I quote?');
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts
index d289ee8907b..faf137ad30e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts
@@ -10,7 +10,7 @@ import { type z } from 'zod';
import { buildToolPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-tool-part.util';
import { buildLogicFunctionToolName } from 'src/engine/core-modules/tool-provider/utils/build-logic-function-tool-name.util';
-import { resolveEmailToolCallProposal } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util';
+import { type ResolveInboxProposal } from 'src/engine/metadata-modules/ai/ai-chat/types/resolve-inbox-proposal.type';
import {
askQuestionsInputSchema,
buildAskQuestionsPendingOutput,
@@ -62,15 +62,17 @@ const parseOptionalRecord = (
: throwInvalidToolCall(`${name} must be an object`);
};
-const buildPausingToolPart = ({
+const buildPausingToolPart = async ({
toolName,
toolCallId,
input,
+ resolveProposal,
}: {
toolName: unknown;
toolCallId: string;
input: unknown;
-}): ExtendedUIMessagePart => {
+ resolveProposal: ResolveInboxProposal;
+}): Promise<ExtendedUIMessagePart> => {
switch (toolName) {
case ASK_QUESTIONS_TOOL_NAME: {
const questionsInput = parseInput(askQuestionsInputSchema, input);
@@ -94,7 +96,7 @@ const buildPausingToolPart = ({
proposeToolCallInputSchema,
input,
);
- const resolution = resolveEmailToolCallProposal(proposeToolCallInput);
+ const resolution = await resolveProposal(proposeToolCallInput);
if ('error' in resolution) {
return throwInvalidToolCall(resolution.error);
@@ -117,17 +119,19 @@ const buildPausingToolPart = ({
// A tool call is either one the member answers, which pauses the
// conversation, or one of the application's own tools, rendered by its front
// component with the input and output the application gives. The caller
-// resolves that tool, scoped to the sending application.
+// resolves that tool, and any proposed call, scoped to the sending application.
export const buildInboxMessageToolCallPart = async ({
toolCall,
toolCallId,
findApplicationTool,
+ resolveProposal,
}: {
toolCall: unknown;
toolCallId: string;
findApplicationTool: (
logicFunctionUniversalIdentifier: string,
) => Promise<FlatLogicFunction | undefined>;
+ resolveProposal: ResolveInboxProposal;
}): Promise<InboxMessageToolCallPart> => {
if (!isPlainObject(toolCall)) {
return throwInvalidToolCall('toolCall must be an object');
@@ -135,10 +139,11 @@ export const buildInboxMessageToolCallPart = async ({
if (!isNonEmptyString(toolCall.logicFunctionUniversalIdentifier)) {
return {
- part: buildPausingToolPart({
+ part: await buildPausingToolPart({
toolName: toolCall.toolName,
toolCallId,
input: toolCall.input,
+ resolveProposal,
}),
isAwaitingAnswer: true,
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util.ts
new file mode 100644
index 00000000000..a44659d382f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util.ts
@@ -0,0 +1,13 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
+
+export const findLastMessageText = (
+ parts: ExtendedUIMessagePart[],
+): string | null =>
+ parts
+ .flatMap((part) =>
+ part.type === 'text' && isNonEmptyString(part.text.trim())
+ ? [part.text]
+ : [],
+ )
+ .pop() ?? null;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
index a71ddc61c73..6669e8c43ce 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
@@ -162,11 +162,14 @@ export class AgentConversationWriterService {
agentId: string | null;
execution: RecordableAgentExecution;
scope?: AgentHistoryTransactionScope;
- }): Promise<{ isAwaitingAnswer: boolean }> {
+ }): Promise<{
+ isAwaitingAnswer: boolean;
+ replyParts: ExtendedUIMessagePart[];
+ }> {
const replyParts = mapAiStepsToUIMessageParts(execution.steps ?? []);
if (replyParts.length === 0) {
- return { isAwaitingAnswer: false };
+ return { isAwaitingAnswer: false, replyParts };
}
const awaitingParts = findAwaitingPausingToolParts(replyParts);
@@ -187,6 +190,6 @@ export class AgentConversationWriterService {
scope,
});
- return { isAwaitingAnswer };
+ return { isAwaitingAnswer, replyParts };
}
}
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
index b204c02541b..335887e39e0 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
@@ -120,6 +120,7 @@ type AgentWorkflowToSeed = {
stepKey: string;
stepName: string;
stepPrompt: string;
+ humanInputInstructions: string;
runKey: string;
initiator: Initiator;
runPrompt: string;
@@ -135,6 +136,8 @@ const AGENT_WORKFLOWS_TO_SEED: AgentWorkflowToSeed[] = [
stepKey: 'agentStep',
stepName: 'Qualify the lead',
stepPrompt: 'Qualify the inbound lead and draft the first reply.',
+ humanInputInstructions:
+ 'Ask me who should follow up when the lead could go to more than one owner.',
runKey: 'qualification',
initiator: 'TIM',
runPrompt:
@@ -150,6 +153,7 @@ const AGENT_WORKFLOWS_TO_SEED: AgentWorkflowToSeed[] = [
stepName: 'Draft the reminder',
stepPrompt:
'Draft a renewal reminder for the account and have it reviewed before it goes out.',
+ humanInputInstructions: 'Have every email reviewed before it goes out.',
runKey: 'renewalReminder',
initiator: 'PHIL',
runPrompt:
@@ -233,7 +237,10 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
type: WorkflowActionType.AI_AGENT,
valid: true,
settings: {
- input: { prompt: agentWorkflow.stepPrompt, canAskQuestions: true },
+ input: {
+ prompt: agentWorkflow.stepPrompt,
+ humanInputInstructions: agentWorkflow.humanInputInstructions,
+ },
outputSchema: {},
errorHandlingOptions: ERROR_HANDLING_OPTIONS,
},
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 78989aea42f..fc832de680d 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,5 +1,7 @@
import { Injectable, Logger } from '@nestjs/common';
+import { isNonEmptyString } from '@sniptt/guards';
+
import {
ASK_QUESTIONS_TOOL_NAME,
REQUEST_FORM_TOOL_NAME,
@@ -26,7 +28,7 @@ import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-e
import { 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 { WORKFLOW_AGENT_ASK_QUESTIONS_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-ask-questions-prompt.constant';
+import { WORKFLOW_AGENT_HUMAN_INPUT_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant';
import {
type RecordedConversation,
WorkflowAgentConversationWorkspaceService,
@@ -71,7 +73,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
);
}
- const { agentId, prompt, canAskQuestions } = step.settings.input;
+ const { agentId, prompt, humanInputInstructions } = step.settings.input;
const workspaceId = runInfo.workspaceId;
let agent: AgentEntity | null = null;
@@ -120,6 +122,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
? this.workflowAgentConversationService.recordContinuation({
workspaceId,
threadId: resumedThreadId,
+ title: step.name,
agentId: agent?.id ?? null,
executionResult,
})
@@ -143,7 +146,8 @@ export class AiAgentWorkflowAction implements WorkflowAction {
return null;
});
- const isAskingQuestionsAllowed = canAskQuestions === true;
+ const trimmedHumanInputInstructions = humanInputInstructions?.trim();
+ const canAskForHumanInput = isNonEmptyString(trimmedHumanInputInstructions);
const startedAtMs = Date.now();
@@ -158,10 +162,10 @@ export class AiAgentWorkflowAction implements WorkflowAction {
}),
}
: { messages: [{ role: 'user', content: resolvedPrompt }] }),
- baseSystemPrompt: isAskingQuestionsAllowed
- ? `${WORKFLOW_BASE_SYSTEM_PROMPT}\n\n${WORKFLOW_AGENT_ASK_QUESTIONS_PROMPT}`
+ baseSystemPrompt: canAskForHumanInput
+ ? `${WORKFLOW_BASE_SYSTEM_PROMPT}\n\n${WORKFLOW_AGENT_HUMAN_INPUT_PROMPT}\n\n${trimmedHumanInputInstructions}`
: WORKFLOW_BASE_SYSTEM_PROMPT,
- pausingTools: isAskingQuestionsAllowed
+ pausingTools: canAskForHumanInput
? {
[ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool({
isWorkspaceSetupThread: false,
@@ -169,7 +173,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
[REQUEST_FORM_TOOL_NAME]: createRequestFormTool(),
}
: {},
- canProposeToolCalls: isAskingQuestionsAllowed,
+ canProposeToolCalls: canAskForHumanInput,
actorContext: executionContext.isActingOnBehalfOfUser
? executionContext.initiator
: undefined,
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.ts
deleted file mode 100644
index 61716a5d1e6..00000000000
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-ask-questions-prompt.constant.ts
+++ /dev/null
@@ -1 +0,0 @@
-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. When you need typed values instead, such as a date, an amount or a record to pick, call request_form. Ask everything you need in one call, and do not ask about anything you can find or decide yourself. When an action needs a person's approval first, because it is hard to undo, because you are unsure it is right, or because your instructions ask for it, call propose_tool_call with the tool and arguments you would have used: the workflow pauses until someone approves it, possibly with edits, or rejects it with feedback, and you get the result. An email a person must review before it goes out is proposed the same way, as a send_email call they can edit, send, save as a draft or discard. Most actions need no approval, so do not propose what you can safely do yourself.`;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant.ts
new file mode 100644
index 00000000000..d7286b6e52d
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-human-input-prompt.constant.ts
@@ -0,0 +1 @@
+export const WORKFLOW_AGENT_HUMAN_INPUT_PROMPT = `You run inside a workflow, with nobody watching as you work. You can stop and ask the person who owns the workflow for input: the workflow pauses until they answer in their inbox, then you continue with their answer. Call ask_questions for a decision or a fact only a person can give, request_form for typed values such as a date, an amount or a record to pick, and propose_tool_call with the tool and arguments you would have used for an action they must approve first: they approve it, possibly with edits, or reject it with feedback, and you get the result. An email they must review is proposed as a send_email call they can edit, send, save as a draft or discard. Ask everything you need in one call, and never ask about what you can find or decide yourself. Stop for input only as the workflow's instructions below say:`;
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 15548a1ffab..61ca7724582 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,10 +1,11 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
import {
type ExtendedUIMessagePart,
REQUEST_FORM_TOOL_NAME,
type RequestFormToolInput,
} from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
@@ -14,6 +15,13 @@ import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-
import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
import { type RecordableAgentExecution } from 'src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
+import { findLastMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util';
+import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
export type RecordedConversation = {
threadId: string;
@@ -21,14 +29,20 @@ export type RecordedConversation = {
};
// One conversation per execution, so a loop iteration or retry never reads or continues another's messages.
-// It has no owner: it belongs to the run and is readable by whoever can read the run.
+// It belongs to the run, and is owned by the workflow's creator so a call waiting on input reaches their inbox.
@Injectable()
export class WorkflowAgentConversationWorkspaceService {
+ private readonly logger = new Logger(
+ WorkflowAgentConversationWorkspaceService.name,
+ );
+
constructor(
@InjectAgentHistoryRepository('agentChatThread')
private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
private readonly conversationWriterService: AgentConversationWriterService,
+ private readonly threadService: AgentChatThreadService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
+ private readonly workflowRunRecordShareService: WorkflowRunRecordShareService,
) {}
async recordExecution({
@@ -68,14 +82,14 @@ export class WorkflowAgentConversationWorkspaceService {
parts: [{ type: 'text', text: prompt }],
});
- const { isAwaitingAnswer } =
- await this.conversationWriterService.insertExecutionReply({
- workspaceId,
- threadId,
- turnId,
- agentId,
- execution: executionResult,
- });
+ const isAwaitingAnswer = await this.recordReply({
+ workspaceId,
+ threadId,
+ turnId,
+ title,
+ agentId,
+ executionResult,
+ });
return { threadId, isAwaitingAnswer };
}
@@ -120,17 +134,21 @@ export class WorkflowAgentConversationWorkspaceService {
} as ExtendedUIMessagePart,
],
});
+
+ await this.recordWaitingActivity({ workspaceId, threadId, text: title });
}
// The answer is already the last message, so only the agent's reply is added
async recordContinuation({
workspaceId,
threadId,
+ title,
agentId,
executionResult,
}: {
workspaceId: string;
threadId: string;
+ title: string;
agentId: string | null;
executionResult: RecordableAgentExecution;
}): Promise<RecordedConversation> {
@@ -140,7 +158,35 @@ export class WorkflowAgentConversationWorkspaceService {
agentId,
});
- const { isAwaitingAnswer } =
+ const isAwaitingAnswer = await this.recordReply({
+ workspaceId,
+ threadId,
+ turnId,
+ title,
+ agentId,
+ executionResult,
+ });
+
+ return { threadId, isAwaitingAnswer };
+ }
+
+ // One unanswerable call would keep the step waiting forever, so the step fails instead
+ private async recordReply({
+ workspaceId,
+ threadId,
+ turnId,
+ title,
+ agentId,
+ executionResult,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ turnId: string;
+ title: string;
+ agentId: string | null;
+ executionResult: RecordableAgentExecution;
+ }): Promise<boolean> {
+ const { isAwaitingAnswer, replyParts } =
await this.conversationWriterService.insertExecutionReply({
workspaceId,
threadId,
@@ -149,7 +195,31 @@ export class WorkflowAgentConversationWorkspaceService {
execution: executionResult,
});
- return { threadId, isAwaitingAnswer };
+ if (isAwaitingAnswer) {
+ await this.recordWaitingActivity({
+ workspaceId,
+ threadId,
+ text: findLastMessageText(replyParts) ?? title,
+ });
+ }
+
+ return isAwaitingAnswer;
+ }
+
+ // the waiting call is already saved and can be answered from the run, so a failure to
+ // surface it in the inbox must not fail the step
+ private async recordWaitingActivity(args: {
+ workspaceId: string;
+ threadId: string;
+ text: string;
+ }): Promise<void> {
+ await this.threadService
+ .recordThreadActivity(args)
+ .catch((error: unknown) =>
+ this.logger.warn(
+ `Could not record waiting activity on thread ${args.threadId}: ${error instanceof Error ? error.message : String(error)}`,
+ ),
+ );
}
private async openConversation({
@@ -165,11 +235,11 @@ export class WorkflowAgentConversationWorkspaceService {
title: string;
agentId: string | null;
}): Promise<{ threadId: string; turnId: string }> {
- const threadInsertResult = await this.threadRepository.insert(workspaceId, {
- title,
+ const threadId = await this.createRunThread({
+ workspaceId,
workflowRunId,
+ title,
});
- const threadId = threadInsertResult.identifiers[0].id as string;
const turnId = await this.conversationWriterService.insertTurn({
workspaceId,
@@ -186,4 +256,58 @@ export class WorkflowAgentConversationWorkspaceService {
return { threadId, turnId };
}
+
+ // a workflow without a member creator, such as one an application installs, or whose creator
+ // cannot use AI, keeps an ownerless conversation
+ private async createRunThread({
+ workspaceId,
+ workflowRunId,
+ title,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ title: string;
+ }): Promise<string> {
+ const { coreWorkflowId } =
+ await this.workflowRunWorkspaceService.getWorkflowRunOrFail({
+ workflowRunId,
+ workspaceId,
+ });
+ const creatorWorkspaceMemberId = isDefined(coreWorkflowId)
+ ? await this.workflowRunRecordShareService.findCreatorWorkspaceMemberId({
+ workspaceId,
+ coreWorkflowId,
+ })
+ : null;
+
+ const ownedThread = isDefined(creatorWorkspaceMemberId)
+ ? await this.threadService
+ .createThread({
+ workspaceId,
+ workspaceMemberId: creatorWorkspaceMemberId,
+ title,
+ workflowRunId,
+ })
+ .catch((error: unknown) => {
+ if (
+ error instanceof AiException &&
+ error.code === AiExceptionCode.THREAD_NOT_FOUND
+ ) {
+ return null;
+ }
+ throw error;
+ })
+ : null;
+
+ if (isDefined(ownedThread)) {
+ return ownedThread.id;
+ }
+
+ const threadInsertResult = await this.threadRepository.insert(workspaceId, {
+ title,
+ workflowRunId,
+ });
+
+ return threadInsertResult.identifiers[0].id as string;
+ }
}
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.ts
index edc6e25907b..d6f53d1a816 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,5 +1,5 @@
export type WorkflowAiAgentActionInput = {
agentId?: string;
prompt?: string;
- canAskQuestions?: boolean;
+ humanInputInstructions?: string;
};
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..8a420c7f309 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
@@ -1,12 +1,20 @@
import { Module } from '@nestjs/common';
+import { WorkflowRunRecordShareModule } from 'src/engine/core-modules/workflow/workflow-run-record-share.module';
+import { AgentChatThreadModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module';
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],
+ imports: [
+ AgentChatThreadModule,
+ AgentHistoryModule,
+ WorkflowRunModule,
+ WorkflowRunRecordShareModule,
+ WorkspaceCacheModule,
+ ],
providers: [WorkflowAgentConversationWorkspaceService],
exports: [WorkflowAgentConversationWorkspaceService],
})
diff --git a/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts
index 289ebe0d797..c8d7c5f2678 100644
--- a/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts
@@ -22,6 +22,7 @@ import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system
import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
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 { OPPORTUNITY_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/opportunity-data-seeds.constant';
import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
@@ -154,6 +155,22 @@ describe('Sending an inbox message as an application', () => {
});
});
+ it('refuses to propose a record call the application could not run itself', async () => {
+ const response = await sendInboxMessage(applicationToken, {
+ threadKey: `inbox-thread-${uuidv4()}`,
+ toolCall: {
+ toolName: 'propose_tool_call',
+ input: {
+ toolName: 'update_one_opportunity',
+ arguments: { id: OPPORTUNITY_DATA_SEED_IDS.ID_1, stage: 'WON' },
+ summary: 'Mark the deal as won',
+ },
+ },
+ });
+
+ expect(JSON.stringify(response.body.errors)).toContain('not available');
+ });
+
it('rejects a member session', async () => {
const response = await sendInboxMessage(APPLE_JANE_ADMIN_ACCESS_TOKEN);
@@ -363,3 +380,87 @@ describe('Sending an inbox message as an application', () => {
);
});
});
+
+describe('Proposing a record call as an application', () => {
+ let application: ApplicationWithResources;
+ let applicationToken: string;
+ let threadId: string | undefined;
+
+ beforeAll(async () => {
+ application = await setupApplicationWithResources({
+ name: 'Inbox Record Application',
+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
+ canReadAndUpdateAllObjectRecords: true,
+ });
+ jest.useRealTimers();
+
+ applicationToken = (
+ await generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ })
+ ).applicationAccessToken.token;
+ });
+
+ afterAll(async () => {
+ if (threadId !== undefined) {
+ await destroyAgentChatThread({ threadId });
+ }
+
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ });
+
+ it('proposes an update the application could run, with the values it changes', async () => {
+ const response = await makeMetadataApiRequest(
+ {
+ query: SEND_INBOX_MESSAGE,
+ variables: {
+ input: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ threadKey: `inbox-thread-${uuidv4()}`,
+ idempotencyKey: 'record-proposal',
+ title: 'A deal looks won',
+ text: 'The signed quote came in.',
+ toolCall: {
+ toolName: 'propose_tool_call',
+ input: {
+ toolName: 'update_one_opportunity',
+ arguments: { id: OPPORTUNITY_DATA_SEED_IDS.ID_1, stage: 'WON' },
+ summary: 'Mark the deal as won',
+ },
+ },
+ },
+ },
+ },
+ applicationToken,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ threadId = response.body.data.sendInboxMessage.threadId;
+
+ const [part] = await global.testDataSource.query(
+ `SELECT part."toolOutput" FROM "${schema}"."agentMessagePart" part
+ JOIN "${schema}"."agentMessage" message ON message.id = part."messageId"
+ WHERE message."threadId" = $1 AND part."toolName" = 'propose_tool_call'`,
+ [threadId],
+ );
+
+ const [opportunity] = await global.testDataSource.query(
+ `SELECT stage FROM "${schema}"."opportunity" WHERE id = $1`,
+ [OPPORTUNITY_DATA_SEED_IDS.ID_1],
+ );
+
+ expect(part.toolOutput.result).toMatchObject({
+ status: 'pending',
+ proposal: {
+ toolName: 'update_one_opportunity',
+ template: 'recordUpdate',
+ objectNameSingular: 'opportunity',
+ recordId: OPPORTUNITY_DATA_SEED_IDS.ID_1,
+ currentValues: { stage: opportunity.stage },
+ },
+ });
+ });
+});
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 2bcb24a6f99..0d04339897b 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
@@ -1,3 +1,4 @@
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
import { CronTriggerDeduplicationService } from 'src/engine/core-modules/cron/services/cron-trigger-deduplication.service';
import { randomUUID } from 'node:crypto';
import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
@@ -29,6 +30,7 @@ import { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/a
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 AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.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';
@@ -1076,7 +1078,10 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
nextStepIds,
settings: {
...settings,
- input: { prompt: 'Draft the quote', canAskQuestions: true },
+ input: {
+ prompt: 'Draft the quote',
+ humanInputInstructions: 'Ask before choosing a plan.',
+ },
},
}) as WorkflowAction;
@@ -1233,6 +1238,96 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
expect(threads).toEqual([]);
});
+ it("routes the waiting conversation to the workflow creator's inbox", async () => {
+ mockAgent();
+ const [creator] = await global.testDataSource.query(
+ `SELECT membership.id AS "userWorkspaceId", member.id AS "workspaceMemberId"
+ FROM core."userWorkspace" membership
+ JOIN "${schema}"."workspaceMember" member ON member."userId" = membership."userId"
+ WHERE membership."workspaceId" = $1 AND membership."deletedAt" IS NULL AND member.id = $2`,
+ [workspaceId, WORKSPACE_MEMBER_DATA_SEED_IDS.JONY],
+ );
+ const agent = agentStep([]);
+ const fixture = await createFixture({ steps: [agent] });
+
+ await global.testDataSource.query(
+ `UPDATE core.workflow SET "createdByUserWorkspaceId" = $1 WHERE id = $2`,
+ [creator.userWorkspaceId, fixture.coreWorkflowId],
+ );
+
+ const runId = await runFixture(fixture);
+ const run = await waitForStep(runId, agent.id, 'PENDING');
+ const [conversation] = await global.testDataSource.query(
+ `SELECT "workspaceMemberId", "workflowRunId", "lastActivityAt", "lastMessageText" FROM "${schema}"."agentChatThread" WHERE id = $1`,
+ [run.state.stepInfos[agent.id].threadId],
+ );
+
+ expect(conversation).toMatchObject({
+ workspaceMemberId: creator.workspaceMemberId,
+ workflowRunId: runId,
+ lastMessageText: agent.name,
+ });
+ expect(conversation.lastActivityAt).not.toBeNull();
+
+ const readByAnotherMember = await request(`http://localhost:${APP_PORT}`)
+ .post('/metadata')
+ .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
+ .send({
+ query: `query ReadRunConversation($threadId: UUID!) { chatMessages(threadId: $threadId) { role } }`,
+ variables: { threadId: run.state.stepInfos[agent.id].threadId },
+ });
+
+ expect(readByAnotherMember.body.errors).toBeUndefined();
+ expect(readByAnotherMember.body.data.chatMessages.length).toBeGreaterThan(
+ 0,
+ );
+ });
+
+ it('keeps the conversation of a workflow without a member creator off every inbox', async () => {
+ mockAgent();
+ const agent = agentStep([]);
+ const fixture = await createFixture({ steps: [agent] });
+
+ await global.testDataSource.query(
+ `UPDATE core.workflow SET "createdByUserWorkspaceId" = NULL WHERE id = $1`,
+ [fixture.coreWorkflowId],
+ );
+
+ const runId = await runFixture(fixture);
+ const run = await waitForStep(runId, agent.id, 'PENDING');
+ const threadId: string = run.state.stepInfos[agent.id].threadId;
+ const [conversation] = await global.testDataSource.query(
+ `SELECT "workspaceMemberId" FROM "${schema}"."agentChatThread" WHERE id = $1`,
+ [threadId],
+ );
+
+ expect(conversation.workspaceMemberId).toBeNull();
+ });
+
+ it('still waits on the question when its conversation cannot be surfaced in the inbox', async () => {
+ mockAgent();
+ const recordThreadActivity = jest
+ .spyOn(
+ getAppProviderByClassName<AgentChatThreadService>(
+ 'AgentChatThreadService',
+ ),
+ 'recordThreadActivity',
+ )
+ .mockRejectedValueOnce(new Error('Database unavailable'));
+
+ try {
+ const { runId, threadId } = await startAskingRun();
+
+ expect(await getToolCalls(threadId)).toMatchObject({
+ isWaiting: true,
+ });
+ expect((await answer({ threadId })).body.errors).toBeUndefined();
+ await waitForRun(runId, 'COMPLETED');
+ } finally {
+ recordThreadActivity.mockRestore();
+ }
+ });
+
it('pauses the run on the question and resumes the same conversation with the answer', async () => {
const executeAgent = mockAgent();
const { runId, agent, finalStep, threadId } = await startAskingRun();
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/setup-application-with-resources.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/setup-application-with-resources.util.ts
index 1b3a3741d7c..a786f95e5fb 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/utils/setup-application-with-resources.util.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/setup-application-with-resources.util.ts
@@ -62,9 +62,11 @@ const findIdByUniversalIdentifier = async ({
export const setupApplicationWithResources = async ({
name,
permissionFlagUniversalIdentifiers = DEFAULT_PERMISSION_FLAG_UNIVERSAL_IDENTIFIERS,
+ canReadAndUpdateAllObjectRecords = false,
}: {
name: string;
permissionFlagUniversalIdentifiers?: string[];
+ canReadAndUpdateAllObjectRecords?: boolean;
}): Promise<ApplicationWithResources> => {
const applicationUniversalIdentifier = uuidv4();
const roleUniversalIdentifier = uuidv4();
@@ -117,6 +119,8 @@ export const setupApplicationWithResources = async ({
label: `${name} role`,
description: 'Reaches application resources',
canUpdateAllSettings: false,
+ canReadAllObjectRecords: canReadAndUpdateAllObjectRecords,
+ canUpdateAllObjectRecords: canReadAndUpdateAllObjectRecords,
permissionFlagUniversalIdentifiers,
},
],
diff --git a/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts b/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts
index c1c0eb799bb..da4cc95840d 100644
--- a/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts
+++ b/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts
@@ -14,7 +14,7 @@ export type SendInboxMessageToolCall =
logicFunctionUniversalIdentifier?: never;
}
| {
- // the approved call runs with the member's permissions
+ // a call the app could run itself, which runs with the member's permissions once approved
toolName: 'propose_tool_call';
input: ProposeToolCallToolInput;
logicFunctionUniversalIdentifier?: never;
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.ts
index ef2bc2269a2..cd544823bd1 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,7 +6,7 @@ export const workflowAiAgentActionSettingsSchema =
input: z.object({
agentId: z.string().optional(),
prompt: z.string().optional(),
- // Off by default: asking pauses the run, which existing workflows were not built to expect.
- canAskQuestions: z.boolean().optional(),
+ // Empty by default: stopping for a person pauses the run, which existing workflows were not built to expect.
+ humanInputInstructions: z.string().optional(),
}),
});