The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(ai): human input bugs found reviewing the approval feature (#27194)
Félix Malfait1feb3665eb20
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatToolCallApprovalStatusRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatToolCallApprovalStatusRenderer.tsxindex 36f48490afc..6642482690f 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatToolCallApprovalStatusRenderer.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatToolCallApprovalStatusRenderer.tsx@@ -37,6 +37,7 @@ export const AiChatToolCallApprovalStatusRenderer = ({pending: isDefined(result)? t`Waiting for your approval`: t`Preparing an action to approve...`,+ running: t`Running...`,approved: t`Approved`,rejected: t`Rejected`,failed: t`Approved but it failed`,@@ -51,6 +52,7 @@ export const AiChatToolCallApprovalStatusRenderer = ({const detailByStatus: Record<ProposeToolCallToolStatus, string | undefined> ={pending: summary,+ running: summary,approved: summary,rejected: result?.feedback,failed: result?.error,@@ -63,7 +65,10 @@ export const AiChatToolCallApprovalStatusRenderer = ({<AiChatAskStatusRowIcon={result?.proposal.template === 'email' ? IconMail : IconTool}message={message}- isShimmering={isStreaming && status === 'pending' && !hasFailedToPropose}+ isShimmering={+ ((isStreaming && status === 'pending') || status === 'running') &&+ !hasFailedToPropose+ }>{isNonEmptyString(detail) && (<StyledAiChatAskStatusDetail>{detail}</StyledAiChatAskStatusDetail>diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatToolCallApprovalCurrentValue.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatToolCallApprovalCurrentValue.tsxindex 538c6924cbc..a37f832984b 100644--- a/packages/twenty-front/src/modules/ai/components/internal/AiChatToolCallApprovalCurrentValue.tsx+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatToolCallApprovalCurrentValue.tsx@@ -1,5 +1,6 @@import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';+import { isDefined } from 'twenty-shared/utils';import { themeCssVariables } from 'twenty-ui/theme';import { FieldContextProvider } from '@/object-record/record-field/ui/components/FieldContextProvider';@@ -9,6 +10,8 @@ import { type FieldDefinition } from '@/object-record/record-field/ui/types/Fielimport { type FieldMetadata } from '@/object-record/record-field/ui/types/FieldMetadata';import { isFieldValueEmpty } from '@/object-record/record-field/ui/utils/isFieldValueEmpty';import { useRecordFieldValue } from '@/object-record/record-store/hooks/useRecordFieldValue';+import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';+import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';const StyledCurrentValue = styled.div`align-items: center;@@ -35,8 +38,14 @@ export const AiChatToolCallApprovalCurrentValue = ({}: AiChatToolCallApprovalCurrentValueProps) => {const { t } = useLingui();const { fieldName } = fieldDefinition.metadata;+ const recordStore = useAtomFamilyStateValue(recordStoreFamilyState, recordId);const fieldValue = useRecordFieldValue(recordId, fieldName, fieldDefinition);+ // the card loads the record, and a value read before then would show as empty+ if (!isDefined(recordStore)) {+ return null;+ }+return (<StyledCurrentValue>{t`Currently:`}diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.tsindex 4e65966eea4..7d561348ee3 100644--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts@@ -79,8 +79,8 @@ export const SETTINGS_ADMIN_FEATURE_FLAG_METADATA: Partial<description: msg`Let admins add conditions a record must meet to be saved, checked on every write.`,},[FeatureFlagKey.IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED]: {- label: msg`Workflow chat messages`,- description: msg`Add a workflow step that posts a message in a member's AI chat.`,+ label: msg`Workflow inbox messages`,+ description: msg`Add a workflow step that sends a message, and optionally an action to approve, to a member's inbox.`,},[FeatureFlagKey.IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED]: {label: msg`Skip unchanged calendar records`,diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/SendChatMessageAction.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/SendChatMessageAction.tsindex b474938f9e5..efe98a0774c 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/SendChatMessageAction.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/SendChatMessageAction.ts@@ -5,7 +5,7 @@ export const SEND_CHAT_MESSAGE_ACTION: {type: Extract<WorkflowActionType, 'SEND_CHAT_MESSAGE'>;icon: string;} = {- defaultLabel: 'Send Chat Message',+ defaultLabel: 'Send to Inbox',type: 'SEND_CHAT_MESSAGE',icon: 'IconMessage',};diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowEditActionSendChatMessage.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowEditActionSendChatMessage.tsxindex c515164755e..57e2b8bc09d 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowEditActionSendChatMessage.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowEditActionSendChatMessage.tsx@@ -1,17 +1,15 @@import { useGetToolIndex } from '@/ai/hooks/useGetToolIndex';-import { FormRawJsonFieldInput } from '@/object-record/record-field/ui/form-types/components/FormRawJsonFieldInput';import { FormSingleRecordPicker } from '@/object-record/record-field/ui/form-types/components/FormSingleRecordPicker';import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';import { Select } from '@/ui/input/components/Select';import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';import { type WorkflowSendChatMessageAction } from '@/workflow/types/Workflow';-import { parseAndValidateVariableFriendlyStringifiedJson } from '@/workflow/utils/parseAndValidateVariableFriendlyStringifiedJson';import { WorkflowStepBody } from '@/workflow/workflow-steps/components/WorkflowStepBody';import { WorkflowStepFooter } from '@/workflow/workflow-steps/components/WorkflowStepFooter';+import { WorkflowSendChatMessageToolArguments } from '@/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowSendChatMessageToolArguments';import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';import { t } from '@lingui/core/macro';import { useEffect, useMemo, useState } from 'react';-import { isNonEmptyString } from '@sniptt/guards';import { CoreObjectNameSingular } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { useDebouncedCallback } from 'use-debounce';@@ -41,9 +39,6 @@ export const WorkflowEditActionSendChatMessage = ({const [formData, setFormData] = useState<SendChatMessageFormData>(action.settings.input,);- const [toolArgumentsError, setToolArgumentsError] = useState<- string | undefined- >(undefined);const saveAction = useDebouncedCallback((nextFormData: SendChatMessageFormData) => {@@ -85,34 +80,18 @@ export const WorkflowEditActionSendChatMessage = ({};const handleToolNameChange = (toolName: string) => {- setToolArgumentsError(undefined);// another tool takes other argumentshandleToolCallChange(toolName === '' ? null : { toolName, arguments: {} });};- // variables sit inside JSON strings, so arguments are saved only once they parse- const handleToolArgumentsChange = (value: string | null) => {- const toolName = formData.toolCall?.toolName;-- if (!isDefined(toolName)) {- return;- }-- const parsedArguments = parseAndValidateVariableFriendlyStringifiedJson(- isNonEmptyString(value) ? value : '{}',- );-- if (!parsedArguments.isValid) {- setToolArgumentsError(t`Arguments must be a valid JSON object.`);-+ const handleToolArgumentsChange = (+ toolArguments: SendChatMessageToolCall['arguments'],+ ) => {+ if (!isDefined(formData.toolCall)) {return;}- setToolArgumentsError(undefined);- handleToolCallChange({- toolName,- arguments: parsedArguments.data as SendChatMessageToolCall['arguments'],- });+ handleToolCallChange({ ...formData.toolCall, arguments: toolArguments });};const storedToolName = formData.toolCall?.toolName;@@ -123,16 +102,19 @@ export const WorkflowEditActionSendChatMessage = ({}));// a saved tool the editor cannot see still runs, so it stays shown rather than reading as none+ const noneOption = { label: t`None, only send the message`, value: '' };+return isDefined(storedToolName) &&!indexedToolOptions.some((option) => option.value === storedToolName)? [+ noneOption,...indexedToolOptions,{label: t`${storedToolName} (not available to you)`,value: storedToolName,},]- : indexedToolOptions;+ : [noneOption, ...indexedToolOptions];}, [toolIndex, storedToolName]);return (@@ -172,7 +154,6 @@ export const WorkflowEditActionSendChatMessage = ({fullWidthdisabled={actionOptions.readonly}value={formData.toolCall?.toolName ?? ''}- emptyOption={{ label: t`None, only send the message`, value: '' }}options={toolOptions}onChange={handleToolNameChange}withSearchInput@@ -180,15 +161,12 @@ export const WorkflowEditActionSendChatMessage = ({dropdownWidth={GenericDropdownContentWidth.ExtraLarge}/>{isDefined(formData.toolCall) && (- <FormRawJsonFieldInput+ <WorkflowSendChatMessageToolArgumentskey={formData.toolCall.toolName}- label={t`Action arguments`}- placeholder={t`Enter the arguments as a JSON object`}- defaultValue={JSON.stringify(formData.toolCall.arguments, null, 2)}- onChange={handleToolArgumentsChange}- error={toolArgumentsError}+ toolName={formData.toolCall.toolName}+ toolArguments={formData.toolCall.arguments}readonly={actionOptions.readonly}- VariablePicker={WorkflowVariablePicker}+ onChange={handleToolArgumentsChange}/>)}</WorkflowStepBody>diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowSendChatMessageToolArguments.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowSendChatMessageToolArguments.tsxnew file mode 100644index 00000000000..f2b7989081f--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowSendChatMessageToolArguments.tsx@@ -0,0 +1,215 @@+import { useQuery } from '@apollo/client/react';+import { FormRawJsonFieldInput } from '@/object-record/record-field/ui/form-types/components/FormRawJsonFieldInput';+import { parseAndValidateVariableFriendlyStringifiedJson } from '@/workflow/utils/parseAndValidateVariableFriendlyStringifiedJson';+import { WorkflowEditActionCodeFieldLeaf } from '@/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowEditActionCodeFieldLeaf';+import { type ToolArgumentField } from '@/workflow/workflow-steps/workflow-actions/send-chat-message-action/types/ToolArgumentField';+import { buildToolArgumentFields } from '@/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/buildToolArgumentFields';+import { isEmptyToolArgument } from '@/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/isEmptyToolArgument';+import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';+import { styled } from '@linaria/react';+import { t } from '@lingui/core/macro';+import { isNonEmptyString } from '@sniptt/guards';+import { useMemo, useState } from 'react';+import { isDefined } from 'twenty-shared/utils';+import { isStandaloneVariableString } from 'twenty-shared/workflow';+import { LightButton } from 'twenty-ui/components';+import { themeCssVariables } from 'twenty-ui/theme';+import { GetToolInputSchemaDocument } from '~/generated-metadata/graphql';++const StyledArguments = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[4]};+`;++const StyledArgument = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[1]};+`;++const StyledHint = styled.span`+ color: ${themeCssVariables.font.color.light};+ font-size: ${themeCssVariables.font.size.sm};+`;++const StyledError = styled.span`+ color: ${themeCssVariables.font.color.danger};+ font-size: ${themeCssVariables.font.size.sm};+`;++type ToolArguments = Record<string, unknown>;++type WorkflowSendChatMessageToolArgumentsProps = {+ toolName: string;+ toolArguments: ToolArguments;+ readonly?: boolean;+ onChange: (toolArguments: ToolArguments) => void;+};++export const WorkflowSendChatMessageToolArguments = ({+ toolName,+ toolArguments,+ readonly,+ onChange,+}: WorkflowSendChatMessageToolArgumentsProps) => {+ const { data, loading } = useQuery(GetToolInputSchemaDocument, {+ variables: { toolName },+ });+ const fields = useMemo(+ () =>+ buildToolArgumentFields({+ jsonSchema: data?.getToolInputSchema,+ savedArgumentNames: Object.keys(toolArguments),+ }),+ [data, toolArguments],+ );+ const [isShowingOptionalArguments, setIsShowingOptionalArguments] =+ useState(false);+ const [jsonErrors, setJsonErrors] = useState<Record<string, string>>({});+ // an optional argument stays shown once it has a value, even while it is cleared to be edited+ const [revealedNames, setRevealedNames] = useState(+ () => new Set(Object.keys(toolArguments)),+ );++ if (loading) {+ return null;+ }++ // an empty value is left out, so an update never clears a field nobody filled in+ const handleArgumentChange = (name: string, value: unknown) => {+ const { [name]: _previousValue, ...otherArguments } = toolArguments;++ if (!isEmptyToolArgument(value) && !revealedNames.has(name)) {+ setRevealedNames(new Set([...revealedNames, name]));+ }++ onChange(+ isEmptyToolArgument(value)+ ? otherArguments+ : { ...otherArguments, [name]: value },+ );+ };++ const setJsonError = (key: string, error: string | undefined) =>+ setJsonErrors(({ [key]: _previousError, ...otherErrors }) =>+ isDefined(error) ? { ...otherErrors, [key]: error } : otherErrors,+ );++ if (!isDefined(fields)) {+ return (+ <FormRawJsonFieldInput+ label={t`Action arguments`}+ placeholder={t`Enter the arguments as a JSON object`}+ defaultValue={JSON.stringify(toolArguments, null, 2)}+ onChange={(value) => {+ const parsedArguments =+ parseAndValidateVariableFriendlyStringifiedJson(+ isNonEmptyString(value) ? value : '{}',+ );++ if (!parsedArguments.isValid) {+ setJsonError('', t`Arguments must be a valid JSON object.`);++ return;+ }++ setJsonError('', undefined);+ onChange(parsedArguments.data);+ }}+ error={jsonErrors['']}+ readonly={readonly}+ VariablePicker={WorkflowVariablePicker}+ />+ );+ }++ const handleJsonArgumentChange = (name: string, value: string | null) => {+ if (!isNonEmptyString(value) || isStandaloneVariableString(value)) {+ setJsonError(name, undefined);+ handleArgumentChange(name, value);++ return;+ }++ try {+ handleArgumentChange(name, JSON.parse(value));+ setJsonError(name, undefined);+ } catch {+ setJsonError(name, t`Enter valid JSON.`);+ }+ };++ const isShown = (field: ToolArgumentField) =>+ field.isRequired ||+ !field.isListed ||+ isShowingOptionalArguments ||+ revealedNames.has(field.name);+ const hiddenOptionalCount = fields.filter((field) => !isShown(field)).length;++ return (+ <StyledArguments>+ {fields.filter(isShown).map((field) => {+ const value = toolArguments[field.name];+ const label = field.isRequired ? `${field.label} *` : field.label;+ const isMissing = field.isRequired && isEmptyToolArgument(value);++ return (+ <StyledArgument key={field.name}>+ {isDefined(field.schemaProperty) ? (+ <WorkflowEditActionCodeFieldLeaf+ label={label}+ inputValue={value}+ schemaProperty={field.schemaProperty}+ readonly={readonly}+ onChange={(nextValue) =>+ handleArgumentChange(field.name, nextValue)+ }+ VariablePicker={WorkflowVariablePicker}+ />+ ) : (+ <FormRawJsonFieldInput+ label={label}+ placeholder={t`Enter a JSON value`}+ defaultValue={+ isDefined(value) ? JSON.stringify(value, null, 2) : undefined+ }+ onChange={(nextValue) =>+ handleJsonArgumentChange(field.name, nextValue)+ }+ error={jsonErrors[field.name]}+ readonly={readonly}+ VariablePicker={WorkflowVariablePicker}+ />+ )}+ {isDefined(field.description) && (+ <StyledHint>{field.description}</StyledHint>+ )}+ {!field.isListed && (+ <StyledHint>+ {t`This action no longer takes this argument. Clear it to remove it.`}+ </StyledHint>+ )}+ {isMissing && !readonly && (+ <StyledError>{t`Required to run the action`}</StyledError>+ )}+ </StyledArgument>+ );+ })}+ {!readonly && (hiddenOptionalCount > 0 || isShowingOptionalArguments) && (+ <LightButton+ emphasis="subtle"+ onClick={() =>+ setIsShowingOptionalArguments(+ (isShowingOptional) => !isShowingOptional,+ )+ }+ >+ {isShowingOptionalArguments+ ? t`Hide empty optional arguments`+ : t`Show ${hiddenOptionalCount} optional arguments`}+ </LightButton>+ )}+ </StyledArguments>+ );+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/types/ToolArgumentField.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/types/ToolArgumentField.tsnew file mode 100644index 00000000000..a8c7b460eae--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/types/ToolArgumentField.ts@@ -0,0 +1,12 @@+import { type InputSchemaProperty } from 'twenty-shared/workflow';++export type ToolArgumentField = {+ name: string;+ label: string;+ description?: string;+ isRequired: boolean;+ // false for a saved argument the tool no longer lists, so it can still be read and removed+ isListed: boolean;+ // undefined when no simple input fits, such as an object or a union, so it is edited as JSON+ schemaProperty?: InputSchemaProperty;+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/__tests__/buildToolArgumentFields.test.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/__tests__/buildToolArgumentFields.test.tsnew file mode 100644index 00000000000..ee5963baa0f--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/__tests__/buildToolArgumentFields.test.ts@@ -0,0 +1,108 @@+import { buildToolArgumentFields } from '@/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/buildToolArgumentFields';++describe('buildToolArgumentFields', () => {+ it('lists required arguments first, with their description', () => {+ const fields = buildToolArgumentFields({+ jsonSchema: {+ type: 'object',+ properties: {+ location: { type: 'string', description: 'Where it happens' },+ startsAt: { type: 'string', description: 'ISO 8601 start' },+ isFullDay: { type: 'boolean' },+ },+ required: ['startsAt'],+ },+ savedArgumentNames: [],+ });++ expect(fields).toEqual([+ {+ name: 'startsAt',+ label: 'Starts at',+ description: 'ISO 8601 start',+ isRequired: true,+ isListed: true,+ schemaProperty: { type: 'string' },+ },+ {+ name: 'location',+ label: 'Location',+ description: 'Where it happens',+ isRequired: false,+ isListed: true,+ schemaProperty: { type: 'string' },+ },+ {+ name: 'isFullDay',+ label: 'Is full day',+ description: undefined,+ isRequired: false,+ isListed: true,+ schemaProperty: { type: 'boolean' },+ },+ ]);+ });++ it('edits objects and unions as JSON', () => {+ const fields = buildToolArgumentFields({+ jsonSchema: {+ type: 'object',+ properties: {+ address: { $ref: '#/$defs/AddressValue' },+ position: { anyOf: [{ type: 'number' }, { type: 'string' }] },+ workPolicy: {+ type: 'array',+ items: { type: 'string', enum: ['ON_SITE', 'REMOTE_WORK'] },+ },+ },+ },+ savedArgumentNames: [],+ });++ expect(+ fields?.map(({ name, schemaProperty }) => ({ name, schemaProperty })),+ ).toEqual([+ { name: 'address', schemaProperty: undefined },+ { name: 'position', schemaProperty: undefined },+ {+ name: 'workPolicy',+ schemaProperty: {+ type: 'array',+ items: { type: 'string', enum: ['ON_SITE', 'REMOTE_WORK'] },+ },+ },+ ]);+ });++ it('keeps arguments the schema does not list, so they can be filled or removed', () => {+ const fields = buildToolArgumentFields({+ jsonSchema: {+ type: 'object',+ properties: { title: { type: 'string' } },+ required: ['title', 'calendarId'],+ },+ savedArgumentNames: ['title', 'legacyNote'],+ });++ expect(+ fields?.map(({ name, isRequired, isListed }) => ({+ name,+ isRequired,+ isListed,+ })),+ ).toEqual([+ { name: 'title', isRequired: true, isListed: true },+ { name: 'calendarId', isRequired: true, isListed: true },+ { name: 'legacyNote', isRequired: false, isListed: false },+ ]);+ });++ it.each([null, {}, { type: 'object', properties: {} }])(+ 'falls back to JSON without listed arguments (%j)',+ (jsonSchema) => {+ expect(+ buildToolArgumentFields({ jsonSchema, savedArgumentNames: [] }),+ ).toBeNull();+ },+ );+});diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/buildToolArgumentFields.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/buildToolArgumentFields.tsnew file mode 100644index 00000000000..9818c8ab8b6--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/buildToolArgumentFields.ts@@ -0,0 +1,103 @@+import { isNonEmptyString, isString } from '@sniptt/guards';+import {+ type InputJsonSchema,+ jsonSchemaToInputSchema,+} from 'twenty-shared/logic-function';+import { capitalize, isPlainObject } from 'twenty-shared/utils';++import { type ToolArgumentField } from '@/workflow/workflow-steps/workflow-actions/send-chat-message-action/types/ToolArgumentField';++const SIMPLE_TYPES = new Set(['string', 'number', 'integer', 'boolean']);++const isSimpleInputJsonSchema = (+ propertySchema: Record<string, unknown>,+): propertySchema is InputJsonSchema =>+ SIMPLE_TYPES.has(String(propertySchema.type)) ||+ (propertySchema.type === 'array' &&+ isPlainObject(propertySchema.items) &&+ propertySchema.items.type === 'string');++const toLabel = (name: string) =>+ capitalize(name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase());++const buildJsonField = ({+ name,+ isRequired,+ isListed,+}: {+ name: string;+ isRequired: boolean;+ isListed: boolean;+}): ToolArgumentField => ({+ name,+ label: toLabel(name),+ isRequired,+ isListed,+});++// null when the schema lists no arguments, so the arguments are edited as JSON+export const buildToolArgumentFields = ({+ jsonSchema,+ savedArgumentNames,+}: {+ jsonSchema: unknown;+ savedArgumentNames: string[];+}): ToolArgumentField[] | null => {+ if (!isPlainObject(jsonSchema) || !isPlainObject(jsonSchema.properties)) {+ return null;+ }++ const { properties } = jsonSchema;+ const requiredNames = new Set(+ Array.isArray(jsonSchema.required)+ ? jsonSchema.required.filter(isString)+ : [],+ );++ const listedFields = Object.entries(properties).flatMap(+ ([name, propertySchema]): ToolArgumentField[] =>+ isPlainObject(propertySchema)+ ? [+ {+ name,+ label: isNonEmptyString(propertySchema.title)+ ? propertySchema.title+ : toLabel(name),+ description: isNonEmptyString(propertySchema.description)+ ? propertySchema.description+ : undefined,+ isRequired: requiredNames.has(name),+ isListed: true,+ schemaProperty: isSimpleInputJsonSchema(propertySchema)+ ? jsonSchemaToInputSchema(propertySchema)[0]+ : undefined,+ },+ ]+ : [],+ );+ const unlistedRequiredFields = [...requiredNames]+ .filter((name) => !Object.hasOwn(properties, name))+ .map((name) => buildJsonField({ name, isRequired: true, isListed: true }));+ const unlistedSavedFields = savedArgumentNames+ .filter(+ (name) => !Object.hasOwn(properties, name) && !requiredNames.has(name),+ )+ .map((name) =>+ buildJsonField({ name, isRequired: false, isListed: false }),+ );++ const fields = [+ ...listedFields,+ ...unlistedRequiredFields,+ ...unlistedSavedFields,+ ];++ if (fields.length === 0) {+ return null;+ }++ return [+ ...fields.filter((field) => field.isRequired),+ ...fields.filter((field) => !field.isRequired),+ ];+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/isEmptyToolArgument.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/isEmptyToolArgument.tsnew file mode 100644index 00000000000..f4ff3a963f4--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/utils/isEmptyToolArgument.ts@@ -0,0 +1,6 @@+import { isString } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++// an empty list stays a value, since clearing a list is how an update empties a field+export const isEmptyToolArgument = (value: unknown): boolean =>+ !isDefined(value) || (isString(value) && value.trim() === '');diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/computeStepOutputSchema.test.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/computeStepOutputSchema.test.tsindex 2b4067c715a..8ba65751a93 100644--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/computeStepOutputSchema.test.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/computeStepOutputSchema.test.ts@@ -58,9 +58,8 @@ describe('computeStepOutputSchema', () => {expect(Object.keys(result ?? {})).toEqual(['threadId',- 'isApproved',- 'approvedToolName',- 'status',+ 'outcome',+ 'toolName','feedback','error','arguments',diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.tsindex 12e87a4a570..d64aa03eea7 100644--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts@@ -234,23 +234,17 @@ export const computeStepOutputSchema = ({return {...threadIdOutputSchema,- isApproved: {- isLeaf: true,- type: FieldMetadataType.BOOLEAN,- label: 'Approved',- value: true,- },- approvedToolName: {+ outcome: {isLeaf: true,type: FieldMetadataType.TEXT,- label: 'Approved action',- value: '',+ label: 'Outcome',+ value: 'executed',},- status: {+ toolName: {isLeaf: true,type: FieldMetadataType.TEXT,- label: 'Status',- value: 'approved',+ label: 'Action',+ value: '',},feedback: {isLeaf: true,@@ -267,13 +261,13 @@ export const computeStepOutputSchema = ({arguments: {isLeaf: true,type: FieldMetadataType.RAW_JSON,- label: 'Approved arguments',+ label: 'Arguments',value: null,},output: {isLeaf: true,type: FieldMetadataType.RAW_JSON,- label: 'Action result',+ label: 'Output',value: null,},};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-tool-call.pausing-tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-tool-call.pausing-tool.tsindex fadba6fe672..bff3d64d2d6 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-tool-call.pausing-tool.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-tool-call.pausing-tool.ts@@ -250,75 +250,115 @@ export const PROPOSE_TOOL_CALL_PAUSING_TOOL = definePausingTool<toolName: approvedToolName,arguments: buildApprovedArguments(proposal, output.arguments),};- const { currentValues, objectNameSingular, recordId } = approvedProposal;- if (- isDefined(currentValues) &&- isDefined(objectNameSingular) &&- isDefined(recordId) &&- Object.keys(currentValues).length > 0- ) {- const latestRecord = await readRecordFieldValues({- executeTool: context.executeTool,- objectNameSingular,- recordId,- fieldNames: Object.keys(currentValues),- });-- // an update whose record cannot be read again cannot be shown to be safe, so it does not run- if (!latestRecord.isFound) {- return buildApprovalCompletion({- success: false,- message: `The user approved the call, but the record could not be read again, so nothing was run: ${latestRecord.error}`,- result: {- status: 'failed',- proposal: approvedProposal,- error: latestRecord.error,- },- });- }+ // the call was claimed as running before this, so it must end with an outcome rather than a throw+ try {+ const { currentValues, objectNameSingular, recordId } = approvedProposal;- if (!isEqual(latestRecord.values, currentValues)) {- return buildApprovalCompletion({- success: false,- message:- 'The user approved the call, but the record changed since it was proposed, so nothing was run. Read the record again and propose a new call if it is still needed.',- result: {- status: 'conflict',- proposal: approvedProposal,- output: { latestValues: latestRecord.values },- },+ if (+ isDefined(currentValues) &&+ isDefined(objectNameSingular) &&+ isDefined(recordId) &&+ Object.keys(currentValues).length > 0+ ) {+ const latestRecord = await readRecordFieldValues({+ executeTool: context.executeTool,+ objectNameSingular,+ recordId,+ fieldNames: Object.keys(currentValues),});- }- }-- const toolOutput = await context.executeTool({- toolName: approvedProposal.toolName,- args: approvedProposal.arguments,- });- return buildApprovalCompletion(- toolOutput.success- ? {- success: true,- message: `The user approved the call. ${toolOutput.message}`,+ // an update whose record cannot be read again cannot be shown to be safe, so it does not run+ if (!latestRecord.isFound) {+ return buildApprovalCompletion({+ success: false,+ message: `The user approved the call, but the record could not be read again, so nothing was run: ${latestRecord.error}`,result: {- status: 'approved',+ status: 'failed',proposal: approvedProposal,- output: toolOutput.result,+ error: latestRecord.error,},- }- : {+ });+ }++ if (!isEqual(latestRecord.values, currentValues)) {+ return buildApprovalCompletion({success: false,- message: `The user approved the call, but it failed: ${toolOutput.error ?? toolOutput.message}`,+ message:+ 'The user approved the call, but the record changed since it was proposed, so nothing was run. Read the record again and propose a new call if it is still needed.',result: {- status: 'failed',+ status: 'conflict',proposal: approvedProposal,- error: toolOutput.error ?? toolOutput.message,+ output: { latestValues: latestRecord.values },},- },- );+ });+ }+ }++ const toolOutput = await context.executeTool({+ toolName: approvedProposal.toolName,+ args: approvedProposal.arguments,+ });++ return buildApprovalCompletion(+ toolOutput.success+ ? {+ success: true,+ message: `The user approved the call. ${toolOutput.message}`,+ result: {+ status: 'approved',+ proposal: approvedProposal,+ output: toolOutput.result,+ },+ }+ : {+ success: false,+ message: `The user approved the call, but it failed: ${toolOutput.error ?? toolOutput.message}`,+ result: {+ status: 'failed',+ proposal: approvedProposal,+ error: toolOutput.error ?? toolOutput.message,+ },+ },+ );+ } catch (error) {+ const errorMessage =+ error instanceof Error ? error.message : String(error);++ return buildApprovalCompletion({+ success: false,+ message: `The user approved the call, but it failed: ${errorMessage}`,+ result: {+ status: 'failed',+ proposal: approvedProposal,+ error: errorMessage,+ },+ });+ }},+ // only an approval runs something, so a rejection is never claimed+ toRunningToolResult: ({ output, input, pendingToolOutput }) =>+ output.decision === 'approve'+ ? {+ success: true,+ message: 'The user approved the call and it is running.',+ result: {+ status: 'running',+ proposal: readProposal(input, pendingToolOutput).proposal,+ } satisfies ProposeToolCallToolResult,+ }+ : undefined,+ toInterruptedToolResult: (input, runningToolOutput) => ({+ success: false,+ message:+ 'The user approved the call, but it was interrupted before its outcome was recorded, so it may or may not have run. Check before proposing it again.',+ result: {+ status: 'failed',+ proposal: readProposal(input, runningToolOutput).proposal,+ error:+ 'Interrupted before its outcome was recorded. It may or may not have run.',+ } satisfies ProposeToolCallToolResult,+ }),toSkippedToolResult: (input, pendingToolOutput) => ({success: true,message:diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type.tsindex 91630da50da..a9b5e51572f 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type.ts@@ -13,4 +13,8 @@ export type PausingToolCall = {context: PausingToolCompletionContext;}) => Promise<PausingToolCompletion>;toSkippedToolResult: () => Record<string, unknown>;+ toRunningToolResult?: (+ output: Record<string, unknown>,+ ) => Record<string, unknown> | undefined;+ toInterruptedToolResult?: () => Record<string, unknown>;};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.tsindex a9cb470bdde..74230b1fd9b 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.ts@@ -20,4 +20,15 @@ export type PausingToolDefinition<TInput, TOutput> = {input: TInput,pendingToolOutput: unknown,) => Record<string, unknown>;+ // an answer that runs something is recorded as running first, so it can never be given twice, and+ // closes as interrupted when its outcome never got recorded, without running it again+ toRunningToolResult?: (args: {+ output: TOutput;+ input: TInput;+ pendingToolOutput: unknown;+ }) => Record<string, unknown> | undefined;+ toInterruptedToolResult?: (+ input: TInput,+ runningToolOutput: unknown,+ ) => Record<string, unknown>;};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/close-open-tool-parts.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/close-open-tool-parts.util.spec.tsnew file mode 100644index 00000000000..36c697c54da--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/__tests__/close-open-tool-parts.util.spec.ts@@ -0,0 +1,120 @@+import {+ ASK_QUESTIONS_TOOL_NAME,+ PROPOSE_TOOL_CALL_TOOL_NAME,+} from 'twenty-shared/ai';++import { closeOpenToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util';+import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';+import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';++const PROPOSAL = {+ toolName: 'update_one_company',+ toolLabel: 'Update company',+ summary: 'Raise the headcount',+ template: 'generic',+ arguments: { id: 'company-id', employees: 25 },+};+const PROPOSE_INPUT = {+ toolName: 'update_one_company',+ arguments: { id: 'company-id', employees: 25 },+ summary: 'Raise the headcount',+};+const QUESTIONS = [+ {+ header: 'Plan',+ question: 'Which plan?',+ options: [{ label: 'Pro' }, { label: 'Team' }],+ },+];++const closeParts = async (+ parts: Partial<AgentMessagePartWorkspaceEntity>[],+) => {+ const writes: { id: string; result: unknown; expectedStatus: string }[] = [];+ const messagePartRepository = {+ find: jest.fn().mockResolvedValue(parts),+ query: jest.fn(async (_workspaceId, run) =>+ run({+ table: (name: string) => name,+ manager: {+ query: async (+ _sql: string,+ [id, toolOutput, expectedStatus]: [string, string, string],+ ) =>+ writes.push({+ id,+ result: JSON.parse(toolOutput).result,+ expectedStatus,+ }),+ },+ }),+ ),+ } as unknown as AgentHistoryRepository<AgentMessagePartWorkspaceEntity>;++ await closeOpenToolParts({+ messagePartRepository,+ messageId: 'message-id',+ workspaceId: 'workspace-id',+ });++ return writes;+};++describe('closeOpenToolParts', () => {+ it('skips the calls still waiting on an answer', async () => {+ expect(+ await closeParts([+ {+ id: 'questions',+ toolName: ASK_QUESTIONS_TOOL_NAME,+ toolInput: { questions: QUESTIONS },+ toolOutput: { result: { status: 'pending', questions: QUESTIONS } },+ },+ ]),+ ).toEqual([+ {+ id: 'questions',+ result: expect.objectContaining({ status: 'skipped' }),+ expectedStatus: 'pending',+ },+ ]);+ });++ it('closes an approved call whose outcome was never recorded as interrupted', async () => {+ expect(+ await closeParts([+ {+ id: 'proposal',+ toolName: PROPOSE_TOOL_CALL_TOOL_NAME,+ toolInput: PROPOSE_INPUT,+ toolOutput: { result: { status: 'running', proposal: PROPOSAL } },+ },+ ]),+ ).toEqual([+ {+ id: 'proposal',+ result: {+ status: 'failed',+ proposal: PROPOSAL,+ error:+ 'Interrupted before its outcome was recorded. It may or may not have run.',+ },+ expectedStatus: 'running',+ },+ ]);+ });++ it('leaves answered calls and other parts as they are', async () => {+ expect(+ await closeParts([+ {+ id: 'answered',+ toolName: PROPOSE_TOOL_CALL_TOOL_NAME,+ toolInput: PROPOSE_INPUT,+ toolOutput: { result: { status: 'approved', proposal: PROPOSAL } },+ },+ { id: 'text', toolName: null, toolInput: null, toolOutput: null },+ ]),+ ).toEqual([]);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util.tsnew file mode 100644index 00000000000..ed2cb27a37b--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util.ts@@ -0,0 +1,56 @@+import { isDefined } from 'twenty-shared/utils';++import { PAUSING_TOOLS } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant';+import { readToolCallStatus } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-tool-call-status.util';+import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';+import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';++// a pending call is skipped, and one still running had its outcome lost, so it closes as interrupted+export const closeOpenToolParts = async ({+ messagePartRepository,+ messageId,+ workspaceId,+}: {+ messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>;+ messageId: string;+ workspaceId: string;+}): Promise<void> => {+ const parts = await messagePartRepository.find(workspaceId, {+ where: { messageId },+ select: ['id', 'toolName', 'toolInput', 'toolOutput'],+ });++ for (const part of parts) {+ const pausingTool = isDefined(part.toolName)+ ? PAUSING_TOOLS.get(part.toolName)+ : undefined;++ if (!isDefined(pausingTool)) {+ continue;+ }++ const status = readToolCallStatus(part.toolOutput);+ const isAwaiting = status === 'pending';+ const pausingToolCall =+ isAwaiting || status === 'running'+ ? pausingTool.parseCall(part.toolInput, part.toolOutput)+ : null;+ const closedToolOutput = isAwaiting+ ? pausingToolCall?.toSkippedToolResult()+ : pausingToolCall?.toInterruptedToolResult?.();++ if (!isDefined(closedToolOutput)) {+ continue;+ }++ // written only while the call is as it was read, so an answer recorded meanwhile is kept, and+ // the rest of the output, such as the workflow step that posted the call, stays readable+ await messagePartRepository.query(workspaceId, ({ manager, table }) =>+ manager.query(+ `UPDATE ${table('agentMessagePart')} SET "toolOutput" = "toolOutput" || $2::jsonb, "updatedAt" = now()+ WHERE id = $1 AND "toolOutput"->'result'->>'status' = $3`,+ [part.id, JSON.stringify(closedToolOutput), status],+ ),+ );+ }+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util.tsindex 81566ea3907..cd92afae4e2 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util.ts@@ -1,3 +1,5 @@+import { isDefined } from 'twenty-shared/utils';+import { type PausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type';import { type PausingToolDefinition } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type';@@ -17,9 +19,27 @@ export const definePausingTool = <const input = parsedInput.data;const outputSchema = definition.outputSchema(input, pendingToolOutput);+ const { toRunningToolResult, toInterruptedToolResult } = definition;+return {toSkippedToolResult: () =>definition.toSkippedToolResult(input, pendingToolOutput),+ ...(isDefined(toRunningToolResult)+ ? {+ toRunningToolResult: (output: Record<string, unknown>) =>+ toRunningToolResult({+ output: outputSchema.parse(output),+ input,+ pendingToolOutput,+ }),+ }+ : {}),+ ...(isDefined(toInterruptedToolResult)+ ? {+ toInterruptedToolResult: () =>+ toInterruptedToolResult(input, pendingToolOutput),+ }+ : {}),validate: (output) => {const parsedOutput = outputSchema.safeParse(output);diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util.tsindex e073ebf8036..c8d39511ce6 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util.ts@@ -1,6 +1,4 @@-import { isPlainObject } from 'twenty-shared/utils';+import { readToolCallStatus } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-tool-call-status.util';export const isAwaitingPausingToolOutput = (toolOutput: unknown): boolean =>- isPlainObject(toolOutput) &&- isPlainObject(toolOutput.result) &&- toolOutput.result.status === 'pending';+ readToolCallStatus(toolOutput) === 'pending';diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-tool-call-status.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-tool-call-status.util.tsnew file mode 100644index 00000000000..581d2091900--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-tool-call-status.util.ts@@ -0,0 +1,6 @@+import { isPlainObject } from 'twenty-shared/utils';++export const readToolCallStatus = (toolOutput: unknown): unknown =>+ isPlainObject(toolOutput) && isPlainObject(toolOutput.result)+ ? toolOutput.result.status+ : undefined;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util.tsdeleted file mode 100644index db9c3c07c41..00000000000--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util.ts+++ /dev/null@@ -1,35 +0,0 @@-import { isDefined } from 'twenty-shared/utils';--import { findAwaitingPausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool.util';-import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';-import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';--export const skipAwaitingToolParts = async ({- messagePartRepository,- messageId,- workspaceId,-}: {- messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>;- messageId: string;- workspaceId: string;-}): Promise<void> => {- const parts = await messagePartRepository.find(workspaceId, {- where: { messageId },- select: ['id', 'toolName', 'toolInput', 'toolOutput'],- });-- for (const part of parts) {- const pausingToolCall = findAwaitingPausingTool(part)?.parseCall(- part.toolInput,- part.toolOutput,- );-- if (isDefined(pausingToolCall)) {- await messagePartRepository.update(- workspaceId,- { id: part.id },- { toolOutput: pausingToolCall.toSkippedToolResult() },- );- }- }-};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.tsindex 7c956735186..4920c12d5ef 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.close-pending-tool-calls.spec.ts@@ -23,9 +23,17 @@ const buildService = ({ claimAffected = 1 } = {}) => {toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },},]),- update: jest.fn().mockResolvedValue({ affected: 1 }),+ writePart: jest.fn(),+ query: jest.fn(),};+ messagePartRepository.query.mockImplementation(async (_workspaceId, run) =>+ run({+ table: (name: string) => name,+ manager: { query: messagePartRepository.writePart },+ }),+ );+const service = new AgentChatService(threadRepository as never,{} as never,@@ -64,15 +72,19 @@ describe('AgentChatService closePendingToolCalls', () => {},{ pendingQuestionMessageId: null },);- expect(messagePartRepository.update).toHaveBeenCalledWith(- 'workspace-id',- { id: 'part-id' },- {- toolOutput: expect.objectContaining({- result: { questions: QUESTIONS, status: 'skipped' },- }),- },- );+ const [[closeQuery, [partId, closedToolOutput, expectedStatus]]] =+ messagePartRepository.writePart.mock.calls;++ expect(closeQuery).toContain(`"toolOutput"->'result'->>'status' = $3`);++ expect({ partId, expectedStatus }).toEqual({+ partId: 'part-id',+ expectedStatus: 'pending',+ });+ expect(JSON.parse(closedToolOutput).result).toEqual({+ questions: QUESTIONS,+ status: 'skipped',+ });});it('leaves the call as it is when an answer holds the conversation', async () => {@@ -82,6 +94,6 @@ describe('AgentChatService closePendingToolCalls', () => {await service.closePendingToolCalls(closeArguments);- expect(messagePartRepository.update).not.toHaveBeenCalled();+ expect(messagePartRepository.writePart).not.toHaveBeenCalled();});});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.tsindex d5b1240b269..a852899a893 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@@ -18,7 +18,7 @@ import { AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-himport { AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity';import { mapUIMessagePartsToDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-db-parts.util';import { findAwaitingPausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool.util';-import { skipAwaitingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util';+import { closeOpenToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util';import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';@@ -523,6 +523,30 @@ export class AgentChatService {return parts.filter((part) => isDefined(findAwaitingPausingTool(part)));}+ // only a call still pending is claimed, so two answers can never both run it; the rest of the+ // pending output, such as the workflow step waiting on it, is kept+ async claimToolCallAnswer({+ partId,+ toolOutput,+ workspaceId,+ }: {+ partId: string;+ toolOutput: Record<string, unknown>;+ workspaceId: string;+ }): Promise<boolean> {+ const claimedParts = await this.messagePartRepository.query(+ workspaceId,+ ({ manager, table }) =>+ manager.query<{ id: string }[]>(+ `WITH claimed_part AS (UPDATE ${table('agentMessagePart')} SET "toolOutput" = "toolOutput" || $2::jsonb, "updatedAt" = now()+ WHERE id = $1 AND "toolOutput"->'result'->>'status' = 'pending' RETURNING id) SELECT id FROM claimed_part`,+ [partId, JSON.stringify(toolOutput)],+ ),+ );++ return claimedParts.length === 1;+ }+// written together so an answer never strands a conversation waiting on answered callsasync recordToolCallAnswer({threadId,@@ -557,7 +581,7 @@ export class AgentChatService {);}- // clearing the marker is the claim, so only one caller closes the calls as skipped+ // clearing the marker is the claim, so only one caller closes the callsasync closePendingToolCalls({threadId,messageId,@@ -579,7 +603,7 @@ export class AgentChatService {return;}- await skipAwaitingToolParts({+ await closeOpenToolParts({messagePartRepository: this.messagePartRepository,messageId,workspaceId,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.tsindex ba804829387..ee2f69477bf 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@@ -1,14 +1,12 @@import { Injectable } from '@nestjs/common';import { type ExtendedUIMessagePart } from 'twenty-shared/ai';-import {- type SendInboxMessageInput,- type SendInboxMessageResult,-} from 'twenty-shared/application';+import { type SendInboxMessageInput } from 'twenty-shared/application';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 AgentInboxDelivery } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-delivery.type';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';@@ -21,6 +19,7 @@ import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-historimport { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';+import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';@@ -32,6 +31,8 @@ export class AgentInboxService {private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,@InjectAgentHistoryRepository('agentMessage')private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,+ @InjectAgentHistoryRepository('agentMessagePart')+ private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,private readonly threadService: AgentChatThreadService,private readonly conversationWriterService: AgentConversationWriterService,private readonly workspaceCacheService: WorkspaceCacheService,@@ -45,7 +46,7 @@ export class AgentInboxService {workspaceId,sender,input,- awaitingToolCall,+ buildAwaitingToolCall,resolveProposal = async (proposeToolCallInput) =>resolveEmailToolCallProposal(proposeToolCallInput),}: {@@ -54,13 +55,14 @@ export class AgentInboxService {input: Omit<SendInboxMessageInput, 'toolCall'> & { toolCall?: unknown };// without a resolver, only emails can be proposed: they need no tool of the sender'sresolveProposal?: ResolveInboxProposal;- // a pausing call the server already resolved, with its pending output- awaitingToolCall?: {+ // a pausing call the server resolves, with its pending output, only when the message is written,+ // so a message delivered earlier is found even once the call could no longer be resolved+ buildAwaitingToolCall?: () => Promise<{toolName: string;input: Record<string, unknown>;output: Record<string, unknown>;- };- }): Promise<SendInboxMessageResult> {+ }>;+ }): Promise<AgentInboxDelivery> {const senderDetails = getAgentInboxSenderDetails(sender);const { threadId, turnId, openingMessageId, messageId, toolCallId } =buildInboxMessageIds({@@ -74,13 +76,21 @@ export class AgentInboxService {// A member who deleted the conversation has dismissed it, and a message// that exists was already delivered.- if (- isDefined(existingThread?.deletedAt) ||- (await this.messageExists({ workspaceId, id: messageId }))- ) {- return { threadId };+ if (isDefined(existingThread?.deletedAt)) {+ return { threadId, isDismissed: true };}+ if (await this.messageExists({ workspaceId, id: messageId })) {+ return {+ threadId,+ isDismissed: false,+ awaitedToolOutput: isDefined(buildAwaitingToolCall)+ ? await this.findToolOutput({ workspaceId, toolCallId })+ : undefined,+ };+ }++ const awaitingToolCall = await buildAwaitingToolCall?.();const toolCallPart = isDefined(awaitingToolCall)? {part: buildToolPart({ ...awaitingToolCall, toolCallId }),@@ -147,7 +157,30 @@ export class AgentInboxService {});}- return { threadId };+ if (!isDefined(awaitingToolCall)) {+ return { threadId, isDismissed: false };+ }++ const awaitedToolOutput = isWritten+ ? awaitingToolCall.output+ : await this.findToolOutput({ workspaceId, toolCallId });++ return { threadId, isDismissed: false, awaitedToolOutput };+ }++ private async findToolOutput({+ workspaceId,+ toolCallId,+ }: {+ workspaceId: string;+ toolCallId: string;+ }): Promise<unknown> {+ const part = await this.messagePartRepository.findOne(workspaceId, {+ where: { toolCallId },+ select: ['toolOutput'],+ });++ return part?.toolOutput;}// Answering a tool call resolves who may answer from the user message ofdiff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-delivery.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-delivery.type.tsnew file mode 100644index 00000000000..a6c47f0dcdf--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-delivery.type.ts@@ -0,0 +1,7 @@+import { type SendInboxMessageResult } from 'twenty-shared/application';++export type AgentInboxDelivery = SendInboxMessageResult & {+ isDismissed: boolean;+ // the awaited call as it stands now, which a message delivered earlier may have settled+ awaitedToolOutput?: unknown;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.tsindex 91897c6e7dd..a7b976998be 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts@@ -166,6 +166,7 @@ export class ToolCallAnswerService {}let step: WorkflowAction | null = null;+ let isClaimedAsRunning = false;let isLastAnswer: boolean;let answerText: string;let toolResult: Record<string, unknown>;@@ -191,9 +192,10 @@ export class ToolCallAnswerService {if (!isDefined(step) &&- isDefined(inboxWorkflowStep) &&(await this.workflowRunWorkspaceService.isStepStillRunning({- ...inboxWorkflowStep,+ stepId: inboxWorkflowStep?.stepId,+ threadId,+ workflowRunId,workspaceId,}))) {@@ -217,6 +219,24 @@ export class ToolCallAnswerService {}}+ const runningToolResult = pausingToolCall.toRunningToolResult?.(+ validation.output,+ );++ if (isDefined(runningToolResult)) {+ if (+ !(await this.agentChatService.claimToolCallAnswer({+ partId: toolPart.id,+ toolOutput: runningToolResult,+ workspaceId,+ }))+ ) {+ throw this.notPending();+ }++ isClaimedAsRunning = true;+ }+const completion = await pausingToolCall.complete({output: validation.output,context: this.buildCompletionContext({@@ -240,11 +260,38 @@ export class ToolCallAnswerService {answerText = completion.answerText;toolResult = completion.toolResult;} catch (error) {- await this.streamRecoveryService.releaseStreamClaim({- threadId,- workspaceId,- streamId,- });+ // a call claimed as running cannot be answered again, so the run or turn fails, which+ // closes the call as interrupted instead of leaving it waiting on an outcome+ if (isClaimedAsRunning) {+ if (!isDefined(workflowRunId)) {+ await this.agentChatService+ .closePendingToolCalls({+ threadId,+ messageId: toolPart.messageId,+ workspaceId,+ where: { activeStreamId: streamId },+ })+ .catch((closeError: unknown) =>+ this.logger.warn(+ `Could not close the interrupted call on thread ${threadId}: ${closeError instanceof Error ? closeError.message : String(closeError)}`,+ ),+ );+ }++ await this.failAfterAnswer({+ threadId,+ workspaceId,+ streamId,+ workflowRunId,+ error,+ });+ } else {+ await this.streamRecoveryService.releaseStreamClaim({+ threadId,+ workspaceId,+ streamId,+ });+ }throw error;}@@ -317,31 +364,55 @@ export class ToolCallAnswerService {return { streamId, turnId: answerMessage.turnId };} catch (error) {- if (isDefined(workflowRunId)) {- await this.streamRecoveryService.releaseStreamClaim({- threadId,- workspaceId,- streamId,- });- await this.workflowRunWorkspaceService.endWorkflowRun({- workflowRunId,- workspaceId,- status: WorkflowRunStatus.FAILED,- error: 'The run could not resume after its question was answered',- });- } else {- await this.streamRecoveryService.failStream({- threadId,- workspaceId,- streamId,- error,- });- }+ await this.failAfterAnswer({+ threadId,+ workspaceId,+ streamId,+ workflowRunId,+ error,+ });throw error;}}+ private async failAfterAnswer({+ threadId,+ workspaceId,+ streamId,+ workflowRunId,+ error,+ }: {+ threadId: string;+ workspaceId: string;+ streamId: string;+ workflowRunId: string | null;+ error: unknown;+ }): Promise<void> {+ if (!isDefined(workflowRunId)) {+ await this.streamRecoveryService.failStream({+ threadId,+ workspaceId,+ streamId,+ error,+ });++ return;+ }++ await this.streamRecoveryService.releaseStreamClaim({+ threadId,+ workspaceId,+ streamId,+ });+ await this.workflowRunWorkspaceService.endWorkflowRun({+ workflowRunId,+ workspaceId,+ status: WorkflowRunStatus.FAILED,+ error: 'The run could not resume after its question was answered',+ });+ }+// an answer that resumes a workflow step starts no chat turn, so it skips the model and// billing checks but still needs a thread the member can write toprivate async assertCanAnswerInChat({diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.tsindex 04cbd7fd9d9..d8a25d3178f 100644--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts@@ -342,7 +342,7 @@ export class WorkflowVersionStepOperationsWorkspaceService {return {builtStep: {...baseStep,- name: 'Send Chat Message',+ name: 'Send to Inbox',type: WorkflowActionType.SEND_CHAT_MESSAGE,settings: {...BASE_STEP_DEFINITION,diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.tsindex 61ca7724582..f7d84dd8267 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@@ -170,7 +170,6 @@ export class WorkflowAgentConversationWorkspaceService {return { threadId, isAwaitingAnswer };}- // One unanswerable call would keep the step waiting forever, so the step fails insteadprivate async recordReply({workspaceId,threadId,diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.tsindex e38d4993a3d..178666380dc 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts@@ -20,7 +20,7 @@ const buildStep = (input: Record<string, unknown>): WorkflowAction =>({id: 'step-1',type: WorkflowActionType.SEND_CHAT_MESSAGE,- name: 'Send Chat Message',+ name: 'Send to Inbox',valid: true,settings: {outputSchema: {},@@ -140,7 +140,7 @@ describe('SendChatMessageWorkflowAction', () => {expect(sendMessage).toHaveBeenCalledWith(expect.objectContaining({- input: expect.objectContaining({ title: 'Send Chat Message' }),+ input: expect.objectContaining({ title: 'Send to Inbox' }),}),);});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.tsindex ad7e6f42112..ad7ce6a3c52 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts@@ -2,7 +2,12 @@ import { Injectable } from '@nestjs/common';import { isNonEmptyString } from '@sniptt/guards';import { PROPOSE_TOOL_CALL_TOOL_NAME } from 'twenty-shared/ai';-import { isDefined, isValidUuid, resolveInput } from 'twenty-shared/utils';+import {+ isDefined,+ isPlainObject,+ isValidUuid,+ resolveInput,+} from 'twenty-shared/utils';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';@@ -10,6 +15,7 @@ import { type WorkflowEntity } from 'src/engine/core-modules/workflow/entities/wimport { 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 { WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';+import { readToolCallStatus } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/read-tool-call-status.util';import { resolveProposedToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-proposed-tool-call.util';import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';import { buildProposeToolCallPendingOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-tool-call.pausing-tool';@@ -27,9 +33,13 @@ import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executoimport { buildStepExecutionKey } from 'src/modules/workflow/workflow-executor/utils/build-step-execution-key.util';import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';import { isWorkflowSendChatMessageAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/guards/is-workflow-send-chat-message-action.guard';+import { findMissingRequiredToolArguments } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/find-missing-required-tool-arguments.util';+import { buildSendChatMessageAnswerResult } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util';import { type WorkflowSendChatMessageActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type';import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';+const MAX_SEND_ATTEMPTS = 10;+@Injectable()export class SendChatMessageWorkflowAction implements WorkflowAction {constructor(@@ -75,60 +85,102 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {);}- const [workflow, awaitingToolCall] = await Promise.all([- this.findRunWorkflowOrThrow(runInfo),- isDefined(toolCall)- ? this.buildAwaitingToolCall({+ const workflow = await this.findRunWorkflowOrThrow(runInfo);+ let awaitingToolCall:+ | ReturnType<SendChatMessageWorkflowAction['resolveAwaitingToolCall']>+ | undefined;+ const buildAwaitingToolCall = isDefined(toolCall)+ ? () => {+ awaitingToolCall ??= this.resolveAwaitingToolCall({toolCall,summary: text,runInfo,stepId: currentStepId,- })- : undefined,- ]);+ });- // Each run gets its own conversation with the member, so every message- // a run sends reads as one exchange.- const { threadId } = await this.agentInboxService.sendMessage({- workspaceId: runInfo.workspaceId,- sender: {- type: 'workflow',- workflowId: workflow.id,- workflowName: isNonEmptyString(workflow.name)- ? workflow.name- : 'Untitled',- },- input: {- workspaceMemberId,- threadKey: runInfo.workflowRunId,- idempotencyKey: buildStepExecutionKey({- stepId: currentStepId,- steps,- context,- }),- title: isNonEmptyString(title) ? title : step.name,- text,- },- awaitingToolCall,- });+ return awaitingToolCall;+ }+ : undefined;- if (!isDefined(awaitingToolCall)) {- return { result: { threadId } };- }-- // the step waits for the member, and their answer finds it through this thread- await this.workflowRunWorkspaceService.setStepThreadId({+ const sendMessage = (idempotencyKey: string) =>+ // Each run gets its own conversation with the member, so every message+ // a run sends reads as one exchange.+ this.agentInboxService.sendMessage({+ workspaceId: runInfo.workspaceId,+ sender: {+ type: 'workflow',+ workflowId: workflow.id,+ workflowName: isNonEmptyString(workflow.name)+ ? workflow.name+ : 'Untitled',+ },+ input: {+ workspaceMemberId,+ threadKey: runInfo.workflowRunId,+ idempotencyKey,+ title: isNonEmptyString(title) ? title : step.name,+ text,+ },+ buildAwaitingToolCall,+ });+ const executionKey = buildStepExecutionKey({stepId: currentStepId,- threadId,- workflowRunId: runInfo.workflowRunId,- workspaceId: runInfo.workspaceId,+ steps,+ context,});- return { pendingEvent: true };+ // a step run again finds the call it posted before: it keeps waiting on a pending one, reuses+ // an answered one so nothing runs twice, and asks again once an earlier call closed unanswered+ for (let attempt = 0; attempt < MAX_SEND_ATTEMPTS; attempt++) {+ const { threadId, isDismissed, awaitedToolOutput } = await sendMessage(+ attempt === 0 ? executionKey : `${executionKey}:${attempt}`,+ );++ if (!isDefined(buildAwaitingToolCall)) {+ return { result: { threadId } };+ }++ if (isDismissed) {+ throw new WorkflowStepExecutorException(+ 'The recipient deleted this conversation, so the action cannot be approved',+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,+ );+ }++ const status = readToolCallStatus(awaitedToolOutput);++ if (status === 'skipped') {+ continue;+ }++ if (status === 'pending' || status === 'running') {+ // the step waits for the member, and their answer finds it through this thread+ await this.workflowRunWorkspaceService.setStepThreadId({+ stepId: currentStepId,+ threadId,+ workflowRunId: runInfo.workflowRunId,+ workspaceId: runInfo.workspaceId,+ });++ return { pendingEvent: true };+ }++ return {+ result: buildSendChatMessageAnswerResult({+ threadId,+ toolResult: isPlainObject(awaitedToolOutput) ? awaitedToolOutput : {},+ }),+ };+ }++ throw new WorkflowStepExecutorException(+ `The action was asked ${MAX_SEND_ATTEMPTS} times without an answer`,+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,+ );}// resolved with the run's permissions, the ones the step itself acts with- private async buildAwaitingToolCall({+ private async resolveAwaitingToolCall({toolCall,summary,runInfo,@@ -142,13 +194,31 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {const { authContext, rolePermissionConfig, application } =await this.workflowExecutionContextService.getExecutionContext(runInfo);- const toolContext: ToolContext = {+ const toolContext = {workspaceId: runInfo.workspaceId,roleId: getRoleIdsFromRolePermissionConfig(rolePermissionConfig)[0] ?? '',rolePermissionConfig,authContext,application: application ?? undefined,- };+ } satisfies ToolContext;++ const catalog = await this.toolRegistryService.getCatalog(toolContext);+ const inputSchemas = await this.toolRegistryService.resolveSchemas({+ toolNames: [toolCall.toolName],+ context: toolContext,+ precomputedCatalog: catalog,+ });+ const missingArgumentNames = findMissingRequiredToolArguments({+ inputSchema: inputSchemas.get(toolCall.toolName),+ toolArguments: toolCall.arguments,+ });++ if (missingArgumentNames.length > 0) {+ throw new WorkflowStepExecutorException(+ `The action is missing required arguments: ${missingArgumentNames.join(', ')}`,+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,+ );+ }const input = {toolName: toolCall.toolName,@@ -158,8 +228,8 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {const resolution = await resolveProposedToolCall({input,- findTool: (toolName) =>- this.toolRegistryService.findCatalogEntry(toolName, toolContext),+ findTool: async (toolName) =>+ catalog.find((catalogEntry) => catalogEntry.name === toolName),executeTool: ({ toolName, args }) =>this.toolRegistryService.resolveAndExecute(toolName, args, toolContext),});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-outcome.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-outcome.type.tsnew file mode 100644index 00000000000..27ebd521cb5--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-outcome.type.ts@@ -0,0 +1,5 @@+export type SendChatMessageAnswerOutcome =+ | 'executed'+ | 'rejected'+ | 'failed'+ | 'conflict';diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-result.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-result.type.tsindex 0df520e46e6..e499336a404 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-result.type.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-result.type.ts@@ -1,9 +1,10 @@+import { type SendChatMessageAnswerOutcome } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-outcome.type';+export type SendChatMessageAnswerResult = {threadId: string;- isApproved: boolean;- approvedToolName: string | null;- status: string | null;- arguments: Record<string, unknown> | null;+ outcome: SendChatMessageAnswerOutcome;+ toolName: string;+ arguments: Record<string, unknown>;output: unknown;feedback: string | null;error: string | null;diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/build-send-chat-message-answer-result.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/build-send-chat-message-answer-result.util.spec.tsindex 8506269c189..da14e8d654d 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/build-send-chat-message-answer-result.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/build-send-chat-message-answer-result.util.spec.ts@@ -14,7 +14,7 @@ const buildResult = (result: Record<string, unknown>) =>describe('buildSendChatMessageAnswerResult', () => {it.each(['send_email', 'draft_email'])(- 'tells later steps the member approved %s',+ 'reports %s as executed once approved',(toolName) => {expect(buildResult({@@ -24,9 +24,8 @@ describe('buildSendChatMessageAnswerResult', () => {}),).toEqual({threadId: 'thread-id',- isApproved: true,- approvedToolName: toolName,- status: 'approved',+ outcome: 'executed',+ toolName,arguments: EMAIL_ARGUMENTS,output: { messageId: 'message-id' },feedback: null,@@ -35,7 +34,7 @@ describe('buildSendChatMessageAnswerResult', () => {},);- it('counts an approved call that failed as approved', () => {+ it('keeps the error of an approved call that failed', () => {expect(buildResult({status: 'failed',@@ -43,14 +42,27 @@ describe('buildSendChatMessageAnswerResult', () => {error: 'No connected account',}),).toMatchObject({- isApproved: true,- approvedToolName: 'send_email',- status: 'failed',+ outcome: 'failed',+ toolName: 'send_email',+ output: null,error: 'No connected account',});});- it('names no action when the member rejects the call', () => {+ it('keeps the latest values of a record that changed before approval', () => {+ expect(+ buildResult({+ status: 'conflict',+ proposal: { toolName: 'update_one_company', arguments: {} },+ output: { latestValues: { employees: 12 } },+ }),+ ).toMatchObject({+ outcome: 'conflict',+ output: { latestValues: { employees: 12 } },+ });+ });++ it('keeps the feedback of a rejected call', () => {expect(buildResult({status: 'rejected',@@ -58,9 +70,21 @@ describe('buildSendChatMessageAnswerResult', () => {feedback: 'Not yet',}),).toMatchObject({- isApproved: false,- approvedToolName: null,+ outcome: 'rejected',+ toolName: 'send_email',feedback: 'Not yet',});});++ it.each(['pending', 'running', 'skipped', undefined])(+ 'refuses to report a %s call',+ (status) => {+ expect(() =>+ buildResult({+ status,+ proposal: { toolName: 'send_email', arguments: EMAIL_ARGUMENTS },+ }),+ ).toThrow('The answer to the action could not be read');+ },+ );});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/find-missing-required-tool-arguments.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/find-missing-required-tool-arguments.util.spec.tsnew file mode 100644index 00000000000..f500c5cd25a--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/__tests__/find-missing-required-tool-arguments.util.spec.ts@@ -0,0 +1,44 @@+import { findMissingRequiredToolArguments } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/find-missing-required-tool-arguments.util';++const CALENDAR_EVENT_SCHEMA = {+ type: 'object',+ properties: {+ title: { type: 'string' },+ startsAt: { type: 'string' },+ endsAt: { type: 'string' },+ location: { type: 'string' },+ },+ required: ['title', 'startsAt', 'endsAt'],+};++describe('findMissingRequiredToolArguments', () => {+ it('names the required arguments that are absent, once each', () => {+ expect(+ findMissingRequiredToolArguments({+ inputSchema: {+ ...CALENDAR_EVENT_SCHEMA,+ required: [...CALENDAR_EVENT_SCHEMA.required, 'endsAt'],+ },+ toolArguments: { title: 'Kickoff', location: 'Paris' },+ }),+ ).toEqual(['startsAt', 'endsAt']);+ });++ it('leaves a present value, even null or empty, to the tool', () => {+ expect(+ findMissingRequiredToolArguments({+ inputSchema: CALENDAR_EVENT_SCHEMA,+ toolArguments: { title: '', startsAt: null, endsAt: '2026-07-01' },+ }),+ ).toEqual([]);+ });++ it('finds nothing missing without a schema', () => {+ expect(+ findMissingRequiredToolArguments({+ inputSchema: undefined,+ toolArguments: {},+ }),+ ).toEqual([]);+ });+});diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util.tsindex bebf389d309..00ba186b75c 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/build-send-chat-message-answer-result.util.ts@@ -1,12 +1,21 @@import { isString } from '@sniptt/guards';-import { isPlainObject } from 'twenty-shared/utils';+import { isDefined, isPlainObject } from 'twenty-shared/utils';+import {+ WorkflowStepExecutorException,+ WorkflowStepExecutorExceptionCode,+} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';+import { type SendChatMessageAnswerOutcome } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-outcome.type';import { type SendChatMessageAnswerResult } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/send-chat-message-answer-result.type';-// the member approved whenever the call was attempted, whatever its outcome, which status carries-const APPROVED_STATUSES = new Set(['approved', 'failed', 'conflict']);+const OUTCOME_BY_STATUS: ReadonlyMap<string, SendChatMessageAnswerOutcome> =+ new Map([+ ['approved', 'executed'],+ ['rejected', 'rejected'],+ ['failed', 'failed'],+ ['conflict', 'conflict'],+ ]);-// flattens the answered call so later steps can branch on the decision and use the resultexport const buildSendChatMessageAnswerResult = ({threadId,toolResult,@@ -16,18 +25,24 @@ export const buildSendChatMessageAnswerResult = ({}): SendChatMessageAnswerResult => {const result = isPlainObject(toolResult.result) ? toolResult.result : {};const proposal = isPlainObject(result.proposal) ? result.proposal : {};+ const outcome = isString(result.status)+ ? OUTCOME_BY_STATUS.get(result.status)+ : undefined;- const isApproved =- isString(result.status) && APPROVED_STATUSES.has(result.status);+ if (!isDefined(outcome) || !isString(proposal.toolName)) {+ throw new WorkflowStepExecutorException(+ 'The answer to the action could not be read',+ WorkflowStepExecutorExceptionCode.INTERNAL_ERROR,+ );+ }return {threadId,- isApproved,+ outcome,// the member may approve an alternative, such as saving an email as a draft instead of sending it- approvedToolName:- isApproved && isString(proposal.toolName) ? proposal.toolName : null,- status: isString(result.status) ? result.status : null,- arguments: isPlainObject(proposal.arguments) ? proposal.arguments : null,+ toolName: proposal.toolName,+ arguments: isPlainObject(proposal.arguments) ? proposal.arguments : {},+ // a conflict carries the record's latest valuesoutput: result.output ?? null,feedback: isString(result.feedback) ? result.feedback : null,error: isString(result.error) ? result.error : null,diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/find-missing-required-tool-arguments.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/find-missing-required-tool-arguments.util.tsnew file mode 100644index 00000000000..8c900399ecc--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/utils/find-missing-required-tool-arguments.util.ts@@ -0,0 +1,25 @@+import { isString } from '@sniptt/guards';+import { isPlainObject } from 'twenty-shared/utils';++// required means present, as in JSON Schema: a null or empty value is the tool's to accept or refuse+export const findMissingRequiredToolArguments = ({+ inputSchema,+ toolArguments,+}: {+ inputSchema: unknown;+ toolArguments: Record<string, unknown>;+}): string[] => {+ if (!isPlainObject(inputSchema) || !Array.isArray(inputSchema.required)) {+ return [];+ }++ const presentArgumentNames = new Set(+ Object.entries(toolArguments)+ .filter(([, value]) => value !== undefined)+ .map(([argumentName]) => argumentName),+ );++ return [...new Set(inputSchema.required.filter(isString))].filter(+ (argumentName) => !presentArgumentNames.has(argumentName),+ );+};diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.tsindex 771a8ac4069..b0f367bcc70 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts@@ -195,6 +195,7 @@ export class WorkflowExecutorWorkspaceService {if (canRetryStep) {await this.scheduleStepRetry({stepId,+ resumedThreadId,error: actionOutput.error,retryDelayMs: getStepRetryDelayMs({ stepInfo: stepInfos[stepId] }),workflowRunId,@@ -729,14 +730,18 @@ export class WorkflowExecutorWorkspaceService {}}+ // a step that failed after resuming on an answer retries from that conversation, so the+ // person is not asked again and an approved call does not run a second timeprivate async scheduleStepRetry({stepId,+ resumedThreadId,error,retryDelayMs,workflowRunId,workspaceId,}: {stepId: string;+ resumedThreadId: string | undefined;error: string;retryDelayMs: number;workflowRunId: string;@@ -744,6 +749,7 @@ export class WorkflowExecutorWorkspaceService {}) {await this.workflowRunWorkspaceService.moveStepToRetry({stepId,+ resumedThreadId,error,workflowRunId,workspaceId,diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.tsindex a3622610f1d..7a857be55de 100644--- a/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.ts@@ -215,11 +215,33 @@ export class RunWorkflowJob {});}- await this.workflowExecutorWorkspaceService.executeFromSteps({- stepIds: stepIdsToRetry,- workflowRunId,- workspaceId,- });+ // a step that failed after resuming on an answer kept its conversation, and continues it+ const resumedStepIds = stepIdsToRetry.filter((stepId) =>+ isDefined(stepInfosToReset[stepId]?.threadId),+ );+ const restartedStepIds = stepIdsToRetry.filter(+ (stepId) => !resumedStepIds.includes(stepId),+ );++ await Promise.all([+ ...(restartedStepIds.length > 0+ ? [+ this.workflowExecutorWorkspaceService.executeFromSteps({+ stepIds: restartedStepIds,+ workflowRunId,+ workspaceId,+ }),+ ]+ : []),+ ...resumedStepIds.map((stepId) =>+ this.workflowExecutorWorkspaceService.executeFromSteps({+ stepIds: [stepId],+ workflowRunId,+ workspaceId,+ resumedThreadId: stepInfosToReset[stepId].threadId,+ }),+ ),+ ]);}// The step stays PENDING until claimed here, so its run can't complete while queued and a second resume no-opsdiff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.tsindex c56acf845f9..9d9261d1624 100644--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts@@ -37,8 +37,16 @@ describe('WorkflowRunWorkspaceService conversations', () => {toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },},]),- update: jest.fn().mockResolvedValue({ affected: 1 }),+ writePart: jest.fn(),+ query: jest.fn(),};++ messagePartRepository.query.mockImplementation(async (_workspaceId, run) =>+ run({+ table: (name: string) => name,+ manager: { query: messagePartRepository.writePart },+ }),+ );const service = new WorkflowRunWorkspaceService({} as never,{} as never,@@ -264,15 +272,19 @@ describe('WorkflowRunWorkspaceService conversations', () => {},{ pendingQuestionMessageId: null },);- expect(messagePartRepository.update).toHaveBeenCalledWith(- 'workspace-id',- { id: 'part-id' },- {- toolOutput: expect.objectContaining({- result: { questions: QUESTIONS, status: 'skipped' },- }),- },- );+ const [[closeQuery, [partId, closedToolOutput, expectedStatus]]] =+ messagePartRepository.writePart.mock.calls;++ expect(closeQuery).toContain(`"toolOutput"->'result'->>'status' = $3`);+ expect({+ partId,+ result: JSON.parse(closedToolOutput).result,+ expectedStatus,+ }).toEqual({+ partId: 'part-id',+ result: { questions: QUESTIONS, status: 'skipped' },+ expectedStatus: 'pending',+ });});it('leaves a conversation to the answer holding its claim', async () => {@@ -283,7 +295,7 @@ describe('WorkflowRunWorkspaceService conversations', () => {await endRun(service);- expect(messagePartRepository.update).not.toHaveBeenCalled();+ expect(messagePartRepository.writePart).not.toHaveBeenCalled();});it('still ends the run when its conversations cannot be closed', async () => {diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.tsindex 2a1f0af6197..1cc7de30ec7 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@@ -18,7 +18,7 @@ import { readToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-chatimport { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';-import { skipAwaitingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util';+import { closeOpenToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/close-open-tool-parts.util';import {WorkflowRunStatus,type WorkflowRunState,@@ -287,11 +287,13 @@ export class WorkflowRunWorkspaceService {@WithLock('workflowRunId')async moveStepToRetry({stepId,+ resumedThreadId,error,workflowRunId,workspaceId,}: {stepId: string;+ resumedThreadId?: string;error: string;workflowRunId: string;workspaceId: string;@@ -315,7 +317,7 @@ export class WorkflowRunWorkspaceService {...currentStepInfo,status: StepStatus.PENDING,error,- threadId: undefined,+ threadId: resumedThreadId,history: [...(currentStepInfo?.history ?? []),{@@ -509,13 +511,16 @@ export class WorkflowRunWorkspaceService {);}- // a step posting a call still runs until its executor marks it pending, and an answer may arrive first+ // a step posting a call still runs until its executor marks it pending, and an answer may arrive first;+ // a step is named by its id when it posted to an inbox, or by its conversation on its own runasync isStepStillRunning({stepId,+ threadId,workflowRunId,workspaceId,}: {- stepId: string;+ stepId?: string;+ threadId: string;workflowRunId: string;workspaceId: string;}): Promise<boolean> {@@ -524,9 +529,16 @@ export class WorkflowRunWorkspaceService {workspaceId,});+ const stepInfos = workflowRun.state?.stepInfos ?? {};+ const stepInfo = isDefined(stepId)+ ? stepInfos[stepId]+ : Object.values(stepInfos).find(+ (candidateStepInfo) => candidateStepInfo?.threadId === threadId,+ );+return (workflowRun.status === WorkflowRunStatus.RUNNING &&- workflowRun.state?.stepInfos?.[stepId]?.status === StepStatus.RUNNING+ stepInfo?.status === StepStatus.RUNNING);}@@ -742,7 +754,7 @@ export class WorkflowRunWorkspaceService {continue;}- await skipAwaitingToolParts({+ await closeOpenToolParts({messagePartRepository: this.messagePartRepository,messageId: pendingQuestionMessageId,workspaceId,diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.tsindex 0d04339897b..2d81b81f03e 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@@ -1304,6 +1304,75 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect(conversation.workspaceMemberId).toBeNull();});+ it('keeps a question waiting when it is answered before its step is marked as waiting', async () => {+ mockAgent();+ const { runId, agent, threadId } = await startAskingRun();+ const setStepStatus = (status: string) =>+ global.testDataSource.query(+ `UPDATE "${schema}"."workflowRun" SET state = jsonb_set(state, ARRAY['stepInfos', $2::text, 'status'], to_jsonb($3::text)) WHERE id = $1`,+ [runId, agent.id, status],+ );++ await setStepStatus('RUNNING');++ const earlyAnswer = await answer({ threadId });++ expect(JSON.stringify(earlyAnswer.body.errors)).toContain(+ 'TOOL_CALL_NOT_PENDING',+ );+ expect(await getToolCalls(threadId)).toEqual({+ isWaiting: true,+ calls: [{ toolCallId: 'ask-1', status: 'pending' }],+ });++ await setStepStatus('PENDING');++ expect((await answer({ threadId })).body.errors).toBeUndefined();+ await waitForRun(runId, 'COMPLETED');+ });++ it('retries a step that failed after its answer from the same conversation, without asking again', async () => {+ const executeAgent = jest+ .spyOn(+ getAppProviderByClassName<AgentAsyncExecutorService>(+ 'AgentAsyncExecutorService',+ ),+ 'executeAgent',+ )+ .mockResolvedValueOnce(askingResult)+ .mockRejectedValueOnce(new Error('The model is overloaded'))+ .mockResolvedValueOnce(replyingResult);+ const agent = {+ ...agentStep([]),+ settings: {+ ...agentStep([]).settings,+ errorHandlingOptions: {+ retryOnFailure: { value: 1 },+ continueOnFailure: { value: false },+ },+ },+ } as WorkflowAction;+ const fixture = await createFixture({ steps: [agent] });+ const runId = await runFixture(fixture);+ const pausedRun = await waitForStep(runId, agent.id, 'PENDING');+ const threadId: string = pausedRun.state.stepInfos[agent.id].threadId;++ expect((await answer({ threadId })).body.errors).toBeUndefined();++ const run = await waitForRun(runId, 'COMPLETED');++ expect(run.state.stepInfos[agent.id]).toMatchObject({+ status: 'SUCCESS',+ threadId,+ });+ expect(executeAgent).toHaveBeenCalledTimes(3);+ expect(executeAgent.mock.calls[2][0].messages).toEqual([]);+ expect(await getToolCalls(threadId)).toMatchObject({+ isWaiting: false,+ calls: [{ toolCallId: 'ask-1', status: 'answered' }],+ });+ });+it('still waits on the question when its conversation cannot be surfaced in the inbox', async () => {mockAgent();const recordThreadActivity = jestdiff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.tsindex 418b7a2cdc0..756b0aa9a44 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts@@ -9,6 +9,11 @@ import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chaimport { FeatureFlagKey } from 'twenty-shared/types';import { v4 as uuidv4 } from 'uuid';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';++import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';+import { type WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';+import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';@@ -125,7 +130,8 @@ describe('Send chat message workflow step', () => {`SELECT p."toolCallId", p."toolOutput"FROM "${SCHEMA}"."agentMessagePart" pJOIN "${SCHEMA}"."agentMessage" m ON m.id = p."messageId"- WHERE m."threadId" = $1 AND p."toolName" = 'propose_tool_call'`,+ WHERE m."threadId" = $1 AND p."toolName" = 'propose_tool_call'+ AND p."toolOutput"->'result'->>'status' = 'pending'`,[threadId],);@@ -213,9 +219,8 @@ describe('Send chat message workflow step', () => {});expect(stepResult).toMatchObject({threadId: postedThreadId,- isApproved: true,- approvedToolName: 'update_one_company',- status: 'approved',+ outcome: 'executed',+ toolName: 'update_one_company',arguments: { id: companyId, employees: 30 },});expect(await readEmployees()).toBe(30);@@ -244,14 +249,184 @@ describe('Send chat message workflow step', () => {expect(status).toBe('COMPLETED');expect(stepResult).toMatchObject({- isApproved: false,- approvedToolName: null,- status: 'rejected',+ outcome: 'rejected',feedback: 'Wait for the audit',});expect(await readEmployees()).toBe(10);}, 120000);+ it('reports a conflict when the record changed before approval', async () => {+ const { status, stepResult } = await runWorkflowActionStep({+ name: 'Approve a stale headcount change',+ stepType: 'SEND_CHAT_MESSAGE',+ input: {+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ title: 'Headcount check',+ text: 'Raise the headcount to 25?',+ toolCall: {+ toolName: 'update_one_company',+ arguments: { id: companyId, employees: 25 },+ },+ },+ whileRunning: async ({ workflowRunId, stepId }) => {+ await waitForWorkflowRunStepStatus(workflowRunId, stepId, 'PENDING');+ await global.testDataSource.query(+ `UPDATE "${SCHEMA}"."company" SET employees = 12 WHERE id = $1`,+ [companyId],+ );+ await answerPostedCall({+ workflowRunId,+ stepId,+ response: { decision: 'approve' },+ });+ },+ });++ expect(status).toBe('COMPLETED');+ expect(stepResult).toMatchObject({+ outcome: 'conflict',+ output: { latestValues: expect.objectContaining({ employees: 12 }) },+ });+ expect(await readEmployees()).toBe(12);+ }, 120000);++ it('never runs an approved action twice when recording the answer fails', async () => {+ const agentChatService =+ getAppProviderByClassName<AgentChatService>('AgentChatService');+ const recordToolCallAnswer = jest+ .spyOn(agentChatService, 'recordToolCallAnswer')+ .mockRejectedValueOnce(new Error('Database unavailable'));+ let secondAnswerErrors: string | undefined;+ let partResult: Record<string, unknown> | undefined;++ try {+ const { status } = await runWorkflowActionStep({+ name: 'Approve a headcount change once',+ stepType: 'SEND_CHAT_MESSAGE',+ input: {+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ title: 'Headcount check',+ text: 'Raise the headcount to 25?',+ toolCall: {+ toolName: 'update_one_company',+ arguments: { id: companyId, employees: 25 },+ },+ },+ whileRunning: async ({ workflowRunId, stepId }) => {+ await waitForWorkflowRunStepStatus(+ workflowRunId,+ stepId,+ 'PENDING',+ );++ const [{ threadId }] = await global.testDataSource.query(+ `SELECT state->'stepInfos'->$2->>'threadId' AS "threadId" FROM "${SCHEMA}"."workflowRun" WHERE id = $1`,+ [workflowRunId, stepId],+ );++ postedThreadId = threadId;++ const readCall = async () => {+ const [part] = await global.testDataSource.query(+ `SELECT p."toolCallId", p."toolOutput" FROM "${SCHEMA}"."agentMessagePart" p+ JOIN "${SCHEMA}"."agentMessage" m ON m.id = p."messageId"+ WHERE m."threadId" = $1 AND p."toolName" = 'propose_tool_call'`,+ [threadId],+ );++ return part;+ };+ const { toolCallId } = await readCall();+ const approve = () =>+ answerToolCall({+ toolCall: { threadId, toolCallId },+ response: { decision: 'approve' },+ });++ expect((await approve()).body.errors).toBeDefined();++ secondAnswerErrors = JSON.stringify((await approve()).body.errors);+ partResult = (await readCall()).toolOutput.result;+ },+ });++ expect(status).toBe('FAILED');+ } finally {+ recordToolCallAnswer.mockRestore();+ }++ expect(secondAnswerErrors).toContain('TOOL_CALL_NOT_PENDING');+ expect(partResult).toMatchObject({+ status: 'failed',+ error:+ 'Interrupted before its outcome was recorded. It may or may not have run.',+ });+ expect(await readEmployees()).toBe(25);+ }, 120000);++ it('asks again when a failed run is retried before the action was answered', async () => {+ const { status, stepResult } = await runWorkflowActionStep({+ name: 'Retry a headcount check',+ stepType: 'SEND_CHAT_MESSAGE',+ input: {+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ title: 'Headcount check',+ text: 'Raise the headcount to 25?',+ toolCall: {+ toolName: 'update_one_company',+ arguments: { id: companyId, employees: 25 },+ },+ },+ whileRunning: async ({ workflowRunId, stepId }) => {+ await waitForWorkflowRunStepStatus(workflowRunId, stepId, 'PENDING');++ const [{ threadId }] = await global.testDataSource.query(+ `SELECT state->'stepInfos'->$2->>'threadId' AS "threadId" FROM "${SCHEMA}"."workflowRun" WHERE id = $1`,+ [workflowRunId, stepId],+ );++ postedThreadId = threadId;++ await getAppProviderByClassName<WorkflowRunWorkspaceService>(+ 'WorkflowRunWorkspaceService',+ ).endWorkflowRun({+ workflowRunId,+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ status: WorkflowRunStatus.FAILED,+ error: 'Another branch failed',+ });++ const retry = await workflowGraphqlRequest(+ 'mutation Retry($id: UUID!) { retryWorkflowRun(workflowRunId: $id) { id } }',+ { id: workflowRunId },+ );++ expect(retry.body.errors).toBeUndefined();++ await answerPostedCall({+ workflowRunId,+ stepId,+ response: { decision: 'approve' },+ });+ },+ });++ const proposalStatuses = await global.testDataSource.query(+ `SELECT p."toolOutput"->'result'->>'status' AS status FROM "${SCHEMA}"."agentMessagePart" p+ JOIN "${SCHEMA}"."agentMessage" m ON m.id = p."messageId"+ WHERE m."threadId" = $1 AND p."toolName" = 'propose_tool_call'+ ORDER BY m."createdAt"`,+ [postedThreadId],+ );++ expect(status).toBe('COMPLETED');+ expect(stepResult).toMatchObject({ outcome: 'executed' });+ expect(+ proposalStatuses.map(({ status }: { status: string }) => status),+ ).toEqual(['skipped', 'approved']);+ expect(await readEmployees()).toBe(25);+ }, 120000);+it('closes the call in the inbox when the run is stopped before the answer', async () => {const { status } = await runWorkflowActionStep({name: 'Stop a headcount check',@@ -317,6 +492,27 @@ describe('Send chat message workflow step', () => {expect(stepError).toContain('cannot be proposed');expect(await readEmployees()).toBe(10);}, 120000);++ it('fails the step when its action is missing required arguments', async () => {+ const { stepStatus, stepError } = await runWorkflowActionStep({+ name: 'Propose an incomplete event',+ stepType: 'SEND_CHAT_MESSAGE',+ input: {+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ title: 'Kickoff',+ text: 'Schedule the kickoff?',+ toolCall: {+ toolName: 'create_calendar_event',+ arguments: { title: 'Kickoff' },+ },+ },+ });++ expect(stepStatus).toBe('FAILED');+ expect(stepError).toBe(+ 'The action is missing required arguments: startsAt, endsAt',+ );+ }, 120000);});it('fails a step that runs after the feature flag is turned off', async () => {diff --git a/packages/twenty-shared/src/ai/constants/propose-tool-call-tool-statuses.const.ts b/packages/twenty-shared/src/ai/constants/propose-tool-call-tool-statuses.const.tsnew file mode 100644index 00000000000..80db322b110--- /dev/null+++ b/packages/twenty-shared/src/ai/constants/propose-tool-call-tool-statuses.const.ts@@ -0,0 +1,9 @@+export const PROPOSE_TOOL_CALL_TOOL_STATUSES = [+ 'pending',+ 'running',+ 'approved',+ 'rejected',+ 'failed',+ 'conflict',+ 'skipped',+] as const;diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.tsindex 5b86668b9d1..3cd873f44b8 100644--- a/packages/twenty-shared/src/ai/index.ts+++ b/packages/twenty-shared/src/ai/index.ts@@ -31,6 +31,7 @@ export { DEFAULT_AI_AGENT_MODEL_TIER } from './constants/default-ai-agent-model-export { DEFAULT_AI_CHAT_MODEL_TIER } from './constants/default-ai-chat-model-tier.const';export { JEV_MODEL_ID } from './constants/jev-model-id.const';export { PROPOSE_TOOL_CALL_TOOL_NAME } from './constants/propose-tool-call-tool-name.const';+export { PROPOSE_TOOL_CALL_TOOL_STATUSES } from './constants/propose-tool-call-tool-statuses.const';export { PROPOSED_TOOL_CALL_TEMPLATES } from './constants/proposed-tool-call-templates.const';export { REQUEST_FORM_TOOL_NAME } from './constants/request-form-tool-name.const';export { ToolCategory } from './constants/tool-category.const';diff --git a/packages/twenty-shared/src/ai/types/ProposeToolCallToolStatus.ts b/packages/twenty-shared/src/ai/types/ProposeToolCallToolStatus.tsindex ac23088f2c3..526efa0a83a 100644--- a/packages/twenty-shared/src/ai/types/ProposeToolCallToolStatus.ts+++ b/packages/twenty-shared/src/ai/types/ProposeToolCallToolStatus.ts@@ -1,7 +1,4 @@+import { type PROPOSE_TOOL_CALL_TOOL_STATUSES } from '@/ai/constants/propose-tool-call-tool-statuses.const';+export type ProposeToolCallToolStatus =- | 'pending'- | 'approved'- | 'rejected'- | 'failed'- | 'conflict'- | 'skipped';+ (typeof PROPOSE_TOOL_CALL_TOOL_STATUSES)[number];