Skip to content

The open alternative to Salesforce, designed for AI.

feat(workflow): agent steps talk through the inbox like Send to Inbox (#27287)

Félix Malfait347506df6430
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx
index 60f238068f3..5fb84f7a5a9 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx
@@ -4,7 +4,6 @@ import { CoreObjectNameSingular } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { useApplyAgentChatThreadUpdate } from '@/ai/hooks/useApplyAgentChatThreadUpdate';
-import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
import { useLeaveRemovedAiChatThread } from '@/ai/hooks/useLeaveRemovedAiChatThread';
import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';
import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';
@@ -74,14 +73,7 @@ export const AgentChatThreadRecordOperationsEffect = () => {
const createdThread =
operation.createdRecord as AgentChatThreadRecord;
- // a workflow run's conversation is listed only for the member it is routed to
- if (
- !isDefined(createdThread.workflowRunId) ||
- createdThread.workspaceMemberId ===
- store.get(currentWorkspaceMemberState.atom)?.id
- ) {
- addAgentChatThread(createdThread);
- }
+ addAgentChatThread(createdThread);
return;
}
case 'update-one':
@@ -93,7 +85,7 @@ export const AgentChatThreadRecordOperationsEffect = () => {
applyUpdates(updateInputs.map(toThreadUpdate));
- // An updated chat past the loaded pages moves to the top; reloading keeps workflow run chats out.
+ // An updated chat past the loaded pages moves to the top
const listedThreadIds =
store.get(agentChatThreadListState.atom)?.threadIds ?? [];
diff --git a/packages/twenty-front/src/modules/ai/constants/AgentChatThreadListFilter.ts b/packages/twenty-front/src/modules/ai/constants/AgentChatThreadListFilter.ts
new file mode 100644
index 00000000000..0bfa8d78846
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AgentChatThreadListFilter.ts
@@ -0,0 +1,6 @@
+import { type RecordGqlOperationFilter } from 'twenty-shared/types';
+
+// Deleted chats stay listed for restore
+export const AGENT_CHAT_THREAD_LIST_FILTER: RecordGqlOperationFilter = {
+ or: [{ deletedAt: { is: 'NULL' } }, { deletedAt: { is: 'NOT_NULL' } }],
+};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts
index 0dfe4452b3f..f0ec32b08cf 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts
@@ -1,5 +1,6 @@
import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';
import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';
+import { AGENT_CHAT_THREAD_LIST_FILTER } from '@/ai/constants/AgentChatThreadListFilter';
import { AGENT_CHAT_THREAD_LIST_RECORD_GQL_FIELDS } from '@/ai/constants/AgentChatThreadListRecordGqlFields';
import { useRefreshAgentChatThreadPermissions } from '@/ai/hooks/useRefreshAgentChatThreadPermissions';
import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';
@@ -9,7 +10,6 @@ import { agentChatThreadStreamedParticipantsState } from '@/ai/states/agentChatT
import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';
-import { buildAgentChatThreadListFilter } from '@/ai/utils/buildAgentChatThreadListFilter';
import { getAgentChatThreadLastActivityFieldName } from '@/ai/utils/getAgentChatThreadLastActivityFieldName';
import { getAgentChatThreadParticipantFromRecord } from '@/ai/utils/getAgentChatThreadParticipantFromRecord';
import { getAgentChatUsageFromThread } from '@/ai/utils/getAgentChatUsageFromThread';
@@ -71,10 +71,6 @@ export const useRefreshAgentChatThreads = () => {
const currentWorkspaceMemberId = store.get(
currentWorkspaceMemberState.atom,
)?.id;
- const listFilter = buildAgentChatThreadListFilter({
- chatObjectMetadataItem,
- currentWorkspaceMemberId,
- });
const result = await apolloCoreClient
.query<RecordGqlOperationFindManyResult>({
@@ -86,8 +82,8 @@ export const useRefreshAgentChatThreads = () => {
}),
variables: {
filter: isDefined(threadIdFilter)
- ? { and: [listFilter, threadIdFilter] }
- : listFilter,
+ ? { and: [AGENT_CHAT_THREAD_LIST_FILTER, threadIdFilter] }
+ : AGENT_CHAT_THREAD_LIST_FILTER,
orderBy: [
{
[getAgentChatThreadLastActivityFieldName(
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/buildAgentChatThreadListFilter.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/buildAgentChatThreadListFilter.test.ts
deleted file mode 100644
index d6bf59fb428..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/buildAgentChatThreadListFilter.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
-import { buildAgentChatThreadListFilter } from '@/ai/utils/buildAgentChatThreadListFilter';
-
-const INCLUDE_DELETED_FILTER = {
- or: [{ deletedAt: { is: 'NULL' } }, { deletedAt: { is: 'NOT_NULL' } }],
-};
-
-const buildChatObject = (fieldNames: string[]) =>
- ({
- fields: fieldNames.map((name) => ({ name })),
- }) as Pick<EnrichedObjectMetadataItem, 'fields'>;
-
-describe('buildAgentChatThreadListFilter', () => {
- it('lists deleted chats so they can be restored', () => {
- expect(
- buildAgentChatThreadListFilter({
- chatObjectMetadataItem: buildChatObject(['title']),
- currentWorkspaceMemberId: 'member-id',
- }),
- ).toEqual(INCLUDE_DELETED_FILTER);
- });
-
- it('lists only the workflow run conversations routed to the member', () => {
- expect(
- buildAgentChatThreadListFilter({
- chatObjectMetadataItem: buildChatObject(['title', 'workflowRun']),
- currentWorkspaceMemberId: 'member-id',
- }),
- ).toEqual({
- and: [
- {
- or: [
- { workflowRunId: { is: 'NULL' } },
- { workspaceMemberId: { eq: 'member-id' } },
- ],
- },
- INCLUDE_DELETED_FILTER,
- ],
- });
- });
-
- it('leaves workflow run conversations out without a current member', () => {
- expect(
- buildAgentChatThreadListFilter({
- chatObjectMetadataItem: buildChatObject(['title', 'workflowRun']),
- currentWorkspaceMemberId: undefined,
- }),
- ).toEqual({
- and: [
- { or: [{ workflowRunId: { is: 'NULL' } }] },
- INCLUDE_DELETED_FILTER,
- ],
- });
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts b/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts
deleted file mode 100644
index 2d173adf064..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
-import { type RecordGqlOperationFilter } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
-
-// Deleted chats stay listed for restore; a workflow run's conversation is listed for the member it is routed to.
-export const buildAgentChatThreadListFilter = ({
- chatObjectMetadataItem,
- currentWorkspaceMemberId,
-}: {
- chatObjectMetadataItem: Pick<EnrichedObjectMetadataItem, 'fields'>;
- currentWorkspaceMemberId: string | undefined;
-}): RecordGqlOperationFilter => {
- const includeDeletedFilter: RecordGqlOperationFilter = {
- or: [{ deletedAt: { is: 'NULL' } }, { deletedAt: { is: 'NOT_NULL' } }],
- };
- const canNameWorkflowRun = chatObjectMetadataItem.fields.some(
- ({ name }) => name === 'workflowRun',
- );
-
- if (!canNameWorkflowRun) {
- return includeDeletedFilter;
- }
-
- return {
- and: [
- {
- or: [
- { workflowRunId: { is: 'NULL' } },
- ...(isDefined(currentWorkspaceMemberId)
- ? [{ workspaceMemberId: { eq: currentWorkspaceMemberId } }]
- : []),
- ],
- },
- includeDeletedFilter,
- ],
- };
-};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsx
index 11f269068ba..37fe236246c 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowAiAgentPromptTab.tsx
@@ -5,9 +5,11 @@ import { agentResponseSchemaToOutputSchema } from '@/ai/utils/agentResponseSchem
import { createDefaultOutputSchemaField } from '@/ai/utils/createDefaultOutputSchemaField';
import { fieldsToSchema } from '@/ai/utils/fieldsToSchema';
import { schemaToFields } from '@/ai/utils/schemaToFields';
+import { FormSingleRecordPicker } from '@/object-record/record-field/ui/form-types/components/FormSingleRecordPicker';
import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
import { type WorkflowAiAgentAction } from '@/workflow/types/Workflow';
+import { WorkflowConversationFields } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowConversationFields';
import { WorkflowOutputSchemaBuilder } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowOutputSchemaBuilder';
import { workflowAiAgentActionAgentState } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/states/workflowAiAgentActionAgentState';
import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
@@ -18,6 +20,8 @@ import {
type AgentResponseSchema,
type ModelConfiguration,
} from 'twenty-shared/ai';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
+import { type WorkflowConversation } from 'twenty-shared/workflow';
import { useDebouncedCallback } from 'use-debounce';
import {
UpdateOneAgentDocument,
@@ -31,6 +35,10 @@ type WorkflowAiAgentPromptTabProps = {
onPromptChange: (value: string) => void;
humanInputInstructions: string;
onHumanInputInstructionsChange: (value: string) => void;
+ recipientWorkspaceMemberId: string | undefined;
+ onRecipientChange: (workspaceMemberId: string | undefined) => void;
+ conversation: WorkflowConversation | undefined;
+ onConversationChange: (conversation: WorkflowConversation) => void;
onActionUpdate?: (action: WorkflowAiAgentAction) => void;
};
@@ -41,6 +49,10 @@ export const WorkflowAiAgentPromptTab = ({
onPromptChange,
humanInputInstructions,
onHumanInputInstructionsChange,
+ recipientWorkspaceMemberId,
+ onRecipientChange,
+ conversation,
+ onConversationChange,
onActionUpdate,
}: WorkflowAiAgentPromptTabProps) => {
const [workflowAiAgentActionAgent, setWorkflowAiAgentActionAgent] =
@@ -161,6 +173,27 @@ export const WorkflowAiAgentPromptTab = ({
readonly={readonly}
/>
+ <FormSingleRecordPicker
+ label={t`Recipient`}
+ objectNameSingulars={[CoreObjectNameSingular.WorkspaceMember]}
+ defaultValue={recipientWorkspaceMemberId}
+ onChange={(workspaceMemberId) =>
+ onRecipientChange(workspaceMemberId ?? undefined)
+ }
+ disabled={readonly}
+ testId="workflow-edit-action-ai-agent-recipient"
+ VariablePicker={WorkflowVariablePicker}
+ />
+
+ <WorkflowConversationFields
+ dropdownId={`workflow-ai-agent-conversation-${action.id}`}
+ conversation={conversation}
+ defaultScope="STEP"
+ description={t`With the recipient, or the workflow creator when empty. It stays out of their inbox until the agent needs them.`}
+ readonly={readonly}
+ onChange={onConversationChange}
+ />
+
<SettingsAgentModelCapabilities
selectedModelId={agent.modelId}
modelConfiguration={agent.modelConfiguration || {}}
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx
index dc65d262b74..326cd3a9ab9 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowEditActionAiAgent.tsx
@@ -21,6 +21,7 @@ import { useLingui } from '@lingui/react/macro';
import { useEffect, useState } from 'react';
import { SettingsPath } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
+import { type WorkflowConversation } from 'twenty-shared/workflow';
import { IconLock, IconSparkles } from 'twenty-ui/icon';
import { themeCssVariables } from 'twenty-ui/theme';
import { useDebouncedCallback } from 'use-debounce';
@@ -79,9 +80,15 @@ export const WorkflowEditActionAiAgent = ({
const [humanInputInstructions, setHumanInputInstructions] = useState(
action.settings.input.humanInputInstructions ?? '',
);
+ const [recipientWorkspaceMemberId, setRecipientWorkspaceMemberId] = useState(
+ action.settings.input.workspaceMemberId,
+ );
+ const [conversation, setConversation] = useState(
+ action.settings.input.conversation,
+ );
- // saves both texts from the latest render, so editing one does not drop a pending edit of the other
- const saveTexts = useDebouncedCallback(() => {
+ // saves every field from the latest render, so editing one does not drop a pending edit of another
+ const saveInput = useDebouncedCallback(() => {
if (actionOptions.readonly === true) {
return;
}
@@ -94,6 +101,8 @@ export const WorkflowEditActionAiAgent = ({
...action.settings.input,
prompt,
humanInputInstructions,
+ workspaceMemberId: recipientWorkspaceMemberId,
+ conversation,
},
},
});
@@ -101,12 +110,22 @@ export const WorkflowEditActionAiAgent = ({
const handleAgentPromptChange = (newPrompt: string) => {
setPrompt(newPrompt);
- saveTexts();
+ saveInput();
};
const handleHumanInputInstructionsChange = (newInstructions: string) => {
setHumanInputInstructions(newInstructions);
- saveTexts();
+ saveInput();
+ };
+
+ const handleRecipientChange = (workspaceMemberId: string | undefined) => {
+ setRecipientWorkspaceMemberId(workspaceMemberId);
+ saveInput();
+ };
+
+ const handleConversationChange = (nextConversation: WorkflowConversation) => {
+ setConversation(nextConversation);
+ saveInput();
};
const tabs: SingleTabProps[] = [
@@ -215,6 +234,10 @@ export const WorkflowEditActionAiAgent = ({
onHumanInputInstructionsChange={
handleHumanInputInstructionsChange
}
+ recipientWorkspaceMemberId={recipientWorkspaceMemberId}
+ onRecipientChange={handleRecipientChange}
+ conversation={conversation}
+ onConversationChange={handleConversationChange}
onActionUpdate={
actionOptions.readonly === true
? undefined
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowConversationFields.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowConversationFields.tsx
new file mode 100644
index 00000000000..a132d5851a7
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowConversationFields.tsx
@@ -0,0 +1,71 @@
+import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
+import { Select } from '@/ui/input/components/Select';
+import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
+import { useLingui } from '@lingui/react/macro';
+import {
+ type WorkflowConversation,
+ type WorkflowConversationScope,
+} from 'twenty-shared/workflow';
+
+type WorkflowConversationFieldsProps = {
+ dropdownId: string;
+ conversation: WorkflowConversation | undefined;
+ defaultScope: WorkflowConversationScope;
+ description?: string;
+ readonly?: boolean;
+ onChange: (conversation: WorkflowConversation) => void;
+};
+
+export const WorkflowConversationFields = ({
+ dropdownId,
+ conversation,
+ defaultScope,
+ description,
+ readonly,
+ onChange,
+}: WorkflowConversationFieldsProps) => {
+ const { t } = useLingui();
+ const scope = conversation?.scope ?? defaultScope;
+
+ const scopeOptions: { label: string; value: WorkflowConversationScope }[] = [
+ { label: t`One per run`, value: 'RUN' },
+ { label: t`A new one each time the step runs`, value: 'STEP' },
+ { label: t`Shared by key, across runs`, value: 'KEY' },
+ ];
+
+ const handleScopeChange = (nextScope: WorkflowConversationScope) => {
+ onChange(
+ nextScope === 'KEY'
+ ? { scope: nextScope, key: conversation?.key ?? '' }
+ : { scope: nextScope },
+ );
+ };
+
+ return (
+ <>
+ <Select
+ dropdownId={dropdownId}
+ label={t`Conversation`}
+ description={
+ description ??
+ t`Which conversation with the recipient this step writes to`
+ }
+ fullWidth
+ disabled={readonly}
+ value={scope}
+ options={scopeOptions}
+ onChange={handleScopeChange}
+ />
+ {scope === 'KEY' && (
+ <FormTextFieldInput
+ label={t`Conversation key`}
+ placeholder={t`Steps of this workflow sharing a key write to the same conversation`}
+ readonly={readonly}
+ defaultValue={conversation?.key}
+ onChange={(key) => onChange({ scope: 'KEY', key })}
+ VariablePicker={WorkflowVariablePicker}
+ />
+ )}
+ </>
+ );
+};
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.tsx
index 57e2b8bc09d..21be92e2a34 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
@@ -6,12 +6,14 @@ import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/Gene
import { type WorkflowSendChatMessageAction } from '@/workflow/types/Workflow';
import { WorkflowStepBody } from '@/workflow/workflow-steps/components/WorkflowStepBody';
import { WorkflowStepFooter } from '@/workflow/workflow-steps/components/WorkflowStepFooter';
+import { WorkflowConversationFields } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowConversationFields';
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 { CoreObjectNameSingular } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
+import { type WorkflowConversation } from 'twenty-shared/workflow';
import { useDebouncedCallback } from 'use-debounce';
type SendChatMessageFormData =
@@ -75,6 +77,10 @@ export const WorkflowEditActionSendChatMessage = ({
updateFormData({ ...formData, [fieldName]: value });
};
+ const handleConversationChange = (conversation: WorkflowConversation) => {
+ updateFormData({ ...formData, conversation });
+ };
+
const handleToolCallChange = (toolCall: SendChatMessageToolCall | null) => {
updateFormData({ ...formData, toolCall: toolCall ?? undefined });
};
@@ -131,6 +137,13 @@ export const WorkflowEditActionSendChatMessage = ({
testId="workflow-edit-action-send-chat-message-recipient"
VariablePicker={WorkflowVariablePicker}
/>
+ <WorkflowConversationFields
+ dropdownId={`workflow-send-chat-message-conversation-${action.id}`}
+ conversation={formData.conversation}
+ defaultScope="RUN"
+ readonly={actionOptions.readonly}
+ onChange={handleConversationChange}
+ />
<FormTextFieldInput
label={t`Conversation title`}
placeholder={t`Defaults to the step name`}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.ts
index e4ef4b916e9..d0ff7dd21ec 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.ts
@@ -7,6 +7,11 @@ import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command
import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
import { LEGACY_CHAT_THREAD_OWNER_FIELD_UNIVERSAL_IDENTIFIER } from 'src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-owner-field-universal-identifier.constant';
+import {
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER,
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_INDEX_UNIVERSAL_IDENTIFIER,
+ LEGACY_WORKFLOW_RUN_AGENT_CHAT_THREADS_FIELD_UNIVERSAL_IDENTIFIER,
+} from 'src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-workflow-run-universal-identifiers.constant';
import { getStandardFlatEntitiesToCreateOrThrow } from 'src/database/commands/upgrade-version-command/2-10/utils/get-standard-flat-entities-to-create-or-throw.util';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
@@ -18,12 +23,12 @@ import { computeTwentyStandardApplicationAllFlatEntityMaps } from 'src/engine/wo
import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
const WORKFLOW_RUN_THREAD_FIELD_UNIVERSAL_IDENTIFIERS = [
- STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier,
- STANDARD_OBJECTS.workflowRun.fields.agentChatThreads.universalIdentifier,
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER,
+ LEGACY_WORKFLOW_RUN_AGENT_CHAT_THREADS_FIELD_UNIVERSAL_IDENTIFIER,
];
const WORKFLOW_RUN_THREAD_INDEX_UNIVERSAL_IDENTIFIERS = [
- STANDARD_OBJECTS.agentChatThread.indexes.workflowRunIndex.universalIdentifier,
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_INDEX_UNIVERSAL_IDENTIFIER,
];
// A workflow agent step now records each execution as a chat thread owned by
@@ -86,18 +91,30 @@ export class AddWorkflowRunToChatThreadsCommand extends ProvisionedWorkspaceComm
twentyStandardApplicationId: twentyStandardFlatApplication.id,
});
- const fieldsToCreate =
- getStandardFlatEntitiesToCreateOrThrow<FlatFieldMetadata>({
- standardFlatEntityMaps: standardAllFlatEntityMaps.flatFieldMetadataMaps,
- existingFlatEntityMaps: flatFieldMetadataMaps,
- universalIdentifiers: WORKFLOW_RUN_THREAD_FIELD_UNIVERSAL_IDENTIFIERS,
- });
- const indexesToCreate =
- getStandardFlatEntitiesToCreateOrThrow<FlatIndexMetadata>({
- standardFlatEntityMaps: standardAllFlatEntityMaps.flatIndexMaps,
- existingFlatEntityMaps: flatIndexMaps,
- universalIdentifiers: WORKFLOW_RUN_THREAD_INDEX_UNIVERSAL_IDENTIFIERS,
- });
+ // Preserves the shipped 2.44 upgrade path after 2.46 dropped the run link
+ // from the standard objects: a workspace jumping past 2.44 skips linking
+ // threads to runs, and 2.46 leaves every workspace without the link.
+ const isRunLinkStandard = isDefined(
+ standardAllFlatEntityMaps.flatFieldMetadataMaps.byUniversalIdentifier[
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER
+ ],
+ );
+
+ const fieldsToCreate = isRunLinkStandard
+ ? getStandardFlatEntitiesToCreateOrThrow<FlatFieldMetadata>({
+ standardFlatEntityMaps:
+ standardAllFlatEntityMaps.flatFieldMetadataMaps,
+ existingFlatEntityMaps: flatFieldMetadataMaps,
+ universalIdentifiers: WORKFLOW_RUN_THREAD_FIELD_UNIVERSAL_IDENTIFIERS,
+ })
+ : [];
+ const indexesToCreate = isRunLinkStandard
+ ? getStandardFlatEntitiesToCreateOrThrow<FlatIndexMetadata>({
+ standardFlatEntityMaps: standardAllFlatEntityMaps.flatIndexMaps,
+ existingFlatEntityMaps: flatIndexMaps,
+ universalIdentifiers: WORKFLOW_RUN_THREAD_INDEX_UNIVERSAL_IDENTIFIERS,
+ })
+ : [];
const ownerField =
flatFieldMetadataMaps.byUniversalIdentifier[
@@ -110,7 +127,7 @@ export class AddWorkflowRunToChatThreadsCommand extends ProvisionedWorkspaceComm
if (options.dryRun ?? false) {
this.logger.log(
- `[DRY RUN] Would create ${fieldsToCreate.length} field(s) and ${indexesToCreate.length} index(es), update ${fieldsToUpdate.length} field(s), then make chat threads inherit readability from their run for workspace ${workspaceId}`,
+ `[DRY RUN] Would create ${fieldsToCreate.length} field(s) and ${indexesToCreate.length} index(es), update ${fieldsToUpdate.length} field(s)${isRunLinkStandard ? ', then make chat threads inherit readability from their run' : ''} for workspace ${workspaceId}`,
);
return;
@@ -139,6 +156,10 @@ export class AddWorkflowRunToChatThreadsCommand extends ProvisionedWorkspaceComm
});
}
+ if (!isRunLinkStandard) {
+ return;
+ }
+
// verify-common-record-sharing has already refused SYSTEM threads, so
// anything but PRIVATE here is a re-run
if (threadObject.readability !== MetadataReadability.PRIVATE) {
@@ -156,8 +177,7 @@ export class AddWorkflowRunToChatThreadsCommand extends ProvisionedWorkspaceComm
...threadObject,
readability: MetadataReadability.INHERITED,
readabilityParentFieldUniversalIdentifiers: [
- STANDARD_OBJECTS.agentChatThread.fields.workflowRun
- .universalIdentifier,
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER,
],
},
];
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790772993322-record-pending-form-conversations.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790772993322-record-pending-form-conversations.command.ts
index 4b65b456cd3..89506c27a0a 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790772993322-record-pending-form-conversations.command.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790772993322-record-pending-form-conversations.command.ts
@@ -1,11 +1,11 @@
import { randomUUID } from 'node:crypto';
import { Command } from 'nest-commander';
-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
import { isDefined } from 'twenty-shared/utils';
import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';
import { AgentHistoryUpgradeStorageService } from 'src/database/commands/agent-history/agent-history-upgrade-storage.service';
+import { LEGACY_CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER } from 'src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-workflow-run-universal-identifiers.constant';
import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
@@ -58,8 +58,7 @@ export class RecordPendingFormConversationsCommand extends ProvisionedWorkspaceC
if (
!isDefined(
flatFieldMetadataMaps.byUniversalIdentifier[
- STANDARD_OBJECTS.agentChatThread.fields.workflowRun
- .universalIdentifier
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER
],
)
) {
@@ -101,8 +100,9 @@ export class RecordPendingFormConversationsCommand extends ProvisionedWorkspaceC
});
const workflowRunRepository =
getRepository<WorkflowRunWorkspaceEntity>('workflowRun');
- const threadRepository =
- getRepository<AgentChatThreadWorkspaceEntity>('agentChatThread');
+ const threadRepository = getRepository<
+ AgentChatThreadWorkspaceEntity & { workflowRunId: string | null }
+ >('agentChatThread');
const turnRepository = getRepository<AgentTurnWorkspaceEntity>('agentTurn');
const messageRepository =
getRepository<AgentMessageWorkspaceEntity>('agentMessage');
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-workflow-run-universal-identifiers.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-workflow-run-universal-identifiers.constant.ts
new file mode 100644
index 00000000000..c03bbf256f1
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-workflow-run-universal-identifiers.constant.ts
@@ -0,0 +1,10 @@
+// Pinned so the commands still build once the standard objects drop the run
+// link, which 2.46 removes from chat threads
+export const LEGACY_CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER =
+ '2187f4c6-bff3-4b80-8585-c82965faf79b';
+
+export const LEGACY_WORKFLOW_RUN_AGENT_CHAT_THREADS_FIELD_UNIVERSAL_IDENTIFIER =
+ 'c664a2e7-ef64-4597-9cdf-ded3eae85ae4';
+
+export const LEGACY_CHAT_THREAD_WORKFLOW_RUN_INDEX_UNIVERSAL_IDENTIFIER =
+ 'cc9f8c37-a1ad-4d8d-8e27-894c2cf01a3b';
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts
index a58e6a5a86e..32f7520d3f0 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts
@@ -7,6 +7,7 @@ import { BackfillAgentChatThreadInboxStateCommand } from 'src/database/commands/
import { AddAiChatInboxCommandMenuItemsCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019633-add-ai-chat-inbox-command-menu-items.command';
import { AllowAiChatInboxCommandsOnSeveralChatsCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791009973891-allow-ai-chat-inbox-commands-on-several-chats.command';
import { MakeAgentChatThreadParticipantsPrivateCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791056679663-make-agent-chat-thread-participants-private.command';
+import { DropWorkflowRunFromChatThreadsCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791208395308-drop-workflow-run-from-chat-threads.command';
import { BackfillAgentAndWorkflowIsSystemCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791130332894-backfill-agent-and-workflow-is-system.command';
import { ScheduleAgentChatThreadSnoozeEndsCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791093059050-schedule-agent-chat-thread-snooze-ends.command';
import { UnpinNewAiChatCommandMenuItemCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019634-unpin-new-ai-chat-command-menu-item.command';
@@ -33,6 +34,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
ScheduleAgentChatThreadSnoozeEndsCommand,
BackfillAgentAndWorkflowIsSystemCommand,
TurnHiddenAgentMessagesIntoSystemMessagesCommand,
+ DropWorkflowRunFromChatThreadsCommand,
],
})
export class V2_46_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791208395308-drop-workflow-run-from-chat-threads.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791208395308-drop-workflow-run-from-chat-threads.command.ts
new file mode 100644
index 00000000000..f70530e7ddc
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791208395308-drop-workflow-run-from-chat-threads.command.ts
@@ -0,0 +1,237 @@
+import { Command } from 'nest-commander';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { MetadataReadability } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { type EntityManager } from 'typeorm';
+
+import { AgentHistoryUpgradeStorageService } from 'src/database/commands/agent-history/agent-history-upgrade-storage.service';
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import { ApplicationService } from 'src/engine/core-modules/application/application.service';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
+import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
+import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';
+
+// Kept as literals because the entries they used to name have been removed
+// from the standard objects in the same change.
+const CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER =
+ '2187f4c6-bff3-4b80-8585-c82965faf79b';
+const WORKFLOW_RUN_AGENT_CHAT_THREADS_FIELD_UNIVERSAL_IDENTIFIER =
+ 'c664a2e7-ef64-4597-9cdf-ded3eae85ae4';
+const CHAT_THREAD_WORKFLOW_RUN_INDEX_UNIVERSAL_IDENTIFIER =
+ 'cc9f8c37-a1ad-4d8d-8e27-894c2cf01a3b';
+
+// A call still waiting in a run's conversation gets the step it waits for,
+// which is how an answer or a wait outcome finds its step once the thread no
+// longer names its run.
+const stampPendingCallsWithTheirStep = async ({
+ manager,
+ workspaceId,
+}: {
+ manager: EntityManager;
+ workspaceId: string;
+}): Promise<number> => {
+ const schema = escapeIdentifier(getWorkspaceSchemaName(workspaceId));
+
+ const stamped: { id: string }[] = await manager.query(
+ `UPDATE ${schema}."agentMessagePart" part
+ SET "toolOutput" = part."toolOutput" || jsonb_build_object(
+ 'workflowStep',
+ jsonb_build_object('workflowRunId', thread."workflowRunId", 'stepId', step.key)
+ )
+ FROM ${schema}."agentMessage" message
+ JOIN ${schema}."agentChatThread" thread ON thread.id = message."threadId"
+ JOIN ${schema}."workflowRun" run ON run.id = thread."workflowRunId"
+ CROSS JOIN LATERAL jsonb_each(COALESCE(run.state -> 'stepInfos', '{}'::jsonb)) AS step(key, value)
+ WHERE part."messageId" = message.id
+ AND step.value ->> 'threadId' = thread.id::text
+ AND jsonb_typeof(part."toolOutput") = 'object'
+ AND part."toolOutput" -> 'result' ->> 'status' = 'pending'
+ AND NOT part."toolOutput" ? 'workflowStep'
+ RETURNING part.id`,
+ );
+
+ return stamped.length;
+};
+
+// A conversation an agent step held now belongs to the member it was routed
+// to, as every other conversation does, rather than to its run. The calls it
+// still waits on keep resuming their step, and threads read only through their
+// own grants again.
+@RegisteredWorkspaceCommand('2.46.0', 1791208395308)
+@Command({
+ name: 'upgrade:2-46:drop-workflow-run-from-chat-threads',
+ description:
+ 'Stop linking chat threads to workflow runs: pending calls name their step, threads become PRIVATE and the run link is dropped',
+})
+export class DropWorkflowRunFromChatThreadsCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly applicationService: ApplicationService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
+ private readonly storage: AgentHistoryUpgradeStorageService,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.up(args);
+ }
+
+ async up({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {
+ const { flatObjectMetadataMaps, flatFieldMetadataMaps, flatIndexMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatObjectMetadataMaps',
+ 'flatFieldMetadataMaps',
+ 'flatIndexMaps',
+ ]);
+
+ const threadObject =
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.agentChatThread.universalIdentifier
+ ];
+
+ if (!isDefined(threadObject)) {
+ this.logger.log(
+ `agentChatThread object not found for workspace ${workspaceId}, skipping`,
+ );
+
+ return;
+ }
+
+ const fieldsToDelete = [
+ CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER,
+ WORKFLOW_RUN_AGENT_CHAT_THREADS_FIELD_UNIVERSAL_IDENTIFIER,
+ ]
+ .map((universalIdentifier) =>
+ findFlatEntityByUniversalIdentifier<FlatFieldMetadata>({
+ flatEntityMaps: flatFieldMetadataMaps,
+ universalIdentifier,
+ }),
+ )
+ .filter(isDefined);
+ const indexesToDelete = [
+ findFlatEntityByUniversalIdentifier<FlatIndexMetadata>({
+ flatEntityMaps: flatIndexMaps,
+ universalIdentifier:
+ CHAT_THREAD_WORKFLOW_RUN_INDEX_UNIVERSAL_IDENTIFIER,
+ }),
+ ].filter(isDefined);
+ const isPrivate =
+ threadObject.readability === MetadataReadability.PRIVATE &&
+ !isDefined(threadObject.readabilityParentFieldUniversalIdentifiers);
+
+ if (
+ isPrivate &&
+ fieldsToDelete.length === 0 &&
+ indexesToDelete.length === 0
+ ) {
+ this.logger.log(
+ `Chat threads are not linked to workflow runs in workspace ${workspaceId}, skipping`,
+ );
+
+ return;
+ }
+
+ if (options.dryRun ?? false) {
+ this.logger.log(
+ `[DRY RUN] Would stamp pending calls, make chat threads PRIVATE and drop ${fieldsToDelete.length} field(s) and ${indexesToDelete.length} index(es) for workspace ${workspaceId}`,
+ );
+
+ return;
+ }
+
+ const stampedCount = fieldsToDelete.some(
+ ({ universalIdentifier }) =>
+ universalIdentifier ===
+ CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER,
+ )
+ ? await this.storage.run(workspaceId, ({ manager }) =>
+ stampPendingCallsWithTheirStep({ manager, workspaceId }),
+ )
+ : 0;
+
+ const { twentyStandardFlatApplication } =
+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId },
+ );
+ const applicationUniversalIdentifier =
+ twentyStandardFlatApplication.universalIdentifier;
+
+ // Readability names the parent field, so it lets go of it before the field goes
+ if (!isPrivate) {
+ await this.runMigration({
+ workspaceId,
+ applicationUniversalIdentifier,
+ allFlatEntityOperationByMetadataName: {
+ objectMetadata: {
+ flatEntityToCreate: [],
+ flatEntityToDelete: [],
+ flatEntityToUpdate: [
+ {
+ ...threadObject,
+ readability: MetadataReadability.PRIVATE,
+ readabilityParentFieldUniversalIdentifiers: null,
+ },
+ ],
+ },
+ },
+ });
+ }
+
+ if (fieldsToDelete.length + indexesToDelete.length > 0) {
+ await this.runMigration({
+ workspaceId,
+ applicationUniversalIdentifier,
+ allFlatEntityOperationByMetadataName: {
+ index: {
+ flatEntityToCreate: [],
+ flatEntityToDelete: indexesToDelete,
+ flatEntityToUpdate: [],
+ },
+ fieldMetadata: {
+ flatEntityToCreate: [],
+ flatEntityToDelete: fieldsToDelete,
+ flatEntityToUpdate: [],
+ },
+ },
+ });
+ }
+
+ this.logger.log(
+ `Workspace ${workspaceId}: stamped ${stampedCount} pending call(s), made chat threads PRIVATE and dropped their workflow run link`,
+ );
+ }
+
+ async down(_args: RunOnWorkspaceArgs): Promise<void> {
+ // The standard objects no longer declare the run link, so it cannot be
+ // recreated, and the stamped calls resume their step without it.
+ }
+
+ private async runMigration(
+ args: Omit<
+ Parameters<
+ WorkspaceMigrationValidateBuildAndRunService['validateBuildAndRunLegacyWorkspaceMigration']
+ >[0],
+ 'isSystemBuild'
+ >,
+ ): Promise<void> {
+ const result =
+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(
+ { ...args, isSystemBuild: true },
+ );
+
+ if (result.status === 'fail') {
+ throw new Error(
+ `Failed to drop the workflow run link from chat threads for workspace ${args.workspaceId}: ${JSON.stringify(result, null, 2)}`,
+ );
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-delete-many.pre-query.hook.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-delete-many.pre-query.hook.ts
deleted file mode 100644
index 0cb156a97f8..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-delete-many.pre-query.hook.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { type WorkspacePreQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/interfaces/workspace-query-hook.interface';
-import { type DeleteManyResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
-
-import { WorkspaceQueryHook } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/decorators/workspace-query-hook.decorator';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { excludeWorkflowRunThreadsFromFilter } from 'src/engine/metadata-modules/ai/ai-chat/utils/exclude-workflow-run-threads-from-filter.util';
-
-@WorkspaceQueryHook(`agentChatThread.deleteMany`)
-export class AgentChatThreadDeleteManyPreQueryHook implements WorkspacePreQueryHookInstance {
- async execute(
- _authContext: WorkspaceAuthContext,
- _objectName: string,
- payload: DeleteManyResolverArgs,
- ): Promise<DeleteManyResolverArgs> {
- return {
- ...payload,
- filter: excludeWorkflowRunThreadsFromFilter(payload.filter),
- };
- }
-}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-delete-one.pre-query.hook.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-delete-one.pre-query.hook.ts
deleted file mode 100644
index e350b56ad2a..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-delete-one.pre-query.hook.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { type WorkspacePreQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/interfaces/workspace-query-hook.interface';
-import { type DeleteOneResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
-
-import { WorkspaceQueryHook } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/decorators/workspace-query-hook.decorator';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service';
-
-@WorkspaceQueryHook(`agentChatThread.deleteOne`)
-export class AgentChatThreadDeleteOnePreQueryHook implements WorkspacePreQueryHookInstance {
- constructor(
- private readonly threadLifecycleService: AgentChatThreadLifecycleService,
- ) {}
-
- async execute(
- authContext: WorkspaceAuthContext,
- _objectName: string,
- payload: DeleteOneResolverArgs,
- ): Promise<DeleteOneResolverArgs> {
- await this.threadLifecycleService.assertThreadIsNotWorkflowRunThread({
- workspaceId: authContext.workspace.id,
- threadId: payload.id,
- });
-
- return payload;
- }
-}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-destroy-many.pre-query.hook.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-destroy-many.pre-query.hook.ts
deleted file mode 100644
index 4d78028795c..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-destroy-many.pre-query.hook.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { type WorkspacePreQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/interfaces/workspace-query-hook.interface';
-import { type DestroyManyResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
-
-import { WorkspaceQueryHook } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/decorators/workspace-query-hook.decorator';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { excludeWorkflowRunThreadsFromFilter } from 'src/engine/metadata-modules/ai/ai-chat/utils/exclude-workflow-run-threads-from-filter.util';
-
-@WorkspaceQueryHook(`agentChatThread.destroyMany`)
-export class AgentChatThreadDestroyManyPreQueryHook implements WorkspacePreQueryHookInstance {
- async execute(
- _authContext: WorkspaceAuthContext,
- _objectName: string,
- payload: DestroyManyResolverArgs,
- ): Promise<DestroyManyResolverArgs> {
- return {
- ...payload,
- filter: excludeWorkflowRunThreadsFromFilter(payload.filter),
- };
- }
-}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-destroy-one.pre-query.hook.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-destroy-one.pre-query.hook.ts
deleted file mode 100644
index a30cca5f779..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-destroy-one.pre-query.hook.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { type WorkspacePreQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/interfaces/workspace-query-hook.interface';
-import { type DestroyOneResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
-
-import { WorkspaceQueryHook } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/decorators/workspace-query-hook.decorator';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service';
-
-@WorkspaceQueryHook(`agentChatThread.destroyOne`)
-export class AgentChatThreadDestroyOnePreQueryHook implements WorkspacePreQueryHookInstance {
- constructor(
- private readonly threadLifecycleService: AgentChatThreadLifecycleService,
- ) {}
-
- async execute(
- authContext: WorkspaceAuthContext,
- _objectName: string,
- payload: DestroyOneResolverArgs,
- ): Promise<DestroyOneResolverArgs> {
- await this.threadLifecycleService.assertThreadIsNotWorkflowRunThread({
- workspaceId: authContext.workspace.id,
- threadId: payload.id,
- });
-
- return payload;
- }
-}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-query-hook.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-query-hook.module.ts
index 8d1e13b112c..4829c3a79cf 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-query-hook.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-query-hook.module.ts
@@ -4,27 +4,15 @@ import { AgentChatThreadLifecycleModule } from 'src/engine/metadata-modules/ai/a
import { AgentChatThreadCreateManyPostQueryHook } from 'src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-create-many.post-query.hook';
import { AgentChatThreadCreateOnePostQueryHook } from 'src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-create-one.post-query.hook';
import { AgentChatThreadDeleteManyPostQueryHook } from 'src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-delete-many.post-query.hook';
-import { AgentChatThreadDeleteManyPreQueryHook } from 'src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-delete-many.pre-query.hook';
import { AgentChatThreadDeleteOnePostQueryHook } from 'src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-delete-one.post-query.hook';
-import { AgentChatThreadDeleteOnePreQueryHook } from 'src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-delete-one.pre-query.hook';
-import { AgentChatThreadDestroyManyPreQueryHook } from 'src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-destroy-many.pre-query.hook';
-import { AgentChatThreadDestroyOnePreQueryHook } from 'src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-destroy-one.pre-query.hook';
-import { AgentChatThreadUpdateManyPreQueryHook } from 'src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-update-many.pre-query.hook';
-import { AgentChatThreadUpdateOnePreQueryHook } from 'src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-update-one.pre-query.hook';
@Module({
imports: [AgentChatThreadLifecycleModule],
providers: [
AgentChatThreadCreateOnePostQueryHook,
AgentChatThreadCreateManyPostQueryHook,
- AgentChatThreadUpdateOnePreQueryHook,
- AgentChatThreadUpdateManyPreQueryHook,
- AgentChatThreadDeleteOnePreQueryHook,
- AgentChatThreadDeleteManyPreQueryHook,
AgentChatThreadDeleteOnePostQueryHook,
AgentChatThreadDeleteManyPostQueryHook,
- AgentChatThreadDestroyOnePreQueryHook,
- AgentChatThreadDestroyManyPreQueryHook,
],
})
export class AgentChatThreadQueryHookModule {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-update-many.pre-query.hook.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-update-many.pre-query.hook.ts
deleted file mode 100644
index 9c6faba4680..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-update-many.pre-query.hook.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { type WorkspacePreQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/interfaces/workspace-query-hook.interface';
-import { type UpdateManyResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
-
-import { WorkspaceQueryHook } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/decorators/workspace-query-hook.decorator';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { excludeWorkflowRunThreadsFromFilter } from 'src/engine/metadata-modules/ai/ai-chat/utils/exclude-workflow-run-threads-from-filter.util';
-
-@WorkspaceQueryHook(`agentChatThread.updateMany`)
-export class AgentChatThreadUpdateManyPreQueryHook implements WorkspacePreQueryHookInstance {
- async execute(
- _authContext: WorkspaceAuthContext,
- _objectName: string,
- payload: UpdateManyResolverArgs,
- ): Promise<UpdateManyResolverArgs> {
- return {
- ...payload,
- filter: excludeWorkflowRunThreadsFromFilter(payload.filter),
- };
- }
-}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-update-one.pre-query.hook.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-update-one.pre-query.hook.ts
deleted file mode 100644
index 75b27def29f..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/query-hooks/agent-chat-thread-update-one.pre-query.hook.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { type WorkspacePreQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/interfaces/workspace-query-hook.interface';
-import { type UpdateOneResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
-
-import { WorkspaceQueryHook } from 'src/engine/api/graphql/workspace-query-runner/workspace-query-hook/decorators/workspace-query-hook.decorator';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service';
-
-@WorkspaceQueryHook(`agentChatThread.updateOne`)
-export class AgentChatThreadUpdateOnePreQueryHook implements WorkspacePreQueryHookInstance {
- constructor(
- private readonly threadLifecycleService: AgentChatThreadLifecycleService,
- ) {}
-
- async execute(
- authContext: WorkspaceAuthContext,
- _objectName: string,
- payload: UpdateOneResolverArgs,
- ): Promise<UpdateOneResolverArgs> {
- await this.threadLifecycleService.assertThreadIsNotWorkflowRunThread({
- workspaceId: authContext.workspace.id,
- threadId: payload.id,
- });
-
- return payload;
- }
-}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
index 56629f991e4..1899e2e419a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
@@ -37,11 +37,12 @@ describe('AgentChatStreamingService claim & reap', () => {
claimAffected = 1,
queuedMessages = [] as unknown[],
heartbeatAlive = true,
+ pendingToolOutput = { result: { questions: QUESTIONS, status: 'pending' } },
}: {
thread?: typeof idleThread & {
pendingQuestionMessageId?: string;
- workflowRunId?: string;
};
+ pendingToolOutput?: Record<string, unknown>;
claimAffected?: number;
queuedMessages?: unknown[];
heartbeatAlive?: boolean;
@@ -72,7 +73,7 @@ describe('AgentChatStreamingService claim & reap', () => {
find: jest.fn().mockResolvedValue([
{
id: 'part-id',
- toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },
+ toolOutput: pendingToolOutput,
},
]),
};
@@ -251,9 +252,13 @@ describe('AgentChatStreamingService claim & reap', () => {
).toBeLessThan(messageQueueService.add.mock.invocationCallOrder[0]);
});
- it('refuses a message while its workflow run waits on the conversation', async () => {
+ it('refuses a message while a workflow step waits on the pending call', async () => {
const { send, agentChatService, messageQueueService } = buildService({
- thread: { ...waitingThread, workflowRunId: 'workflow-run-id' },
+ thread: waitingThread,
+ pendingToolOutput: {
+ result: { questions: QUESTIONS, status: 'pending' },
+ workflowStep: { workflowRunId: 'workflow-run-id', stepId: 'step-id' },
+ },
});
await expect(send()).rejects.toMatchObject({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-inbox.service.open-thread.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-inbox.service.open-thread.spec.ts
new file mode 100644
index 00000000000..45eb7729706
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-inbox.service.open-thread.spec.ts
@@ -0,0 +1,130 @@
+import { QueryFailedError } from 'typeorm';
+
+import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
+import { buildInboxThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-thread-id.util';
+
+const SENDER = {
+ type: 'workflow' as const,
+ workflowId: 'workflow-id',
+ workflowName: 'New deals',
+};
+
+const OPEN_ARGS = {
+ workspaceId: 'workspace-id',
+ sender: SENDER,
+ threadKey: 'run-id',
+ title: 'Draft the quote',
+};
+
+const buildUniqueViolation = () =>
+ Object.assign(new QueryFailedError('INSERT', [], new Error('duplicate')), {
+ code: '23505',
+ });
+
+const buildService = () => {
+ const threadRepository = {
+ findOne: jest.fn().mockResolvedValue(null),
+ findOneOrFail: jest
+ .fn()
+ .mockImplementation(
+ (_workspaceId: string, { where }: { where: { id: string } }) =>
+ Promise.resolve({ id: where.id, workspaceMemberId: null }),
+ ),
+ insert: jest.fn().mockResolvedValue(undefined),
+ };
+ const threadService = {
+ createThread: jest
+ .fn()
+ .mockImplementation(({ id, workspaceMemberId }) =>
+ Promise.resolve({ id, workspaceMemberId }),
+ ),
+ };
+
+ const service = new AgentInboxService(
+ threadRepository as never,
+ {} as never,
+ {} as never,
+ threadService as never,
+ {} as never,
+ {} as never,
+ );
+
+ return { service, threadRepository, threadService };
+};
+
+describe('AgentInboxService.openThread', () => {
+ it('continues the conversation the sender already has with the member under that key', async () => {
+ const { service, threadRepository, threadService } = buildService();
+ const existingThread = { id: 'existing-thread-id' };
+
+ threadRepository.findOne.mockResolvedValue(existingThread);
+
+ await expect(
+ service.openThread({ ...OPEN_ARGS, workspaceMemberId: 'member-id' }),
+ ).resolves.toEqual({ thread: existingThread, isCreated: false });
+ expect(threadService.createThread).not.toHaveBeenCalled();
+ });
+
+ it("creates the member's conversation under an id derived from the sender, member and key", async () => {
+ const { service, threadService } = buildService();
+
+ const { thread, isCreated } = await service.openThread({
+ ...OPEN_ARGS,
+ workspaceMemberId: 'member-id',
+ isArchivedOnCreate: true,
+ });
+
+ expect(isCreated).toBe(true);
+ expect(thread.id).toBe(
+ buildInboxThreadId({
+ senderKey: 'workflow:workflow-id',
+ workspaceMemberId: 'member-id',
+ threadKey: 'run-id',
+ }),
+ );
+ expect(threadService.createThread).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ workspaceMemberId: 'member-id',
+ id: thread.id,
+ title: 'Draft the quote',
+ isArchived: true,
+ });
+ });
+
+ it('keeps a conversation with no member out of every inbox', async () => {
+ const { service, threadRepository, threadService } = buildService();
+
+ const { thread, isCreated } = await service.openThread({
+ ...OPEN_ARGS,
+ workspaceMemberId: null,
+ });
+
+ expect(isCreated).toBe(true);
+ expect(threadService.createThread).not.toHaveBeenCalled();
+ expect(threadRepository.insert).toHaveBeenCalledWith('workspace-id', {
+ id: thread.id,
+ title: 'Draft the quote',
+ });
+ expect(thread.id).not.toBe(
+ buildInboxThreadId({
+ senderKey: 'workflow:workflow-id',
+ workspaceMemberId: 'member-id',
+ threadKey: 'run-id',
+ }),
+ );
+ });
+
+ it('returns the conversation a concurrent open created first', async () => {
+ const { service, threadRepository, threadService } = buildService();
+ const concurrentThread = { id: 'concurrent-thread-id' };
+
+ threadService.createThread.mockRejectedValue(buildUniqueViolation());
+ threadRepository.findOne
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce(concurrentThread);
+
+ await expect(
+ service.openThread({ ...OPEN_ARGS, workspaceMemberId: 'member-id' }),
+ ).resolves.toEqual({ thread: concurrentThread, isCreated: false });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
index 4991c6062df..45693adb363 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
@@ -203,7 +203,8 @@ export class AgentChatSharingService {
workspaceMemberId: string;
id?: string;
title?: string;
- workflowRunId?: string;
+ // filed under done for its owner, until activity brings it back to their inbox
+ isArchived?: boolean;
}): Promise<AgentChatThreadWorkspaceEntity> {
const authContext = await this.getAuthContext(args);
const objectMetadata = await this.getThreadObjectMetadata(args.workspaceId);
@@ -211,7 +212,6 @@ export class AgentChatSharingService {
await this.findParticipantObjectMetadataId(args.workspaceId);
const hasInboxState = isDefined(participantObjectMetadataId);
- // workflowRunId is set by the server for a run conversation, never written by the member
await this.workspaceOrmManager.executeInWorkspaceContext(
() =>
this.workspaceOrmManager
@@ -228,12 +228,11 @@ export class AgentChatSharingService {
args.workspaceId,
async ({ manager, table }) => {
const records = await manager.query<AgentChatThreadWorkspaceEntity[]>(
- `INSERT INTO ${table('agentChatThread')} (id, title, "workflowRunId", "workspaceMemberId", "userWorkspaceId"${hasInboxState ? ', "lastActivityAt"' : ''})
- VALUES ($1, $2, $3, $4, $5${hasInboxState ? ', clock_timestamp()' : ''}) RETURNING *`,
+ `INSERT INTO ${table('agentChatThread')} (id, title, "workspaceMemberId", "userWorkspaceId"${hasInboxState ? ', "lastActivityAt"' : ''})
+ VALUES ($1, $2, $3, $4${hasInboxState ? ', clock_timestamp()' : ''}) RETURNING *`,
[
args.id ?? randomUUID(),
args.title ?? null,
- args.workflowRunId ?? null,
authContext.workspaceMemberId,
authContext.userWorkspaceId,
],
@@ -260,8 +259,8 @@ export class AgentChatSharingService {
if (hasInboxState) {
await manager.query(
`WITH participant AS (
- INSERT INTO ${getAgentChatThreadParticipantTable(args.workspaceId)} ("threadId", "workspaceMemberId", "lastReadAt")
- VALUES ($1, $2, $3)
+ INSERT INTO ${getAgentChatThreadParticipantTable(args.workspaceId)} ("threadId", "workspaceMemberId", "lastReadAt", "archivedAt")
+ VALUES ($1, $2, $3, CASE WHEN $5::boolean THEN clock_timestamp() END)
RETURNING id, "workspaceMemberId"
)
${buildAgentChatThreadParticipantOwnerShareInsert({
@@ -274,6 +273,7 @@ export class AgentChatSharingService {
authContext.workspaceMemberId,
record.lastActivityAt,
participantObjectMetadataId,
+ args.isArchived ?? false,
],
);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
index 1fbaa4c182c..9008d9f4bde 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
@@ -604,14 +604,14 @@ export class AgentChatStreamingService {
}
// a message sent while the agent waits on a person closes its pending calls as skipped, so the model sees why
- // an answer holding the stream keeps them, and workflow-run calls gate the run, so a chat message never closes them
+ // an answer holding the stream keeps them, and workflow-step calls gate the run, so a chat message never closes them
private async settlePendingToolCallsBeforeSending({
thread,
workspaceId,
}: {
thread: Pick<
AgentChatThreadWorkspaceEntity,
- 'id' | 'workflowRunId' | 'pendingQuestionMessageId'
+ 'id' | 'pendingQuestionMessageId'
>;
workspaceId: string;
}): Promise<void> {
@@ -621,10 +621,7 @@ export class AgentChatStreamingService {
return;
}
- if (
- isDefined(thread.workflowRunId) ||
- (await this.isAwaitingWorkflowStep({ messageId, workspaceId }))
- ) {
+ if (await this.isAwaitingWorkflowStep({ messageId, workspaceId })) {
throw new AiException(
'This conversation is waiting on an answer to its workflow run',
AiExceptionCode.THREAD_AWAITING_WORKFLOW_INPUT,
@@ -639,7 +636,7 @@ export class AgentChatStreamingService {
});
}
- // a call a workflow step posted to the inbox gates that step like a run's own call
+ // a call a workflow step posted gates that step until it is answered
private async isAwaitingWorkflowStep({
messageId,
workspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts
index e1c893f3433..202c10460fe 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts
@@ -13,11 +13,6 @@ import { getCancelChannel } from 'src/engine/metadata-modules/ai/ai-chat/utils/g
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
-import {
- PermissionsException,
- PermissionsExceptionCode,
- PermissionsExceptionMessage,
-} from 'src/engine/metadata-modules/permissions/permissions.exception';
@Injectable()
export class AgentChatThreadLifecycleService {
@@ -87,27 +82,7 @@ export class AgentChatThreadLifecycleService {
}
}
- // a run's conversation records what its agent step did, so the record API may only read it
- async assertThreadIsNotWorkflowRunThread({
- workspaceId,
- threadId,
- }: {
- workspaceId: string;
- threadId: string;
- }): Promise<void> {
- const thread = await this.threadRepository.findOne(workspaceId, {
- where: { id: threadId },
- });
-
- if (isDefined(thread?.workflowRunId)) {
- throw new PermissionsException(
- `${PermissionsExceptionMessage.PERMISSION_DENIED}: a workflow run conversation is read-only`,
- PermissionsExceptionCode.PERMISSION_DENIED,
- );
- }
- }
-
- // owned and workflow-run threads are skipped so an upsert cannot reassign them
+ // owned threads are skipped so an upsert cannot reassign them
async assignCreatedThreadsToCreator({
authContext,
threadIds,
@@ -120,10 +95,7 @@ export class AgentChatThreadLifecycleService {
}
const workspaceId = authContext.workspace.id;
- const unassignedThreadCriteria = {
- workspaceMemberId: IsNull(),
- workflowRunId: IsNull(),
- };
+ const unassignedThreadCriteria = { workspaceMemberId: IsNull() };
const threadsBefore = await this.threadRepository.find(workspaceId, {
where: { id: In(threadIds), ...unassignedThreadCriteria },
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts
index 56fbdfdb2aa..6a6a7a0c2ca 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts
@@ -10,6 +10,7 @@ import { type AgentInboxDelivery } from 'src/engine/metadata-modules/ai/ai-chat/
import { type AgentInboxSender } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type';
import { resolveEmailToolCallProposal } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util';
import { buildInboxMessageIds } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util';
+import { buildInboxThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-thread-id.util';
import { buildInboxMessageToolCallPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util';
import { buildToolPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-tool-part.util';
import { type ResolveInboxProposal } from 'src/engine/metadata-modules/ai/ai-chat/types/resolve-inbox-proposal.type';
@@ -112,12 +113,15 @@ export class AgentInboxService {
const thread =
existingThread ??
- (await this.createThread({
- workspaceId,
- threadId,
- workspaceMemberId: input.workspaceMemberId,
- title: input.title,
- }));
+ (
+ await this.openThread({
+ workspaceId,
+ sender,
+ workspaceMemberId: input.workspaceMemberId,
+ threadKey: input.threadKey,
+ title: input.title,
+ })
+ ).thread;
await this.ensureOpener({
workspaceId,
@@ -168,6 +172,64 @@ export class AgentInboxService {
return { threadId, isDismissed: false, awaitedToolOutput };
}
+ // The thread key picks the sender's conversation with the member, so every
+ // write with the same key lands in one thread. A conversation with no
+ // member belongs to no inbox, and only the server reads it. One the member
+ // deleted is returned as it is, and the caller decides whether to write to it.
+ async openThread({
+ workspaceId,
+ sender,
+ workspaceMemberId,
+ threadKey,
+ title,
+ isArchivedOnCreate = false,
+ }: {
+ workspaceId: string;
+ sender: AgentInboxSender;
+ workspaceMemberId: string | null;
+ threadKey: string;
+ title: string;
+ isArchivedOnCreate?: boolean;
+ }): Promise<{
+ thread: AgentChatThreadWorkspaceEntity;
+ isCreated: boolean;
+ }> {
+ const threadId = buildInboxThreadId({
+ senderKey: getAgentInboxSenderDetails(sender).key,
+ workspaceMemberId,
+ threadKey,
+ });
+ const existingThread = await this.findThread({ workspaceId, threadId });
+
+ if (isDefined(existingThread)) {
+ return { thread: existingThread, isCreated: false };
+ }
+
+ try {
+ const thread = isDefined(workspaceMemberId)
+ ? await this.threadService.createThread({
+ workspaceId,
+ workspaceMemberId,
+ id: threadId,
+ title,
+ isArchived: isArchivedOnCreate,
+ })
+ : await this.createUnaddressedThread({ workspaceId, threadId, title });
+
+ return { thread, isCreated: true };
+ } catch (error) {
+ const concurrentlyCreatedThread = isUniqueViolationError(error)
+ ? await this.findThread({ workspaceId, threadId })
+ : null;
+
+ if (!isDefined(concurrentlyCreatedThread)) {
+ throw error;
+ }
+
+ return { thread: concurrentlyCreatedThread, isCreated: false };
+ }
+ }
+
private async findToolOutput({
workspaceId,
toolCallId,
@@ -239,35 +301,20 @@ export class AgentInboxService {
});
}
- private async createThread({
+ private async createUnaddressedThread({
workspaceId,
threadId,
- workspaceMemberId,
title,
}: {
workspaceId: string;
threadId: string;
- workspaceMemberId: string;
title: string;
}): Promise<AgentChatThreadWorkspaceEntity> {
- try {
- return await this.threadService.createThread({
- workspaceId,
- workspaceMemberId,
- id: threadId,
- title,
- });
- } catch (error) {
- const concurrentlyCreatedThread = isUniqueViolationError(error)
- ? await this.findThread({ workspaceId, threadId })
- : null;
+ await this.threadRepository.insert(workspaceId, { id: threadId, title });
- if (!isDefined(concurrentlyCreatedThread)) {
- throw error;
- }
-
- return concurrentlyCreatedThread;
- }
+ return this.threadRepository.findOneOrFail(workspaceId, {
+ where: { id: threadId },
+ });
}
// Every id is derived from the keys, so a row that already exists was
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/stamp-pending-tool-parts-with-workflow-step.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/stamp-pending-tool-parts-with-workflow-step.util.spec.ts
new file mode 100644
index 00000000000..6eb9ad241a2
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/stamp-pending-tool-parts-with-workflow-step.util.spec.ts
@@ -0,0 +1,34 @@
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
+
+import { stampPendingToolPartsWithWorkflowStep } from 'src/engine/metadata-modules/ai/ai-chat/utils/stamp-pending-tool-parts-with-workflow-step.util';
+
+const WORKFLOW_STEP = { workflowRunId: 'run-id', stepId: 'step-id' };
+
+const toolPart = (status: string) =>
+ ({
+ type: 'tool-ask_question',
+ toolCallId: `call-${status}`,
+ state: 'output-available',
+ input: {},
+ output: { result: { status } },
+ }) as unknown as ExtendedUIMessagePart;
+
+describe('stampPendingToolPartsWithWorkflowStep', () => {
+ it('names the waiting step on pending calls only', () => {
+ const textPart = { type: 'text', text: 'Hello' } as ExtendedUIMessagePart;
+
+ expect(
+ stampPendingToolPartsWithWorkflowStep({
+ parts: [textPart, toolPart('pending'), toolPart('answered')],
+ workflowStep: WORKFLOW_STEP,
+ }),
+ ).toEqual([
+ textPart,
+ {
+ ...toolPart('pending'),
+ output: { result: { status: 'pending' }, workflowStep: WORKFLOW_STEP },
+ },
+ toolPart('answered'),
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util.ts
index 28ccbfa361c..f4f22d7ec39 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util.ts
@@ -1,6 +1,7 @@
import { v5 } from 'uuid';
import { INBOX_MESSAGE_ID_NAMESPACE } from 'src/engine/metadata-modules/ai/ai-chat/constants/inbox-message-id-namespace.constant';
+import { buildInboxThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-thread-id.util';
type InboxMessageIds = {
threadId: string;
@@ -21,10 +22,11 @@ export const buildInboxMessageIds = ({
threadKey: string;
idempotencyKey: string;
}): InboxMessageIds => {
- const threadId = v5(
- `${senderKey}:${workspaceMemberId}:${threadKey}`,
- INBOX_MESSAGE_ID_NAMESPACE,
- );
+ const threadId = buildInboxThreadId({
+ senderKey,
+ workspaceMemberId,
+ threadKey,
+ });
const messageId = v5(
`${threadId}:message:${idempotencyKey}`,
INBOX_MESSAGE_ID_NAMESPACE,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-thread-id.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-thread-id.util.ts
new file mode 100644
index 00000000000..e2351a6f601
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-thread-id.util.ts
@@ -0,0 +1,18 @@
+import { v5 } from 'uuid';
+
+import { INBOX_MESSAGE_ID_NAMESPACE } from 'src/engine/metadata-modules/ai/ai-chat/constants/inbox-message-id-namespace.constant';
+
+// A conversation no member receives keeps an empty recipient in its key
+export const buildInboxThreadId = ({
+ senderKey,
+ workspaceMemberId,
+ threadKey,
+}: {
+ senderKey: string;
+ workspaceMemberId: string | null;
+ threadKey: string;
+}): string =>
+ v5(
+ `${senderKey}:${workspaceMemberId ?? ''}:${threadKey}`,
+ INBOX_MESSAGE_ID_NAMESPACE,
+ );
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/exclude-workflow-run-threads-from-filter.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/exclude-workflow-run-threads-from-filter.util.ts
deleted file mode 100644
index e33494889ac..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/exclude-workflow-run-threads-from-filter.util.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-// A workflow run's conversation belongs to the run, so bulk record operations
-// on chats never reach it.
-export const excludeWorkflowRunThreadsFromFilter = <TFilter>(
- filter: TFilter,
-): { and: [TFilter, { workflowRunId: { is: 'NULL' } }] } => ({
- and: [filter, { workflowRunId: { is: 'NULL' } }],
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/stamp-pending-tool-parts-with-workflow-step.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/stamp-pending-tool-parts-with-workflow-step.util.ts
new file mode 100644
index 00000000000..4cc8afc00a5
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/stamp-pending-tool-parts-with-workflow-step.util.ts
@@ -0,0 +1,26 @@
+import { isToolUIPart } from 'ai';
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util';
+import { type ToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-chat/types/tool-call-workflow-step.type';
+
+// A pending call names the step that waits on it, so its answer or outcome
+// resumes that step even in a conversation other runs also write to
+export const stampPendingToolPartsWithWorkflowStep = ({
+ parts,
+ workflowStep,
+}: {
+ parts: ExtendedUIMessagePart[];
+ workflowStep: ToolCallWorkflowStep;
+}): ExtendedUIMessagePart[] =>
+ parts.map((part) =>
+ isToolUIPart(part) &&
+ isPlainObject(part.output) &&
+ isAwaitingPausingToolOutput(part.output)
+ ? ({
+ ...part,
+ output: { ...part.output, workflowStep },
+ } as ExtendedUIMessagePart)
+ : part,
+ );
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
index edd65aa0f90..905bc435cfa 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
@@ -9,6 +9,8 @@ import { IsNull } from 'typeorm';
import { findAwaitingPausingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util';
import { mapAiStepsToUIMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util';
import { mapUIMessagePartsToDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-db-parts.util';
+import { type ToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-chat/types/tool-call-workflow-step.type';
+import { stampPendingToolPartsWithWorkflowStep } from 'src/engine/metadata-modules/ai/ai-chat/utils/stamp-pending-tool-parts-with-workflow-step.util';
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
@@ -191,6 +193,7 @@ export class AgentConversationWriterService {
turnId,
agentId,
execution,
+ workflowStep,
scope,
}: {
workspaceId: string;
@@ -198,12 +201,19 @@ export class AgentConversationWriterService {
turnId: string;
agentId: string | null;
execution: RecordableAgentExecution;
+ workflowStep?: ToolCallWorkflowStep;
scope?: AgentHistoryTransactionScope;
}): Promise<{
isAwaitingAnswer: boolean;
replyParts: ExtendedUIMessagePart[];
}> {
- const replyParts = mapAiStepsToUIMessageParts(execution.steps ?? []);
+ const mappedReplyParts = mapAiStepsToUIMessageParts(execution.steps ?? []);
+ const replyParts = isDefined(workflowStep)
+ ? stampPendingToolPartsWithWorkflowStep({
+ parts: mappedReplyParts,
+ workflowStep,
+ })
+ : mappedReplyParts;
if (replyParts.length === 0) {
return { isAwaitingAnswer: false, replyParts };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts
index f377eb1e521..486ae79d6fc 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts
@@ -7,7 +7,6 @@ import { type AgentChatThreadTargetWorkspaceEntity } from 'src/engine/metadata-m
import { BaseWorkspaceEntity } from 'src/engine/twenty-orm/base.workspace-entity';
import { type AgentChatThreadLastStreamError } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-last-stream-error.type';
import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
-import { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
export class AgentChatThreadWorkspaceEntity extends BaseWorkspaceEntity {
messages: EntityRelation<AgentMessageWorkspaceEntity[]>;
@@ -16,13 +15,11 @@ export class AgentChatThreadWorkspaceEntity extends BaseWorkspaceEntity {
workspaceMember: EntityRelation<WorkspaceMemberWorkspaceEntity> | null;
recordTargets: EntityRelation<AgentChatThreadTargetWorkspaceEntity[]>;
participants: EntityRelation<AgentChatThreadParticipantWorkspaceEntity[]>;
- workflowRun: EntityRelation<WorkflowRunWorkspaceEntity> | null;
archivedAt: string | null;
userWorkspaceId: string | null;
workspaceMemberId: string | null;
- workflowRunId: string | null;
title: string | null;
lastActivityAt: string | null;
lastMessageText: string | null;
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.ts
index 11c05b1efd4..d1bb82b797e 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
@@ -12,6 +12,7 @@ import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/to
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
import { type PausingToolCompletionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type';
+import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util';
import { parsePausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/parse-pausing-tool-call.util';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
import { AgentChatActorService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service';
@@ -80,12 +81,7 @@ export class ToolCallAnswerService {
const [thread, toolPart] = await Promise.all([
this.threadRepository.findOne(workspaceId, {
where: { id: threadId },
- select: [
- 'id',
- 'workflowRunId',
- 'activeStreamId',
- 'pendingQuestionMessageId',
- ],
+ select: ['id', 'activeStreamId', 'pendingQuestionMessageId'],
}),
this.agentChatService.findToolPart({ threadId, toolCallId, workspaceId }),
]);
@@ -102,28 +98,21 @@ export class ToolCallAnswerService {
);
}
- // a run's own conversation, or a member's inbox where a step posted a call it waits on
- const inboxWorkflowStep = isDefined(thread.workflowRunId)
- ? null
- : readToolCallWorkflowStep(toolPart.toolOutput);
- const workflowRunId =
- thread.workflowRunId ?? inboxWorkflowStep?.workflowRunId ?? null;
-
- if (isDefined(thread.workflowRunId)) {
- await this.assertCanAnswerForWorkflowRun({
- userWorkspaceId,
- workspaceId,
- workflowRunId: thread.workflowRunId,
- });
- } else {
- await this.assertCanAnswerInChat({
- ...args,
- messageId: toolPart.messageId,
- isStartingChatTurn: !isDefined(inboxWorkflowStep),
- });
- }
+ // a workflow step that posted the call waits on it, and the answer resumes that step. An answer
+ // replaces that output, so a call no longer pending starts nothing and is refused below
+ const workflowStep = readToolCallWorkflowStep(toolPart.toolOutput);
+ const workflowRunId = workflowStep?.workflowRunId ?? null;
+ const isToolCallPending =
+ thread.pendingQuestionMessageId === toolPart.messageId &&
+ isAwaitingPausingToolOutput(toolPart.toolOutput);
+
+ await this.assertCanAnswerInChat({
+ ...args,
+ messageId: toolPart.messageId,
+ isStartingChatTurn: !isDefined(workflowStep) && isToolCallPending,
+ });
- if (thread.pendingQuestionMessageId !== toolPart.messageId) {
+ if (!isToolCallPending) {
throw this.notPending();
}
@@ -181,13 +170,13 @@ export class ToolCallAnswerService {
threadId,
workflowRunId,
workspaceId,
- expectedStepId: inboxWorkflowStep?.stepId,
+ expectedStepId: workflowStep?.stepId,
});
if (
!isDefined(step) &&
(await this.workflowRunWorkspaceService.isStepStillRunning({
- stepId: inboxWorkflowStep?.stepId,
+ stepId: workflowStep?.stepId,
threadId,
workflowRunId,
workspaceId,
@@ -305,23 +294,20 @@ export class ToolCallAnswerService {
await this.publishToolCallResolved({ threadId, toolCallId, workspaceId });
// An answer is a message the member sent, so the chat moves up and
- // comes back to their inbox. A run's conversation is not in chat lists.
- // The answer is already recorded and cannot be given again, so a
- // failure here must not fail the turn
- if (!isDefined(workflowRunId)) {
- await this.threadService
- .notifyThreadActivityUpdated({
- threadId,
- workspaceMemberId: args.workspaceMemberId,
- workspaceId,
- text: answerText,
- })
- .catch((error: unknown) =>
- this.logger.warn(
- `Could not record answer activity on thread ${threadId}: ${formatErrorWithCause(error)}`,
- ),
- );
- }
+ // comes back to their inbox. The answer is already recorded and cannot
+ // be given again, so a failure here must not fail the turn
+ await this.threadService
+ .notifyThreadActivityUpdated({
+ threadId,
+ workspaceMemberId: args.workspaceMemberId,
+ workspaceId,
+ text: answerText,
+ })
+ .catch((error: unknown) =>
+ this.logger.warn(
+ `Could not record answer activity on thread ${threadId}: ${formatErrorWithCause(error)}`,
+ ),
+ );
// runs resume in their own executor, and only the last answer resumes a chat
if (isDefined(step) || !isLastAnswer) {
@@ -449,33 +435,6 @@ export class ToolCallAnswerService {
});
}
- private async assertCanAnswerForWorkflowRun({
- userWorkspaceId,
- workspaceId,
- workflowRunId,
- }: {
- userWorkspaceId: string;
- workspaceId: string;
- workflowRunId: string;
- }): Promise<void> {
- await this.assertHasSettingPermission({
- setting: PermissionFlagType.WORKFLOWS,
- userWorkspaceId,
- workspaceId,
- });
-
- if (
- !(await this.workflowRunWorkspaceService.isWorkflowRunReadableByRequester(
- workflowRunId,
- ))
- ) {
- throw new AiException(
- 'The tool call to answer could not be found',
- AiExceptionCode.TOOL_CALL_NOT_FOUND,
- );
- }
- }
-
private buildCompletionContext({
workspaceId,
userWorkspaceId,
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
index d74ce39f010..c046139bbfd 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
@@ -10,6 +10,10 @@ import {
WorkflowVersionStatus,
} from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
@@ -238,11 +242,35 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
workflowRunId,
workflow,
initiator: agentWorkflow.initiator,
- recordConversation: () =>
- this.workflowAgentConversationService.recordExecution({
+ recordConversation: async () => {
+ const openConversation = (
+ recipientWorkspaceMemberId: string | null,
+ ) =>
+ this.workflowAgentConversationService.openConversation({
+ runInfo: { workspaceId, workflowRunId },
+ stepId: workflow.step.id,
+ title: workflow.step.name,
+ recipientWorkspaceMemberId,
+ threadKey: `${workflowRunId}:${workflow.step.id}`,
+ });
+ // an initiator who cannot hold a chat in this workspace leaves the question with no recipient
+ const { threadId } = await openConversation(
+ INITIATORS[agentWorkflow.initiator].workspaceMemberId,
+ ).catch((error) => {
+ if (
+ error instanceof AiException &&
+ error.code === AiExceptionCode.THREAD_NOT_FOUND
+ ) {
+ return openConversation(null);
+ }
+
+ throw error;
+ });
+
+ await this.workflowAgentConversationService.recordExecution({
workspaceId,
- workflowRunId,
- stepId: workflow.step.id,
+ threadId,
+ workflowStep: { workflowRunId, stepId: workflow.step.id },
title: workflow.step.name,
agentId: null,
prompt: agentWorkflow.runPrompt,
@@ -251,7 +279,8 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
isPaused: true,
steps: [{ content }],
},
- }),
+ });
+ },
});
}
}
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap
index 20e417a040e..0a86845cf96 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap
@@ -5,352 +5,349 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object
"agentChatThread": {
"fields": {
"activeStreamId": {
- "id": "00000000-0000-0000-0000-000000001031",
+ "id": "00000000-0000-0000-0000-000000001030",
},
"archivedAt": {
- "id": "00000000-0000-0000-0000-000000001019",
+ "id": "00000000-0000-0000-0000-000000001018",
},
"attachments": {
- "id": "00000000-0000-0000-0000-000000001037",
+ "id": "00000000-0000-0000-0000-000000001035",
},
"contextWindowTokens": {
- "id": "00000000-0000-0000-0000-000000001025",
+ "id": "00000000-0000-0000-0000-000000001024",
},
"conversationSize": {
- "id": "00000000-0000-0000-0000-000000001026",
+ "id": "00000000-0000-0000-0000-000000001025",
},
"createdAt": {
- "id": "00000000-0000-0000-0000-000000001016",
+ "id": "00000000-0000-0000-0000-000000001015",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000001018",
+ "id": "00000000-0000-0000-0000-000000001017",
},
"id": {
- "id": "00000000-0000-0000-0000-000000001015",
+ "id": "00000000-0000-0000-0000-000000001014",
},
"lastActivityAt": {
- "id": "00000000-0000-0000-0000-000000001040",
+ "id": "00000000-0000-0000-0000-000000001038",
},
"lastMessageSenderWorkspaceMemberId": {
- "id": "00000000-0000-0000-0000-000000001042",
+ "id": "00000000-0000-0000-0000-000000001040",
},
"lastMessageText": {
- "id": "00000000-0000-0000-0000-000000001041",
+ "id": "00000000-0000-0000-0000-000000001039",
},
"lastStreamError": {
- "id": "00000000-0000-0000-0000-000000001034",
+ "id": "00000000-0000-0000-0000-000000001032",
},
"messages": {
- "id": "00000000-0000-0000-0000-000000001036",
+ "id": "00000000-0000-0000-0000-000000001034",
},
"participants": {
- "id": "00000000-0000-0000-0000-000000001039",
+ "id": "00000000-0000-0000-0000-000000001037",
},
"pendingQuestionMessageId": {
- "id": "00000000-0000-0000-0000-000000001033",
+ "id": "00000000-0000-0000-0000-000000001031",
},
"recordTargets": {
- "id": "00000000-0000-0000-0000-000000001038",
+ "id": "00000000-0000-0000-0000-000000001036",
},
"title": {
- "id": "00000000-0000-0000-0000-000000001022",
+ "id": "00000000-0000-0000-0000-000000001021",
},
"totalCacheCreationTokens": {
- "id": "00000000-0000-0000-0000-000000001030",
+ "id": "00000000-0000-0000-0000-000000001029",
},
"totalCacheReadTokens": {
- "id": "00000000-0000-0000-0000-000000001029",
+ "id": "00000000-0000-0000-0000-000000001028",
},
"totalInputCredits": {
- "id": "00000000-0000-0000-0000-000000001027",
+ "id": "00000000-0000-0000-0000-000000001026",
},
"totalInputTokens": {
- "id": "00000000-0000-0000-0000-000000001023",
+ "id": "00000000-0000-0000-0000-000000001022",
},
"totalOutputCredits": {
- "id": "00000000-0000-0000-0000-000000001028",
+ "id": "00000000-0000-0000-0000-000000001027",
},
"totalOutputTokens": {
- "id": "00000000-0000-0000-0000-000000001024",
+ "id": "00000000-0000-0000-0000-000000001023",
},
"turns": {
- "id": "00000000-0000-0000-0000-000000001035",
+ "id": "00000000-0000-0000-0000-000000001033",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000001017",
+ "id": "00000000-0000-0000-0000-000000001016",
},
"userWorkspaceId": {
- "id": "00000000-0000-0000-0000-000000001020",
- },
- "workflowRun": {
- "id": "00000000-0000-0000-0000-000000001032",
+ "id": "00000000-0000-0000-0000-000000001019",
},
"workspaceMember": {
- "id": "00000000-0000-0000-0000-000000001021",
+ "id": "00000000-0000-0000-0000-000000001020",
},
"writerWorkspaceMemberIds": {
- "id": "00000000-0000-0000-0000-000000001043",
+ "id": "00000000-0000-0000-0000-000000001041",
},
},
- "id": "00000000-0000-0000-0000-000000001044",
+ "id": "00000000-0000-0000-0000-000000001042",
"views": undefined,
},
"agentChatThreadParticipant": {
"fields": {
"archivedAt": {
- "id": "00000000-0000-0000-0000-000000001052",
+ "id": "00000000-0000-0000-0000-000000001050",
},
"createdAt": {
- "id": "00000000-0000-0000-0000-000000001046",
+ "id": "00000000-0000-0000-0000-000000001044",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000001048",
+ "id": "00000000-0000-0000-0000-000000001046",
},
"id": {
- "id": "00000000-0000-0000-0000-000000001045",
+ "id": "00000000-0000-0000-0000-000000001043",
},
"lastReadAt": {
- "id": "00000000-0000-0000-0000-000000001051",
+ "id": "00000000-0000-0000-0000-000000001049",
},
"snoozedUntil": {
- "id": "00000000-0000-0000-0000-000000001053",
+ "id": "00000000-0000-0000-0000-000000001051",
},
"thread": {
- "id": "00000000-0000-0000-0000-000000001049",
+ "id": "00000000-0000-0000-0000-000000001047",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000001047",
+ "id": "00000000-0000-0000-0000-000000001045",
},
"workspaceMember": {
- "id": "00000000-0000-0000-0000-000000001050",
+ "id": "00000000-0000-0000-0000-000000001048",
},
},
- "id": "00000000-0000-0000-0000-000000001054",
+ "id": "00000000-0000-0000-0000-000000001052",
"views": undefined,
},
"agentChatThreadTarget": {
"fields": {
"createdAt": {
- "id": "00000000-0000-0000-0000-000000001056",
+ "id": "00000000-0000-0000-0000-000000001054",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000001058",
+ "id": "00000000-0000-0000-0000-000000001056",
},
"id": {
- "id": "00000000-0000-0000-0000-000000001055",
+ "id": "00000000-0000-0000-0000-000000001053",
},
"targetCompany": {
- "id": "00000000-0000-0000-0000-000000001061",
+ "id": "00000000-0000-0000-0000-000000001059",
},
"targetOpportunity": {
- "id": "00000000-0000-0000-0000-000000001062",
+ "id": "00000000-0000-0000-0000-000000001060",
},
"targetPerson": {
- "id": "00000000-0000-0000-0000-000000001060",
+ "id": "00000000-0000-0000-0000-000000001058",
},
"thread": {
- "id": "00000000-0000-0000-0000-000000001059",
+ "id": "00000000-0000-0000-0000-000000001057",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000001057",
+ "id": "00000000-0000-0000-0000-000000001055",
},
},
- "id": "00000000-0000-0000-0000-000000001063",
+ "id": "00000000-0000-0000-0000-000000001061",
"views": {},
},
"agentMessage": {
"fields": {
"agentId": {
- "id": "00000000-0000-0000-0000-000000001077",
+ "id": "00000000-0000-0000-0000-000000001075",
},
"createdAt": {
- "id": "00000000-0000-0000-0000-000000001074",
+ "id": "00000000-0000-0000-0000-000000001072",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000001076",
+ "id": "00000000-0000-0000-0000-000000001074",
},
"id": {
- "id": "00000000-0000-0000-0000-000000001073",
+ "id": "00000000-0000-0000-0000-000000001071",
},
"isHidden": {
- "id": "00000000-0000-0000-0000-000000001083",
+ "id": "00000000-0000-0000-0000-000000001081",
},
"parts": {
- "id": "00000000-0000-0000-0000-000000001087",
+ "id": "00000000-0000-0000-0000-000000001085",
},
"processedAt": {
- "id": "00000000-0000-0000-0000-000000001084",
+ "id": "00000000-0000-0000-0000-000000001082",
},
"role": {
- "id": "00000000-0000-0000-0000-000000001081",
+ "id": "00000000-0000-0000-0000-000000001079",
},
"senderApplicationId": {
- "id": "00000000-0000-0000-0000-000000001080",
+ "id": "00000000-0000-0000-0000-000000001078",
},
"senderUserWorkspaceId": {
- "id": "00000000-0000-0000-0000-000000001079",
+ "id": "00000000-0000-0000-0000-000000001077",
},
"senderWorkspaceMember": {
- "id": "00000000-0000-0000-0000-000000001078",
+ "id": "00000000-0000-0000-0000-000000001076",
},
"status": {
- "id": "00000000-0000-0000-0000-000000001082",
+ "id": "00000000-0000-0000-0000-000000001080",
},
"thread": {
- "id": "00000000-0000-0000-0000-000000001085",
+ "id": "00000000-0000-0000-0000-000000001083",
},
"turn": {
- "id": "00000000-0000-0000-0000-000000001086",
+ "id": "00000000-0000-0000-0000-000000001084",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000001075",
+ "id": "00000000-0000-0000-0000-000000001073",
},
},
- "id": "00000000-0000-0000-0000-000000001088",
+ "id": "00000000-0000-0000-0000-000000001086",
"views": undefined,
},
"agentMessagePart": {
"fields": {
"createdAt": {
- "id": "00000000-0000-0000-0000-000000001090",
+ "id": "00000000-0000-0000-0000-000000001088",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000001092",
+ "id": "00000000-0000-0000-0000-000000001090",
},
"errorDetails": {
- "id": "00000000-0000-0000-0000-000000001104",
+ "id": "00000000-0000-0000-0000-000000001102",
},
"errorMessage": {
- "id": "00000000-0000-0000-0000-000000001103",
+ "id": "00000000-0000-0000-0000-000000001101",
},
"fileFilename": {
- "id": "00000000-0000-0000-0000-000000001112",
+ "id": "00000000-0000-0000-0000-000000001110",
},
"fileId": {
- "id": "00000000-0000-0000-0000-000000001113",
+ "id": "00000000-0000-0000-0000-000000001111",
},
"id": {
- "id": "00000000-0000-0000-0000-000000001089",
+ "id": "00000000-0000-0000-0000-000000001087",
},
"message": {
- "id": "00000000-0000-0000-0000-000000001115",
+ "id": "00000000-0000-0000-0000-000000001113",
},
"orderIndex": {
- "id": "00000000-0000-0000-0000-000000001093",
+ "id": "00000000-0000-0000-0000-000000001091",
},
"providerExecuted": {
- "id": "00000000-0000-0000-0000-000000001102",
+ "id": "00000000-0000-0000-0000-000000001100",
},
"providerMetadata": {
- "id": "00000000-0000-0000-0000-000000001114",
+ "id": "00000000-0000-0000-0000-000000001112",
},
"reasoningContent": {
- "id": "00000000-0000-0000-0000-000000001096",
+ "id": "00000000-0000-0000-0000-000000001094",
},
"sourceDocumentFilename": {
- "id": "00000000-0000-0000-0000-000000001111",
+ "id": "00000000-0000-0000-0000-000000001109",
},
"sourceDocumentMediaType": {
- "id": "00000000-0000-0000-0000-000000001109",
+ "id": "00000000-0000-0000-0000-000000001107",
},
"sourceDocumentSourceId": {
- "id": "00000000-0000-0000-0000-000000001108",
+ "id": "00000000-0000-0000-0000-000000001106",
},
"sourceDocumentTitle": {
- "id": "00000000-0000-0000-0000-000000001110",
+ "id": "00000000-0000-0000-0000-000000001108",
},
"sourceUrlSourceId": {
- "id": "00000000-0000-0000-0000-000000001105",
+ "id": "00000000-0000-0000-0000-000000001103",
},
"sourceUrlTitle": {
- "id": "00000000-0000-0000-0000-000000001107",
+ "id": "00000000-0000-0000-0000-000000001105",
},
"sourceUrlUrl": {
- "id": "00000000-0000-0000-0000-000000001106",
+ "id": "00000000-0000-0000-0000-000000001104",
},
"state": {
- "id": "00000000-0000-0000-0000-000000001101",
+ "id": "00000000-0000-0000-0000-000000001099",
},
"textContent": {
- "id": "00000000-0000-0000-0000-000000001095",
+ "id": "00000000-0000-0000-0000-000000001093",
},
"toolCallId": {
- "id": "00000000-0000-0000-0000-000000001098",
+ "id": "00000000-0000-0000-0000-000000001096",
},
"toolInput": {
- "id": "00000000-0000-0000-0000-000000001099",
+ "id": "00000000-0000-0000-0000-000000001097",
},
"toolName": {
- "id": "00000000-0000-0000-0000-000000001097",
+ "id": "00000000-0000-0000-0000-000000001095",
},
"toolOutput": {
- "id": "00000000-0000-0000-0000-000000001100",
+ "id": "00000000-0000-0000-0000-000000001098",
},
"type": {
- "id": "00000000-0000-0000-0000-000000001094",
+ "id": "00000000-0000-0000-0000-000000001092",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000001091",
+ "id": "00000000-0000-0000-0000-000000001089",
},
},
- "id": "00000000-0000-0000-0000-000000001116",
+ "id": "00000000-0000-0000-0000-000000001114",
"views": undefined,
},
"agentTurn": {
"fields": {
"agentId": {
- "id": "00000000-0000-0000-0000-000000001068",
+ "id": "00000000-0000-0000-0000-000000001066",
},
"createdAt": {
- "id": "00000000-0000-0000-0000-000000001065",
+ "id": "00000000-0000-0000-0000-000000001063",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000001067",
+ "id": "00000000-0000-0000-0000-000000001065",
},
"evaluations": {
- "id": "00000000-0000-0000-0000-000000001071",
+ "id": "00000000-0000-0000-0000-000000001069",
},
"id": {
- "id": "00000000-0000-0000-0000-000000001064",
+ "id": "00000000-0000-0000-0000-000000001062",
},
"messages": {
- "id": "00000000-0000-0000-0000-000000001070",
+ "id": "00000000-0000-0000-0000-000000001068",
},
"thread": {
- "id": "00000000-0000-0000-0000-000000001069",
+ "id": "00000000-0000-0000-0000-000000001067",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000001066",
+ "id": "00000000-0000-0000-0000-000000001064",
},
},
- "id": "00000000-0000-0000-0000-000000001072",
+ "id": "00000000-0000-0000-0000-000000001070",
"views": undefined,
},
"agentTurnEvaluation": {
"fields": {
"comment": {
- "id": "00000000-0000-0000-0000-000000001122",
+ "id": "00000000-0000-0000-0000-000000001120",
},
"createdAt": {
- "id": "00000000-0000-0000-0000-000000001118",
+ "id": "00000000-0000-0000-0000-000000001116",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000001120",
+ "id": "00000000-0000-0000-0000-000000001118",
},
"id": {
- "id": "00000000-0000-0000-0000-000000001117",
+ "id": "00000000-0000-0000-0000-000000001115",
},
"score": {
- "id": "00000000-0000-0000-0000-000000001121",
+ "id": "00000000-0000-0000-0000-000000001119",
},
"turn": {
- "id": "00000000-0000-0000-0000-000000001123",
+ "id": "00000000-0000-0000-0000-000000001121",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000001119",
+ "id": "00000000-0000-0000-0000-000000001117",
},
},
- "id": "00000000-0000-0000-0000-000000001124",
+ "id": "00000000-0000-0000-0000-000000001122",
"views": undefined,
},
"attachment": {
@@ -1108,64 +1105,64 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object
"campaignDelivery": {
"fields": {
"bouncedAt": {
- "id": "00000000-0000-0000-0000-000000001140",
+ "id": "00000000-0000-0000-0000-000000001138",
},
"campaignId": {
- "id": "00000000-0000-0000-0000-000000001129",
+ "id": "00000000-0000-0000-0000-000000001127",
},
"claimExpiresAt": {
- "id": "00000000-0000-0000-0000-000000001136",
+ "id": "00000000-0000-0000-0000-000000001134",
},
"claimToken": {
- "id": "00000000-0000-0000-0000-000000001135",
+ "id": "00000000-0000-0000-0000-000000001133",
},
"complainedAt": {
- "id": "00000000-0000-0000-0000-000000001141",
+ "id": "00000000-0000-0000-0000-000000001139",
},
"createdAt": {
- "id": "00000000-0000-0000-0000-000000001126",
+ "id": "00000000-0000-0000-0000-000000001124",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000001128",
+ "id": "00000000-0000-0000-0000-000000001126",
},
"deliveredAt": {
- "id": "00000000-0000-0000-0000-000000001139",
+ "id": "00000000-0000-0000-0000-000000001137",
},
"failureReason": {
- "id": "00000000-0000-0000-0000-000000001134",
+ "id": "00000000-0000-0000-0000-000000001132",
},
"id": {
- "id": "00000000-0000-0000-0000-000000001125",
+ "id": "00000000-0000-0000-0000-000000001123",
},
"personId": {
- "id": "00000000-0000-0000-0000-000000001130",
+ "id": "00000000-0000-0000-0000-000000001128",
},
"providerMessageId": {
- "id": "00000000-0000-0000-0000-000000001137",
+ "id": "00000000-0000-0000-0000-000000001135",
},
"recipientEmail": {
- "id": "00000000-0000-0000-0000-000000001131",
+ "id": "00000000-0000-0000-0000-000000001129",
},
"rejectedAt": {
- "id": "00000000-0000-0000-0000-000000001142",
+ "id": "00000000-0000-0000-0000-000000001140",
},
"renderingFailedAt": {
- "id": "00000000-0000-0000-0000-000000001143",
+ "id": "00000000-0000-0000-0000-000000001141",
},
"sentAt": {
- "id": "00000000-0000-0000-0000-000000001138",
+ "id": "00000000-0000-0000-0000-000000001136",
},
"skipReason": {
- "id": "00000000-0000-0000-0000-000000001133",
+ "id": "00000000-0000-0000-0000-000000001131",
},
"state": {
- "id": "00000000-0000-0000-0000-000000001132",
+ "id": "00000000-0000-0000-0000-000000001130",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000001127",
+ "id": "00000000-0000-0000-0000-000000001125",
},
},
- "id": "00000000-0000-0000-0000-000000001144",
+ "id": "00000000-0000-0000-0000-000000001142",
"views": undefined,
},
"company": {
@@ -2122,34 +2119,34 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object
"messageSuppression": {
"fields": {
"createdAt": {
- "id": "00000000-0000-0000-0000-000000001146",
+ "id": "00000000-0000-0000-0000-000000001144",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000001148",
+ "id": "00000000-0000-0000-0000-000000001146",
},
"emailAddress": {
- "id": "00000000-0000-0000-0000-000000001149",
+ "id": "00000000-0000-0000-0000-000000001147",
},
"id": {
- "id": "00000000-0000-0000-0000-000000001145",
+ "id": "00000000-0000-0000-0000-000000001143",
},
"providerEventId": {
- "id": "00000000-0000-0000-0000-000000001152",
+ "id": "00000000-0000-0000-0000-000000001150",
},
"reason": {
- "id": "00000000-0000-0000-0000-000000001150",
+ "id": "00000000-0000-0000-0000-000000001148",
},
"source": {
- "id": "00000000-0000-0000-0000-000000001151",
+ "id": "00000000-0000-0000-0000-000000001149",
},
"unsubscribeTopicId": {
- "id": "00000000-0000-0000-0000-000000001153",
+ "id": "00000000-0000-0000-0000-000000001151",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000001147",
+ "id": "00000000-0000-0000-0000-000000001145",
},
},
- "id": "00000000-0000-0000-0000-000000001154",
+ "id": "00000000-0000-0000-0000-000000001152",
"views": undefined,
},
"messageThread": {
@@ -3463,9 +3460,6 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object
},
"workflowRun": {
"fields": {
- "agentChatThreads": {
- "id": "00000000-0000-0000-0000-000000000919",
- },
"coreWorkflowId": {
"id": "00000000-0000-0000-0000-000000000917",
},
@@ -3512,7 +3506,7 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object
"id": "00000000-0000-0000-0000-000000000916",
},
"timelineActivities": {
- "id": "00000000-0000-0000-0000-000000000920",
+ "id": "00000000-0000-0000-0000-000000000919",
},
"updatedAt": {
"id": "00000000-0000-0000-0000-000000000902",
@@ -3527,70 +3521,70 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object
"id": "00000000-0000-0000-0000-000000000909",
},
},
- "id": "00000000-0000-0000-0000-000000000940",
+ "id": "00000000-0000-0000-0000-000000000939",
"views": {
"allWorkflowRuns": {
- "id": "00000000-0000-0000-0000-000000000924",
+ "id": "00000000-0000-0000-0000-000000000923",
"viewFieldGroups": {},
"viewFields": {
"name": {
- "id": "00000000-0000-0000-0000-000000000921",
+ "id": "00000000-0000-0000-0000-000000000920",
},
"status": {
- "id": "00000000-0000-0000-0000-000000000923",
+ "id": "00000000-0000-0000-0000-000000000922",
},
"workflow": {
- "id": "00000000-0000-0000-0000-000000000922",
+ "id": "00000000-0000-0000-0000-000000000921",
},
},
"viewGroups": {},
},
"workflowRunRecordPageFields": {
- "id": "00000000-0000-0000-0000-000000000939",
+ "id": "00000000-0000-0000-0000-000000000938",
"viewFieldGroups": {
"general": {
- "id": "00000000-0000-0000-0000-000000000937",
+ "id": "00000000-0000-0000-0000-000000000936",
},
"system": {
- "id": "00000000-0000-0000-0000-000000000938",
+ "id": "00000000-0000-0000-0000-000000000937",
},
},
"viewFields": {
"createdAt": {
- "id": "00000000-0000-0000-0000-000000000930",
+ "id": "00000000-0000-0000-0000-000000000929",
},
"createdBy": {
- "id": "00000000-0000-0000-0000-000000000931",
+ "id": "00000000-0000-0000-0000-000000000930",
},
"endedAt": {
- "id": "00000000-0000-0000-0000-000000000929",
+ "id": "00000000-0000-0000-0000-000000000928",
},
"enqueuedAt": {
- "id": "00000000-0000-0000-0000-000000000932",
+ "id": "00000000-0000-0000-0000-000000000931",
},
"startedAt": {
- "id": "00000000-0000-0000-0000-000000000928",
+ "id": "00000000-0000-0000-0000-000000000927",
},
"state": {
- "id": "00000000-0000-0000-0000-000000000933",
+ "id": "00000000-0000-0000-0000-000000000932",
},
"status": {
- "id": "00000000-0000-0000-0000-000000000925",
+ "id": "00000000-0000-0000-0000-000000000924",
},
"timelineActivities": {
- "id": "00000000-0000-0000-0000-000000000936",
+ "id": "00000000-0000-0000-0000-000000000935",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000000934",
+ "id": "00000000-0000-0000-0000-000000000933",
},
"updatedBy": {
- "id": "00000000-0000-0000-0000-000000000935",
+ "id": "00000000-0000-0000-0000-000000000934",
},
"workflow": {
- "id": "00000000-0000-0000-0000-000000000926",
+ "id": "00000000-0000-0000-0000-000000000925",
},
"workflowVersion": {
- "id": "00000000-0000-0000-0000-000000000927",
+ "id": "00000000-0000-0000-0000-000000000926",
},
},
"viewGroups": {},
@@ -3600,118 +3594,118 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object
"workflowVersion": {
"fields": {
"coreWorkflowVersionId": {
- "id": "00000000-0000-0000-0000-000000000955",
+ "id": "00000000-0000-0000-0000-000000000954",
},
"createdAt": {
- "id": "00000000-0000-0000-0000-000000000942",
+ "id": "00000000-0000-0000-0000-000000000941",
},
"createdBy": {
- "id": "00000000-0000-0000-0000-000000000945",
+ "id": "00000000-0000-0000-0000-000000000944",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000000944",
+ "id": "00000000-0000-0000-0000-000000000943",
},
"id": {
- "id": "00000000-0000-0000-0000-000000000941",
+ "id": "00000000-0000-0000-0000-000000000940",
},
"name": {
- "id": "00000000-0000-0000-0000-000000000949",
+ "id": "00000000-0000-0000-0000-000000000948",
},
"position": {
- "id": "00000000-0000-0000-0000-000000000947",
+ "id": "00000000-0000-0000-0000-000000000946",
},
"runs": {
- "id": "00000000-0000-0000-0000-000000000953",
+ "id": "00000000-0000-0000-0000-000000000952",
},
"searchVector": {
- "id": "00000000-0000-0000-0000-000000000948",
+ "id": "00000000-0000-0000-0000-000000000947",
},
"status": {
- "id": "00000000-0000-0000-0000-000000000952",
+ "id": "00000000-0000-0000-0000-000000000951",
},
"steps": {
- "id": "00000000-0000-0000-0000-000000000954",
+ "id": "00000000-0000-0000-0000-000000000953",
},
"timelineActivities": {
- "id": "00000000-0000-0000-0000-000000000956",
+ "id": "00000000-0000-0000-0000-000000000955",
},
"trigger": {
- "id": "00000000-0000-0000-0000-000000000951",
+ "id": "00000000-0000-0000-0000-000000000950",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000000943",
+ "id": "00000000-0000-0000-0000-000000000942",
},
"updatedBy": {
- "id": "00000000-0000-0000-0000-000000000946",
+ "id": "00000000-0000-0000-0000-000000000945",
},
"workflow": {
- "id": "00000000-0000-0000-0000-000000000950",
+ "id": "00000000-0000-0000-0000-000000000949",
},
},
- "id": "00000000-0000-0000-0000-000000000976",
+ "id": "00000000-0000-0000-0000-000000000975",
"views": {
"allWorkflowVersions": {
- "id": "00000000-0000-0000-0000-000000000962",
+ "id": "00000000-0000-0000-0000-000000000961",
"viewFieldGroups": {},
"viewFields": {
"name": {
- "id": "00000000-0000-0000-0000-000000000957",
+ "id": "00000000-0000-0000-0000-000000000956",
},
"runs": {
- "id": "00000000-0000-0000-0000-000000000961",
+ "id": "00000000-0000-0000-0000-000000000960",
},
"status": {
- "id": "00000000-0000-0000-0000-000000000959",
+ "id": "00000000-0000-0000-0000-000000000958",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000000960",
+ "id": "00000000-0000-0000-0000-000000000959",
},
"workflow": {
- "id": "00000000-0000-0000-0000-000000000958",
+ "id": "00000000-0000-0000-0000-000000000957",
},
},
"viewGroups": {},
},
"workflowVersionRecordPageFields": {
- "id": "00000000-0000-0000-0000-000000000975",
+ "id": "00000000-0000-0000-0000-000000000974",
"viewFieldGroups": {
"general": {
- "id": "00000000-0000-0000-0000-000000000973",
+ "id": "00000000-0000-0000-0000-000000000972",
},
"system": {
- "id": "00000000-0000-0000-0000-000000000974",
+ "id": "00000000-0000-0000-0000-000000000973",
},
},
"viewFields": {
"createdAt": {
- "id": "00000000-0000-0000-0000-000000000966",
+ "id": "00000000-0000-0000-0000-000000000965",
},
"createdBy": {
- "id": "00000000-0000-0000-0000-000000000968",
+ "id": "00000000-0000-0000-0000-000000000967",
},
"runs": {
- "id": "00000000-0000-0000-0000-000000000971",
+ "id": "00000000-0000-0000-0000-000000000970",
},
"status": {
- "id": "00000000-0000-0000-0000-000000000963",
+ "id": "00000000-0000-0000-0000-000000000962",
},
"steps": {
- "id": "00000000-0000-0000-0000-000000000967",
+ "id": "00000000-0000-0000-0000-000000000966",
},
"timelineActivities": {
- "id": "00000000-0000-0000-0000-000000000972",
+ "id": "00000000-0000-0000-0000-000000000971",
},
"trigger": {
- "id": "00000000-0000-0000-0000-000000000965",
+ "id": "00000000-0000-0000-0000-000000000964",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000000969",
+ "id": "00000000-0000-0000-0000-000000000968",
},
"updatedBy": {
- "id": "00000000-0000-0000-0000-000000000970",
+ "id": "00000000-0000-0000-0000-000000000969",
},
"workflow": {
- "id": "00000000-0000-0000-0000-000000000964",
+ "id": "00000000-0000-0000-0000-000000000963",
},
},
"viewGroups": {},
@@ -3721,119 +3715,119 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object
"workspaceMember": {
"fields": {
"accountOwnerForCompanies": {
- "id": "00000000-0000-0000-0000-000000000996",
+ "id": "00000000-0000-0000-0000-000000000995",
},
"agentChatThreadParticipants": {
- "id": "00000000-0000-0000-0000-000000001003",
+ "id": "00000000-0000-0000-0000-000000001002",
},
"agentChatThreads": {
- "id": "00000000-0000-0000-0000-000000001002",
+ "id": "00000000-0000-0000-0000-000000001001",
},
"agentMessages": {
- "id": "00000000-0000-0000-0000-000000001001",
+ "id": "00000000-0000-0000-0000-000000001000",
},
"assignedTasks": {
- "id": "00000000-0000-0000-0000-000000000994",
+ "id": "00000000-0000-0000-0000-000000000993",
},
"avatarUrl": {
- "id": "00000000-0000-0000-0000-000000000990",
+ "id": "00000000-0000-0000-0000-000000000989",
},
"blocklist": {
- "id": "00000000-0000-0000-0000-000000000998",
+ "id": "00000000-0000-0000-0000-000000000997",
},
"calendarEventParticipants": {
- "id": "00000000-0000-0000-0000-000000000999",
+ "id": "00000000-0000-0000-0000-000000000998",
},
"calendarStartDay": {
- "id": "00000000-0000-0000-0000-000000001007",
+ "id": "00000000-0000-0000-0000-000000001006",
},
"colorScheme": {
- "id": "00000000-0000-0000-0000-000000000986",
+ "id": "00000000-0000-0000-0000-000000000985",
},
"createdAt": {
- "id": "00000000-0000-0000-0000-000000000978",
+ "id": "00000000-0000-0000-0000-000000000977",
},
"createdBy": {
- "id": "00000000-0000-0000-0000-000000000981",
+ "id": "00000000-0000-0000-0000-000000000980",
},
"dateFormat": {
- "id": "00000000-0000-0000-0000-000000001005",
+ "id": "00000000-0000-0000-0000-000000001004",
},
"deletedAt": {
- "id": "00000000-0000-0000-0000-000000000980",
+ "id": "00000000-0000-0000-0000-000000000979",
},
"id": {
- "id": "00000000-0000-0000-0000-000000000977",
+ "id": "00000000-0000-0000-0000-000000000976",
},
"jobTitle": {
- "id": "00000000-0000-0000-0000-000000000992",
+ "id": "00000000-0000-0000-0000-000000000991",
},
"locale": {
- "id": "00000000-0000-0000-0000-000000000989",
+ "id": "00000000-0000-0000-0000-000000000988",
},
"messageParticipants": {
- "id": "00000000-0000-0000-0000-000000000997",
+ "id": "00000000-0000-0000-0000-000000000996",
},
"name": {
- "id": "00000000-0000-0000-0000-000000000985",
+ "id": "00000000-0000-0000-0000-000000000984",
},
"numberFormat": {
- "id": "00000000-0000-0000-0000-000000001008",
+ "id": "00000000-0000-0000-0000-000000001007",
},
"openRecordIn": {
- "id": "00000000-0000-0000-0000-000000000988",
+ "id": "00000000-0000-0000-0000-000000000987",
},
"ownedOpportunities": {
- "id": "00000000-0000-0000-0000-000000000995",
+ "id": "00000000-0000-0000-0000-000000000994",
},
"position": {
- "id": "00000000-0000-0000-0000-000000000983",
+ "id": "00000000-0000-0000-0000-000000000982",
},
"searchVector": {
- "id": "00000000-0000-0000-0000-000000000984",
+ "id": "00000000-0000-0000-0000-000000000983",
},
"timeFormat": {
- "id": "00000000-0000-0000-0000-000000001006",
+ "id": "00000000-0000-0000-0000-000000001005",
},
"timeZone": {
- "id": "00000000-0000-0000-0000-000000001004",
+ "id": "00000000-0000-0000-0000-000000001003",
},
"timelineActivities": {
- "id": "00000000-0000-0000-0000-000000001000",
+ "id": "00000000-0000-0000-0000-000000000999",
},
"uiScale": {
- "id": "00000000-0000-0000-0000-000000000987",
+ "id": "00000000-0000-0000-0000-000000000986",
},
"updatedAt": {
- "id": "00000000-0000-0000-0000-000000000979",
+ "id": "00000000-0000-0000-0000-000000000978",
},
"updatedBy": {
- "id": "00000000-0000-0000-0000-000000000982",
+ "id": "00000000-0000-0000-0000-000000000981",
},
"userEmail": {
- "id": "00000000-0000-0000-0000-000000000991",
+ "id": "00000000-0000-0000-0000-000000000990",
},
"userId": {
- "id": "00000000-0000-0000-0000-000000000993",
+ "id": "00000000-0000-0000-0000-000000000992",
},
},
- "id": "00000000-0000-0000-0000-000000001014",
+ "id": "00000000-0000-0000-0000-000000001013",
"views": {
"allWorkspaceMembers": {
- "id": "00000000-0000-0000-0000-000000001013",
+ "id": "00000000-0000-0000-0000-000000001012",
"viewFieldGroups": {},
"viewFields": {
"assignedTasks": {
- "id": "00000000-0000-0000-0000-000000001012",
+ "id": "00000000-0000-0000-0000-000000001011",
},
"createdAt": {
- "id": "00000000-0000-0000-0000-000000001010",
+ "id": "00000000-0000-0000-0000-000000001009",
},
"name": {
- "id": "00000000-0000-0000-0000-000000001009",
+ "id": "00000000-0000-0000-0000-000000001008",
},
"ownedOpportunities": {
- "id": "00000000-0000-0000-0000-000000001011",
+ "id": "00000000-0000-0000-0000-000000001010",
},
},
"viewGroups": {},
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts
index b68433361a1..0d23e297046 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts
@@ -97,7 +97,7 @@ describe('agent history workspace metadata', () => {
>
> = {
agentChatThread: {
- readability: MetadataReadability.INHERITED,
+ readability: MetadataReadability.PRIVATE,
writability: MetadataWritability.OPEN,
},
agentChatThreadTarget: {
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
index d6d621f79dc..0747f512ce5 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
@@ -23,7 +23,6 @@ const INHERITED_STANDARD_OBJECT_PARENT_FIELDS = {
messageThreadTarget: STANDARD_OBJECT_FIELDS.messageThreadTarget.messageThread,
calendarEventTarget: STANDARD_OBJECT_FIELDS.calendarEventTarget.calendarEvent,
agentChatThreadTarget: STANDARD_OBJECT_FIELDS.agentChatThreadTarget.thread,
- agentChatThread: STANDARD_OBJECT_FIELDS.agentChatThread.workflowRun,
} as const;
describe('Standard object readability', () => {
@@ -68,6 +67,7 @@ describe('Standard object readability', () => {
STANDARD_OBJECTS.agentMessagePart.universalIdentifier,
STANDARD_OBJECTS.agentTurn.universalIdentifier,
STANDARD_OBJECTS.agentTurnEvaluation.universalIdentifier,
+ STANDARD_OBJECTS.agentChatThread.universalIdentifier,
STANDARD_OBJECTS.agentChatThreadParticipant.universalIdentifier,
STANDARD_OBJECTS.campaignDelivery.universalIdentifier,
@@ -111,6 +111,13 @@ describe('Standard object readability', () => {
},
);
+ it('declares agentChatThread PRIVATE, read through its own grants', () => {
+ expect(findStandardFlatObjectMetadata('agentChatThread')).toMatchObject({
+ readability: MetadataReadability.PRIVATE,
+ readabilityParentFieldUniversalIdentifiers: null,
+ });
+ });
+
it('declares agentChatThreadParticipant PRIVATE, written only by the chat resolvers', () => {
expect(
findStandardFlatObjectMetadata('agentChatThreadParticipant'),
@@ -182,25 +189,10 @@ describe('Standard object readability', () => {
).toContainEqual({
joinColumnName: 'targetAgentChatThreadId',
parentNameSingular: 'agentChatThread',
- parentReadability: MetadataReadability.INHERITED,
+ parentReadability: MetadataReadability.PRIVATE,
});
});
- it('resolves its workflow run as the only parent of an agentChatThread', () => {
- expect(
- resolveParents('agentChatThread').map((parent) =>
- parent.kind === 'column'
- ? {
- joinColumnName: parent.joinColumnName,
- parentNameSingular: parent.parentFlatObjectMetadata.nameSingular,
- }
- : parent.kind,
- ),
- ).toEqual([
- { joinColumnName: 'workflowRunId', parentNameSingular: 'workflowRun' },
- ]);
- });
-
it('resolves every target of a noteTarget as its parent, not the note', () => {
const parents = resolveParents('noteTarget').map((parent) =>
parent.kind === 'column'
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts
index cf643708fdf..ef49c383fcf 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts
@@ -632,37 +632,6 @@ export const buildAgentChatThreadStandardFlatFieldMetadatas = (
writability: MetadataWritability.SYSTEM,
isAuditLogged: false,
},
- workflowRun: {
- ...createStandardRelationFieldFlatMetadata({
- ...args,
- context: {
- fieldName: 'workflowRun',
- type: FieldMetadataType.RELATION,
- label: i18nLabel(
- msg({ message: 'Workflow Run', context: 'fieldMetadata.label' }),
- ),
- description: i18nLabel(
- msg({
- message: 'Workflow run whose agent step held this conversation',
- context: 'fieldMetadata.description',
- }),
- ),
- icon: 'IconHistoryToggle',
- isUIEditable: false,
- isNullable: true,
- targetObjectName: 'workflowRun',
- targetFieldName: 'agentChatThreads',
- morphId: null,
- settings: {
- relationType: RelationType.MANY_TO_ONE,
- onDelete: RelationOnDeleteAction.CASCADE,
- joinColumnName: 'workflowRunId',
- },
- },
- }),
- writability: MetadataWritability.SYSTEM,
- isAuditLogged: false,
- },
messages: {
...createStandardRelationFieldFlatMetadata({
...args,
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.ts
index 7ce07eb0e2c..77aa217b3ab 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.ts
@@ -599,36 +599,6 @@ export const buildWorkflowRunStandardFlatFieldMetadatas = ({
twentyStandardApplicationId,
now,
}),
- agentChatThreads: createStandardRelationFieldFlatMetadata({
- objectName,
- workspaceId,
- context: {
- type: FieldMetadataType.RELATION,
- morphId: null,
- fieldName: 'agentChatThreads',
- label: i18nLabel(
- msg({ message: `Conversations`, context: 'fieldMetadata.label' }),
- ),
- description: i18nLabel(
- msg({
- message: `Conversations held by the run's agent steps`,
- context: 'fieldMetadata.description',
- }),
- ),
- icon: 'IconMessage',
- isNullable: true,
- isUIEditable: false,
- targetObjectName: 'agentChatThread',
- targetFieldName: 'workflowRun',
- settings: {
- relationType: RelationType.ONE_TO_MANY,
- },
- },
- standardObjectMetadataRelatedEntityIds,
- dependencyFlatEntityMaps,
- twentyStandardApplicationId,
- now,
- }),
timelineActivities: createStandardRelationFieldFlatMetadata({
objectName,
workspaceId,
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-agent-chat-thread-standard-flat-index-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-agent-chat-thread-standard-flat-index-metadata.util.ts
index 3618f882ed5..db5d5889d57 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-agent-chat-thread-standard-flat-index-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-agent-chat-thread-standard-flat-index-metadata.util.ts
@@ -25,13 +25,4 @@ export const buildAgentChatThreadStandardFlatIndexMetadatas = (
indexWhereClause: null,
},
}),
- workflowRunIndex: createStandardIndexFlatMetadata({
- ...args,
- context: {
- indexName: 'workflowRunIndex',
- relatedFieldNames: ['workflowRun'],
- isUnique: false,
- indexWhereClause: null,
- },
- }),
});
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
index bee0bb531f7..ed6ad72e92e 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
@@ -53,9 +53,7 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isAuditLogged: false,
isUIEditable: true,
isUICreatable: false,
- // Read by whoever reads its workflow run; with no run it reads only through its own grants, like a PRIVATE record
- readability: MetadataReadability.INHERITED,
- readabilityParentFieldMetadataNames: ['workflowRun'],
+ readability: MetadataReadability.PRIVATE,
writability: MetadataWritability.OPEN,
labelIdentifierFieldMetadataName: 'title',
},
diff --git a/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.ts b/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.ts
index 2784b9f1b11..aed4b44d99d 100644
--- a/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.ts
+++ b/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.ts
@@ -1,4 +1,3 @@
-import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { registerEnumType } from '@nestjs/graphql';
import { type ActorMetadata } from 'twenty-shared/types';
@@ -72,6 +71,5 @@ export class WorkflowRunWorkspaceEntity extends BaseWorkspaceEntity {
workflowId: string | null;
coreWorkflowId: string | null;
coreWorkflowVersionId: string | null;
- agentChatThreads: EntityRelation<AgentChatThreadWorkspaceEntity[]>;
timelineActivities: EntityRelation<TimelineActivityWorkspaceEntity[]>;
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/__tests__/validate-workflow-conversation-step.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/__tests__/validate-workflow-conversation-step.util.spec.ts
new file mode 100644
index 00000000000..4ed5ba4a5f1
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/__tests__/validate-workflow-conversation-step.util.spec.ts
@@ -0,0 +1,56 @@
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import { validateWorkflowConversationStep } from 'src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-conversation-step.util';
+import { type WorkflowSendChatMessageAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+const buildStep = (
+ conversation: WorkflowSendChatMessageAction['settings']['input']['conversation'],
+): WorkflowSendChatMessageAction =>
+ ({
+ id: 'step-id',
+ name: 'Send to Inbox',
+ type: WorkflowActionType.SEND_CHAT_MESSAGE,
+ valid: true,
+ settings: {
+ outputSchema: {},
+ errorHandlingOptions: {
+ retryOnFailure: { value: 0 },
+ continueOnFailure: { value: false },
+ },
+ input: { workspaceMemberId: '', title: '', text: '', conversation },
+ },
+ }) as WorkflowSendChatMessageAction;
+
+describe('validateWorkflowConversationStep', () => {
+ it.each([undefined, { scope: 'RUN' as const }, { scope: 'STEP' as const }])(
+ 'accepts a conversation that needs no key: %o',
+ (conversation) => {
+ expect(validateWorkflowConversationStep(buildStep(conversation))).toEqual(
+ [],
+ );
+ },
+ );
+
+ it('accepts a shared conversation with a key', () => {
+ expect(
+ validateWorkflowConversationStep(
+ buildStep({ scope: 'KEY', key: '{{trigger.object.id}}' }),
+ ),
+ ).toEqual([]);
+ });
+
+ it.each([undefined, '', ' '])(
+ 'blocks activation of a shared conversation without a key: %o',
+ (key) => {
+ expect(
+ validateWorkflowConversationStep(buildStep({ scope: 'KEY', key })),
+ ).toEqual([
+ expect.objectContaining({
+ code: 'CONVERSATION_MISSING_KEY',
+ severity: 'error',
+ stepId: 'step-id',
+ }),
+ ]);
+ },
+ );
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-conversation-step.util.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-conversation-step.util.ts
new file mode 100644
index 00000000000..429527aa02f
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-conversation-step.util.ts
@@ -0,0 +1,30 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type WorkflowValidationIssue } from 'twenty-shared/workflow';
+
+import {
+ type WorkflowAiAgentAction,
+ type WorkflowSendChatMessageAction,
+} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+// A draft can pick sharing by key before typing the key, so it is caught before activation rather than on save
+export const validateWorkflowConversationStep = (
+ step: WorkflowAiAgentAction | WorkflowSendChatMessageAction,
+): WorkflowValidationIssue[] => {
+ const conversation = step.settings?.input?.conversation;
+
+ if (
+ conversation?.scope !== 'KEY' ||
+ isNonEmptyString(conversation.key?.trim())
+ ) {
+ return [];
+ }
+
+ return [
+ {
+ severity: 'error',
+ code: 'CONVERSATION_MISSING_KEY',
+ message: `Step "${step.name ?? step.id}" shares its conversation by key but has no key.`,
+ stepId: step.id,
+ },
+ ];
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts
index 550f2b47519..55dc367c9de 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts
@@ -17,6 +17,7 @@ import {
import { getWorkflowRecordStepMetadataIssues } from 'src/modules/workflow/workflow-builder/workflow-validation/utils/get-workflow-record-step-metadata-issues.util';
import { validateWorkflowAiAgentStep } from 'src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-ai-agent-step.util';
import { validateWorkflowClassifyStep } from 'src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-classify-step.util';
+import { validateWorkflowConversationStep } from 'src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-conversation-step.util';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { type WorkflowTrigger } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
@@ -72,7 +73,14 @@ export class WorkflowVersionValidationWorkspaceService {
const stepTypeIssues = steps.flatMap((step) => {
if (step.type === WorkflowActionType.AI_AGENT) {
- return validateWorkflowAiAgentStep(step);
+ return [
+ ...validateWorkflowAiAgentStep(step),
+ ...validateWorkflowConversationStep(step),
+ ];
+ }
+
+ if (step.type === WorkflowActionType.SEND_CHAT_MESSAGE) {
+ return validateWorkflowConversationStep(step);
}
if (step.type === WorkflowActionType.CLASSIFY) {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.module.ts
new file mode 100644
index 00000000000..f3c2f6c5eb8
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.module.ts
@@ -0,0 +1,11 @@
+import { Module } from '@nestjs/common';
+
+import { WorkflowCoreModule } from 'src/engine/core-modules/workflow/workflow-core.module';
+import { WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';
+
+@Module({
+ imports: [WorkflowCoreModule],
+ providers: [WorkflowRunInboxSenderWorkspaceService],
+ exports: [WorkflowRunInboxSenderWorkspaceService],
+})
+export class WorkflowRunInboxSenderModule {}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service.ts
new file mode 100644
index 00000000000..aff320774df
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service.ts
@@ -0,0 +1,68 @@
+import { Injectable } from '@nestjs/common';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';
+import { type AgentInboxSender } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+import {
+ WorkflowStepExecutorException,
+ WorkflowStepExecutorExceptionCode,
+} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+import { type WorkflowRunInfo } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
+
+// Every run carries the core workflow it was started from, which is the
+// identity its conversations are attributed to.
+@Injectable()
+export class WorkflowRunInboxSenderWorkspaceService {
+ constructor(
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly workflowCoreSyncService: WorkflowCoreSyncService,
+ ) {}
+
+ async findRunSenderOrThrow({
+ workflowRunId,
+ workspaceId,
+ }: WorkflowRunInfo): Promise<
+ Extract<AgentInboxSender, { type: 'workflow' }>
+ > {
+ const workflowRun =
+ await this.workspaceOrmManager.executeInWorkspaceContext(
+ () =>
+ this.workspaceOrmManager
+ .getRepository<WorkflowRunWorkspaceEntity>('workflowRun', {
+ shouldBypassPermissionChecks: true,
+ })
+ .findOne({
+ where: { id: workflowRunId },
+ select: ['id', 'coreWorkflowId'],
+ }),
+ buildSystemAuthContext(workspaceId),
+ );
+
+ const workflow = isDefined(workflowRun?.coreWorkflowId)
+ ? await this.workflowCoreSyncService.findCoreWorkflowById(
+ workspaceId,
+ workflowRun.coreWorkflowId,
+ )
+ : null;
+
+ if (!isDefined(workflow)) {
+ throw new WorkflowStepExecutorException(
+ 'Workflow run has no workflow',
+ WorkflowStepExecutorExceptionCode.INTERNAL_ERROR,
+ );
+ }
+
+ return {
+ type: 'workflow',
+ workflowId: workflow.id,
+ workflowName: isNonEmptyString(workflow.name)
+ ? workflow.name
+ : 'Untitled',
+ };
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/resolve-conversation-thread-key.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/resolve-conversation-thread-key.util.spec.ts
new file mode 100644
index 00000000000..0991064ecce
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/resolve-conversation-thread-key.util.spec.ts
@@ -0,0 +1,65 @@
+import { resolveConversationThreadKey } from 'src/modules/workflow/workflow-executor/utils/resolve-conversation-thread-key.util';
+
+const RUN_ID = 'run-1';
+const STEP_EXECUTION_KEY = 'step-1:iterator=2';
+
+describe('resolveConversationThreadKey', () => {
+ it('falls back to the default scope when the step sets none', () => {
+ expect(
+ resolveConversationThreadKey({
+ conversation: undefined,
+ defaultScope: 'RUN',
+ workflowRunId: RUN_ID,
+ stepExecutionKey: STEP_EXECUTION_KEY,
+ }),
+ ).toBe(RUN_ID);
+
+ expect(
+ resolveConversationThreadKey({
+ conversation: undefined,
+ defaultScope: 'STEP',
+ workflowRunId: RUN_ID,
+ stepExecutionKey: STEP_EXECUTION_KEY,
+ }),
+ ).toBe(`${RUN_ID}:${STEP_EXECUTION_KEY}`);
+ });
+
+ it('keeps a run conversation separate from each execution of a step', () => {
+ const runKey = resolveConversationThreadKey({
+ conversation: { scope: 'RUN' },
+ defaultScope: 'STEP',
+ workflowRunId: RUN_ID,
+ stepExecutionKey: STEP_EXECUTION_KEY,
+ });
+ const stepKey = resolveConversationThreadKey({
+ conversation: { scope: 'STEP' },
+ defaultScope: 'RUN',
+ workflowRunId: RUN_ID,
+ stepExecutionKey: STEP_EXECUTION_KEY,
+ });
+
+ expect(runKey).not.toBe(stepKey);
+ });
+
+ it('uses a trimmed custom key that cannot equal a run conversation', () => {
+ expect(
+ resolveConversationThreadKey({
+ conversation: { scope: 'KEY', key: ` ${RUN_ID} ` },
+ defaultScope: 'RUN',
+ workflowRunId: RUN_ID,
+ stepExecutionKey: STEP_EXECUTION_KEY,
+ }),
+ ).toBe(`key:${RUN_ID}`);
+ });
+
+ it('refuses a key scope without a key', () => {
+ expect(() =>
+ resolveConversationThreadKey({
+ conversation: { scope: 'KEY', key: ' ' },
+ defaultScope: 'RUN',
+ workflowRunId: RUN_ID,
+ stepExecutionKey: STEP_EXECUTION_KEY,
+ }),
+ ).toThrow('A conversation key is required');
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/resolve-conversation-thread-key.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/resolve-conversation-thread-key.util.ts
new file mode 100644
index 00000000000..20f96f65f06
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/resolve-conversation-thread-key.util.ts
@@ -0,0 +1,48 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+import {
+ type WorkflowConversation,
+ type WorkflowConversationScope,
+} from 'twenty-shared/workflow';
+
+import {
+ WorkflowStepExecutorException,
+ WorkflowStepExecutorExceptionCode,
+} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+
+// The thread key picks the conversation with the recipient. A custom key is
+// prefixed so it never names the conversation of a run whose id it happens to equal.
+export const resolveConversationThreadKey = ({
+ conversation,
+ defaultScope,
+ workflowRunId,
+ stepExecutionKey,
+}: {
+ conversation: WorkflowConversation | undefined;
+ defaultScope: WorkflowConversationScope;
+ workflowRunId: string;
+ stepExecutionKey: string;
+}): string => {
+ const scope = conversation?.scope ?? defaultScope;
+
+ switch (scope) {
+ case 'RUN':
+ return workflowRunId;
+ case 'STEP':
+ return `${workflowRunId}:${stepExecutionKey}`;
+ case 'KEY': {
+ const key = isDefined(conversation?.key)
+ ? String(conversation.key).trim()
+ : '';
+
+ if (!isNonEmptyString(key)) {
+ throw new WorkflowStepExecutorException(
+ 'A conversation key is required to share a conversation by key',
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ );
+ }
+
+ return `key:${key}`;
+ }
+ }
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
index 9eebff6f33b..9689cdb6283 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
@@ -1,12 +1,12 @@
import { Injectable, Logger } from '@nestjs/common';
-import { isNonEmptyString } from '@sniptt/guards';
+import { isNonEmptyString, isString } from '@sniptt/guards';
import {
ASK_QUESTION_TOOL_NAME,
REQUEST_FORM_TOOL_NAME,
} from 'twenty-shared/ai';
-import { isDefined, resolveInput } from 'twenty-shared/utils';
+import { isDefined, isValidUuid, resolveInput } from 'twenty-shared/utils';
import { type WorkflowRunStepLog } from 'twenty-shared/workflow';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
@@ -28,7 +28,9 @@ import {
import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';
+import { 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 { resolveConversationThreadKey } from 'src/modules/workflow/workflow-executor/utils/resolve-conversation-thread-key.util';
import { APPLICATION_BOUND_AGENT_EXCLUDED_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant';
import { WORKFLOW_AGENT_WAIT_PROMPT } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-prompt.constant';
import { createWorkflowAgentWaitTools } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/tools/create-workflow-agent-wait-tools.util';
@@ -41,6 +43,7 @@ import {
type RecordedConversation,
WorkflowAgentConversationWorkspaceService,
} from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
+import { type WorkflowAiAgentActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type';
import { mergeAiAgentStepLogs } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/merge-ai-agent-step-logs.util';
import { buildAiAgentStepLog } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util';
import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';
@@ -83,6 +86,36 @@ export class AiAgentWorkflowAction implements WorkflowAction {
const { agentId, prompt, humanInputInstructions } = step.settings.input;
const workspaceId = runInfo.workspaceId;
+ const workflowStep = {
+ workflowRunId: runInfo.workflowRunId,
+ stepId: currentStepId,
+ };
+ const { workspaceMemberId: recipientWorkspaceMemberId, conversation } =
+ resolveInput(
+ {
+ workspaceMemberId: step.settings.input.workspaceMemberId,
+ conversation: step.settings.input.conversation,
+ },
+ context,
+ ) as Pick<
+ WorkflowAiAgentActionInput,
+ 'workspaceMemberId' | 'conversation'
+ >;
+
+ // a variable can resolve to any value, so anything but a member id or nothing is refused
+ if (
+ isDefined(recipientWorkspaceMemberId) &&
+ recipientWorkspaceMemberId !== '' &&
+ !(
+ isString(recipientWorkspaceMemberId) &&
+ isValidUuid(recipientWorkspaceMemberId)
+ )
+ ) {
+ throw new WorkflowStepExecutorException(
+ 'Recipient must be a workspace member',
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ );
+ }
let agent: AgentEntity | null = null;
@@ -122,22 +155,57 @@ export class AiAgentWorkflowAction implements WorkflowAction {
const resolvedPrompt = resolveInput(prompt, context) as string;
+ // a resumed step continues where it paused, any other opens the conversation its key names
+ const conversationThread = isDefined(resumedThreadId)
+ ? {
+ threadId: resumedThreadId,
+ isResumed: true,
+ priorMessages: await this.conversationReaderService.loadMessages({
+ workspaceId,
+ threadId: resumedThreadId,
+ }),
+ }
+ : {
+ ...(await this.workflowAgentConversationService.openConversation({
+ runInfo,
+ stepId: currentStepId,
+ title: step.name,
+ recipientWorkspaceMemberId: isNonEmptyString(
+ recipientWorkspaceMemberId,
+ )
+ ? recipientWorkspaceMemberId
+ : null,
+ threadKey: resolveConversationThreadKey({
+ conversation,
+ defaultScope: 'STEP',
+ workflowRunId: runInfo.workflowRunId,
+ stepExecutionKey: buildStepExecutionKey({
+ stepId: currentStepId,
+ steps,
+ context,
+ }),
+ }),
+ })),
+ isResumed: false,
+ };
+
// A record of the step, not its outcome, so a write failure must not fail the step
const recordConversation = (
executionResult: AgentExecutionResult,
): Promise<RecordedConversation | null> =>
- (isDefined(resumedThreadId)
+ (conversationThread.isResumed
? this.workflowAgentConversationService.recordContinuation({
workspaceId,
- threadId: resumedThreadId,
+ threadId: conversationThread.threadId,
+ workflowStep,
title: step.name,
agentId: agent?.id ?? null,
executionResult,
})
: this.workflowAgentConversationService.recordExecution({
workspaceId,
- workflowRunId: runInfo.workflowRunId,
- stepId: currentStepId,
+ threadId: conversationThread.threadId,
+ workflowStep,
title: step.name,
agentId: agent?.id ?? null,
prompt: resolvedPrompt,
@@ -161,15 +229,10 @@ export class AiAgentWorkflowAction implements WorkflowAction {
const executionResult = await this.aiAgentExecutionService.executeAgent({
agent,
- ...(isDefined(resumedThreadId)
- ? {
- messages: [],
- priorMessages: await this.conversationReaderService.loadMessages({
- workspaceId,
- threadId: resumedThreadId,
- }),
- }
- : { messages: [{ role: 'user', content: resolvedPrompt }] }),
+ messages: conversationThread.isResumed
+ ? []
+ : [{ role: 'user', content: resolvedPrompt }],
+ priorMessages: conversationThread.priorMessages,
baseSystemPrompt: canAskForHumanInput
? `${WORKFLOW_BASE_SYSTEM_PROMPT}\n\n${WORKFLOW_AGENT_WAIT_PROMPT}\n\n${WORKFLOW_AGENT_HUMAN_INPUT_PROMPT}\n\n${trimmedHumanInputInstructions}`
: `${WORKFLOW_BASE_SYSTEM_PROMPT}\n\n${WORKFLOW_AGENT_WAIT_PROMPT}`,
@@ -204,11 +267,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
const durationMs = Date.now() - startedAtMs;
- // Only executions that ask get a conversation, saving a thread per execution for looping agents
- const recordedConversation =
- isDefined(resumedThreadId) || executionResult.isPaused
- ? await recordConversation(executionResult)
- : null;
+ const recordedConversation = await recordConversation(executionResult);
await this.persistStepLog({
workflowRunId: runInfo.workflowRunId,
@@ -250,6 +309,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
}
async resolveWait({
+ step,
stepInfo,
outcome,
runInfo,
@@ -266,6 +326,10 @@ export class AiAgentWorkflowAction implements WorkflowAction {
await this.workflowAgentConversationService.recordWaitOutcome({
workspaceId: runInfo.workspaceId,
threadId,
+ workflowStep: {
+ workflowRunId: runInfo.workflowRunId,
+ stepId: step.id,
+ },
toolOutput: buildWaitOutcomeToolOutput(outcome),
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts
new file mode 100644
index 00000000000..e778edc2e5a
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/__tests__/workflow-agent-conversation.workspace-service.spec.ts
@@ -0,0 +1,318 @@
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
+
+const RUN_INFO = { workspaceId: 'workspace-id', workflowRunId: 'run-id' };
+const SENDER = {
+ type: 'workflow' as const,
+ workflowId: 'workflow-id',
+ workflowName: 'New deals',
+};
+const PRIOR_MESSAGES = [{ id: 'message-id', role: 'assistant', parts: [] }];
+
+const OPEN_ARGS = {
+ runInfo: RUN_INFO,
+ stepId: 'step-id',
+ title: 'Draft the quote',
+ threadKey: 'run-id:step-id',
+};
+
+const buildService = ({
+ creatorWorkspaceMemberId = 'creator-id' as string | null,
+ isCreated = true,
+} = {}) => {
+ const messagePartRepository = { update: jest.fn() };
+ const messageRepository = { find: jest.fn().mockResolvedValue([]) };
+ const agentInboxService = {
+ openThread: jest.fn().mockImplementation(({ workspaceMemberId }) =>
+ Promise.resolve({
+ thread: { id: `thread-for-${workspaceMemberId ?? 'nobody'}` },
+ isCreated,
+ }),
+ ),
+ };
+ const conversationReaderService = {
+ loadMessages: jest.fn().mockResolvedValue(PRIOR_MESSAGES),
+ };
+ const workflowRunWorkspaceService = {
+ setStepThreadId: jest.fn().mockResolvedValue(undefined),
+ };
+ const workflowRunRecordShareService = {
+ findCreatorWorkspaceMemberId: jest
+ .fn()
+ .mockResolvedValue(creatorWorkspaceMemberId),
+ };
+
+ const service = new WorkflowAgentConversationWorkspaceService(
+ messageRepository as never,
+ messagePartRepository as never,
+ agentInboxService as never,
+ conversationReaderService as never,
+ {} as never,
+ {} as never,
+ {
+ findRunSenderOrThrow: jest.fn().mockResolvedValue(SENDER),
+ } as never,
+ workflowRunWorkspaceService as never,
+ workflowRunRecordShareService as never,
+ );
+
+ return {
+ service,
+ agentInboxService,
+ conversationReaderService,
+ messageRepository,
+ messagePartRepository,
+ workflowRunWorkspaceService,
+ };
+};
+
+describe('WorkflowAgentConversationWorkspaceService', () => {
+ describe('openConversation', () => {
+ it('opens the conversation with the recipient the step names, filed under done', async () => {
+ const { service, agentInboxService, workflowRunWorkspaceService } =
+ buildService();
+
+ const conversation = await service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ });
+
+ expect(conversation).toEqual({
+ threadId: 'thread-for-recipient-id',
+ priorMessages: [],
+ });
+ expect(agentInboxService.openThread).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ sender: SENDER,
+ workspaceMemberId: 'recipient-id',
+ threadKey: 'run-id:step-id',
+ title: 'Draft the quote',
+ isArchivedOnCreate: true,
+ });
+ expect(workflowRunWorkspaceService.setStepThreadId).toHaveBeenCalledWith({
+ stepId: 'step-id',
+ threadId: 'thread-for-recipient-id',
+ workflowRunId: 'run-id',
+ workspaceId: 'workspace-id',
+ });
+ });
+
+ it("falls back to the workflow creator's inbox when the step names no recipient", async () => {
+ const { service } = buildService();
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: null,
+ }),
+ ).resolves.toMatchObject({ threadId: 'thread-for-creator-id' });
+ });
+
+ it('keeps a conversation no inbox receives when the creator cannot have it', async () => {
+ const { service, agentInboxService } = buildService();
+
+ agentInboxService.openThread.mockRejectedValueOnce(
+ new AiException(
+ 'Thread owner is no longer a workspace member',
+ AiExceptionCode.THREAD_NOT_FOUND,
+ ),
+ );
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: null,
+ }),
+ ).resolves.toMatchObject({ threadId: 'thread-for-nobody' });
+ });
+
+ it('keeps a conversation no inbox receives for a workflow without a member creator', async () => {
+ const { service } = buildService({ creatorWorkspaceMemberId: null });
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: null,
+ }),
+ ).resolves.toMatchObject({ threadId: 'thread-for-nobody' });
+ });
+
+ it('fails when the named recipient cannot have the conversation', async () => {
+ const { service, agentInboxService } = buildService();
+
+ agentInboxService.openThread.mockRejectedValueOnce(
+ new AiException(
+ 'Thread owner is no longer a workspace member',
+ AiExceptionCode.THREAD_NOT_FOUND,
+ ),
+ );
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ }),
+ ).rejects.toMatchObject({ code: AiExceptionCode.THREAD_NOT_FOUND });
+ });
+
+ it('starts its own conversation when the recipient deleted the one its key names', async () => {
+ const { service, agentInboxService } = buildService();
+
+ agentInboxService.openThread.mockResolvedValueOnce({
+ thread: { id: 'deleted-thread-id', deletedAt: '2026-01-01' },
+ isCreated: false,
+ });
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ }),
+ ).resolves.toEqual({
+ threadId: 'thread-for-recipient-id',
+ priorMessages: [],
+ });
+ expect(agentInboxService.openThread).toHaveBeenLastCalledWith(
+ expect.objectContaining({ threadKey: 'run-id:step-id:run-id:step-id' }),
+ );
+ });
+
+ it('starts its own conversation while the one its key names waits on another answer', async () => {
+ const { service, agentInboxService } = buildService();
+
+ agentInboxService.openThread.mockResolvedValueOnce({
+ thread: {
+ id: 'waiting-thread-id',
+ pendingQuestionMessageId: 'question-message-id',
+ },
+ isCreated: false,
+ });
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ }),
+ ).resolves.toEqual({
+ threadId: 'thread-for-recipient-id',
+ priorMessages: [],
+ });
+ });
+
+ it('fails when the recipient also deleted the conversation this execution started', async () => {
+ const { service, agentInboxService } = buildService();
+
+ agentInboxService.openThread.mockResolvedValue({
+ thread: { id: 'deleted-thread-id', deletedAt: '2026-01-01' },
+ isCreated: false,
+ });
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ }),
+ ).rejects.toThrow('The recipient deleted this conversation');
+ });
+
+ it('continues from what an existing conversation holds', async () => {
+ const { service, conversationReaderService } = buildService({
+ isCreated: false,
+ });
+
+ await expect(
+ service.openConversation({
+ ...OPEN_ARGS,
+ recipientWorkspaceMemberId: 'recipient-id',
+ }),
+ ).resolves.toEqual({
+ threadId: 'thread-for-recipient-id',
+ priorMessages: PRIOR_MESSAGES,
+ });
+ expect(conversationReaderService.loadMessages).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-for-recipient-id',
+ });
+ });
+ });
+
+ describe('recordWaitOutcome', () => {
+ const waitPart = (id: string, workflowStep: Record<string, string>) => ({
+ id,
+ toolName: 'wait_for_duration',
+ toolOutput: { result: { status: 'pending' }, workflowStep },
+ });
+
+ it("settles the step's own wait, not another run's waiting in the same conversation", async () => {
+ const { service, messageRepository, messagePartRepository } =
+ buildService();
+
+ messageRepository.find.mockResolvedValue([
+ {
+ parts: [
+ waitPart('other-run-part', {
+ workflowRunId: 'other-run-id',
+ stepId: 'step-id',
+ }),
+ ],
+ },
+ {
+ parts: [
+ waitPart('other-step-part', {
+ workflowRunId: 'run-id',
+ stepId: 'other-step-id',
+ }),
+ ],
+ },
+ {
+ parts: [
+ waitPart('own-part', {
+ workflowRunId: 'run-id',
+ stepId: 'step-id',
+ }),
+ ],
+ },
+ ]);
+
+ await service.recordWaitOutcome({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ workflowStep: { workflowRunId: 'run-id', stepId: 'step-id' },
+ toolOutput: { success: true },
+ });
+
+ expect(messagePartRepository.update).toHaveBeenCalledWith(
+ 'workspace-id',
+ { id: 'own-part' },
+ { toolOutput: { success: true } },
+ );
+ });
+
+ it('refuses to settle a wait the step never posted', async () => {
+ const { service, messageRepository } = buildService();
+
+ messageRepository.find.mockResolvedValue([
+ {
+ parts: [
+ waitPart('other-run-part', {
+ workflowRunId: 'other-run-id',
+ stepId: 'step-id',
+ }),
+ ],
+ },
+ ]);
+
+ await expect(
+ service.recordWaitOutcome({
+ workspaceId: 'workspace-id',
+ threadId: 'thread-id',
+ workflowStep: { workflowRunId: 'run-id', stepId: 'step-id' },
+ toolOutput: { success: true },
+ }),
+ ).rejects.toMatchObject({ code: AiExceptionCode.TOOL_CALL_NOT_FOUND });
+ });
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
index 33e8fde18ad..ef5fcf2a05e 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
@@ -1,35 +1,52 @@
import { Injectable, Logger } from '@nestjs/common';
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
+import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
+import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util';
+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
+import { type ToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-chat/types/tool-call-workflow-step.type';
+import { findLastMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util';
+import { readToolCallWorkflowStep } from 'src/engine/metadata-modules/ai/ai-chat/utils/read-tool-call-workflow-step.util';
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
-import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentConversationReaderService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-reader.service';
import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
-import { type RecordableAgentExecution } from 'src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type';
-import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
-import { isAwaitingPausingToolOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/is-awaiting-pausing-tool-output.util';
-import { WORKFLOW_AGENT_WAIT_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant';
-import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-import { findLastMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-last-message-text.util';
-import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
-import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
+import { type RecordableAgentExecution } from 'src/engine/metadata-modules/ai/ai-history/types/recordable-agent-execution.type';
import {
AiException,
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
+import {
+ WorkflowStepExecutorException,
+ WorkflowStepExecutorExceptionCode,
+} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+import { WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';
+import { type WorkflowRunInfo } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
+import { WORKFLOW_AGENT_WAIT_TOOL_NAMES } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-wait-tool-names.constant';
+import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
const RECENT_MESSAGES_TO_SEARCH_FOR_WAIT = 50;
+export type OpenedConversation = {
+ threadId: string;
+ // what the conversation held before this execution, which the agent continues from
+ priorMessages: ExtendedUIMessage[];
+};
+
export type RecordedConversation = {
threadId: string;
isAwaitingAnswer: boolean;
};
-// One conversation per execution, so a loop iteration or retry never reads or continues another's messages.
-// It belongs to the run, and is owned by the workflow's creator so a call waiting on input reaches their inbox.
+// Every execution records its conversation through the inbox, with the step's
+// recipient or else the workflow's creator. A conversation the execution opens is
+// filed under done, and only comes back to the inbox when the agent needs them.
@Injectable()
export class WorkflowAgentConversationWorkspaceService {
private readonly logger = new Logger(
@@ -37,22 +54,95 @@ export class WorkflowAgentConversationWorkspaceService {
);
constructor(
- @InjectAgentHistoryRepository('agentChatThread')
- private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
@InjectAgentHistoryRepository('agentMessage')
private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,
@InjectAgentHistoryRepository('agentMessagePart')
private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,
+ private readonly agentInboxService: AgentInboxService,
+ private readonly conversationReaderService: AgentConversationReaderService,
private readonly conversationWriterService: AgentConversationWriterService,
private readonly threadService: AgentChatThreadService,
+ private readonly workflowRunInboxSenderService: WorkflowRunInboxSenderWorkspaceService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
private readonly workflowRunRecordShareService: WorkflowRunRecordShareService,
) {}
+ async openConversation({
+ runInfo,
+ stepId,
+ title,
+ recipientWorkspaceMemberId,
+ threadKey,
+ }: {
+ runInfo: WorkflowRunInfo;
+ stepId: string;
+ title: string;
+ recipientWorkspaceMemberId: string | null;
+ threadKey: string;
+ }): Promise<OpenedConversation> {
+ const { workspaceId, workflowRunId } = runInfo;
+ const sender =
+ await this.workflowRunInboxSenderService.findRunSenderOrThrow(runInfo);
+ const openThreadUnderKey = (key: string) => {
+ const openThread = (workspaceMemberId: string | null) =>
+ this.agentInboxService.openThread({
+ workspaceId,
+ sender,
+ workspaceMemberId,
+ threadKey: key,
+ title,
+ isArchivedOnCreate: true,
+ });
+
+ return isDefined(recipientWorkspaceMemberId)
+ ? openThread(recipientWorkspaceMemberId)
+ : this.openThreadWithCreator({
+ workspaceId,
+ coreWorkflowId: sender.workflowId,
+ openThread,
+ });
+ };
+
+ const keyedConversation = await openThreadUnderKey(threadKey);
+
+ // a conversation the recipient deleted is not written to again, and one already waiting on an answer
+ // has no room for another question, so this execution starts its own
+ const isKeyedConversationUnavailable =
+ isDefined(keyedConversation.thread.deletedAt) ||
+ isDefined(keyedConversation.thread.pendingQuestionMessageId);
+ const { thread, isCreated } = isKeyedConversationUnavailable
+ ? await openThreadUnderKey(`${threadKey}:${workflowRunId}:${stepId}`)
+ : keyedConversation;
+
+ if (isDefined(thread.deletedAt)) {
+ throw new WorkflowStepExecutorException(
+ 'The recipient deleted this conversation',
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ );
+ }
+
+ await this.workflowRunWorkspaceService.setStepThreadId({
+ stepId,
+ threadId: thread.id,
+ workflowRunId,
+ workspaceId,
+ });
+
+ return {
+ threadId: thread.id,
+ priorMessages: isCreated
+ ? []
+ : await this.conversationReaderService.loadMessages({
+ workspaceId,
+ threadId: thread.id,
+ }),
+ };
+ }
+
async recordExecution({
workspaceId,
- workflowRunId,
- stepId,
+ threadId,
+ workflowStep,
title,
agentId,
prompt,
@@ -60,19 +150,17 @@ export class WorkflowAgentConversationWorkspaceService {
executionResult,
}: {
workspaceId: string;
- workflowRunId: string;
- stepId: string;
+ threadId: string;
+ workflowStep: ToolCallWorkflowStep;
title: string;
agentId: string | null;
prompt: string;
initiatorUserWorkspaceId: string | null;
executionResult: RecordableAgentExecution;
}): Promise<RecordedConversation> {
- const { threadId, turnId } = await this.openConversation({
+ const turnId = await this.conversationWriterService.insertTurn({
workspaceId,
- workflowRunId,
- stepId,
- title,
+ threadId,
agentId,
});
@@ -90,6 +178,42 @@ export class WorkflowAgentConversationWorkspaceService {
workspaceId,
threadId,
turnId,
+ workflowStep,
+ title,
+ agentId,
+ executionResult,
+ });
+
+ return { threadId, isAwaitingAnswer };
+ }
+
+ // The answer is already the last message, so only the agent's reply is added
+ async recordContinuation({
+ workspaceId,
+ threadId,
+ workflowStep,
+ title,
+ agentId,
+ executionResult,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ workflowStep: ToolCallWorkflowStep;
+ title: string;
+ agentId: string | null;
+ executionResult: RecordableAgentExecution;
+ }): Promise<RecordedConversation> {
+ const turnId = await this.conversationWriterService.insertTurn({
+ workspaceId,
+ threadId,
+ agentId,
+ });
+
+ const isAwaitingAnswer = await this.recordReply({
+ workspaceId,
+ threadId,
+ turnId,
+ workflowStep,
title,
agentId,
executionResult,
@@ -102,10 +226,12 @@ export class WorkflowAgentConversationWorkspaceService {
async recordWaitOutcome({
workspaceId,
threadId,
+ workflowStep,
toolOutput,
}: {
workspaceId: string;
threadId: string;
+ workflowStep: ToolCallWorkflowStep;
toolOutput: Record<string, unknown>;
}): Promise<void> {
// messages can follow the call while it waits, so the latest one may not carry it
@@ -118,12 +244,17 @@ export class WorkflowAgentConversationWorkspaceService {
const waitPart = recentMessages
.flatMap((message) => message.parts ?? [])
- .find(
- (part) =>
+ .find((part) => {
+ const partWorkflowStep = readToolCallWorkflowStep(part.toolOutput);
+
+ return (
isDefined(part.toolName) &&
WORKFLOW_AGENT_WAIT_TOOL_NAMES.includes(part.toolName) &&
- isAwaitingPausingToolOutput(part.toolOutput),
- );
+ isAwaitingPausingToolOutput(part.toolOutput) &&
+ partWorkflowStep?.workflowRunId === workflowStep.workflowRunId &&
+ partWorkflowStep.stepId === workflowStep.stepId
+ );
+ });
if (!isDefined(waitPart)) {
throw new AiException(
@@ -139,42 +270,48 @@ export class WorkflowAgentConversationWorkspaceService {
);
}
- // The answer is already the last message, so only the agent's reply is added
- async recordContinuation({
+ // a workflow without a member creator, such as one an application installs, or whose
+ // creator cannot use AI, keeps a conversation no inbox receives
+ private async openThreadWithCreator({
workspaceId,
- threadId,
- title,
- agentId,
- executionResult,
+ coreWorkflowId,
+ openThread,
}: {
workspaceId: string;
- threadId: string;
- title: string;
- agentId: string | null;
- executionResult: RecordableAgentExecution;
- }): Promise<RecordedConversation> {
- const turnId = await this.conversationWriterService.insertTurn({
- workspaceId,
- threadId,
- agentId,
- });
+ coreWorkflowId: string;
+ openThread: (
+ workspaceMemberId: string | null,
+ ) => ReturnType<AgentInboxService['openThread']>;
+ }): ReturnType<AgentInboxService['openThread']> {
+ const creatorWorkspaceMemberId =
+ await this.workflowRunRecordShareService.findCreatorWorkspaceMemberId({
+ workspaceId,
+ coreWorkflowId,
+ });
- const isAwaitingAnswer = await this.recordReply({
- workspaceId,
- threadId,
- turnId,
- title,
- agentId,
- executionResult,
- });
+ if (!isDefined(creatorWorkspaceMemberId)) {
+ return openThread(null);
+ }
- return { threadId, isAwaitingAnswer };
+ try {
+ return await openThread(creatorWorkspaceMemberId);
+ } catch (error) {
+ if (
+ error instanceof AiException &&
+ error.code === AiExceptionCode.THREAD_NOT_FOUND
+ ) {
+ return openThread(null);
+ }
+
+ throw error;
+ }
}
private async recordReply({
workspaceId,
threadId,
turnId,
+ workflowStep,
title,
agentId,
executionResult,
@@ -182,6 +319,7 @@ export class WorkflowAgentConversationWorkspaceService {
workspaceId: string;
threadId: string;
turnId: string;
+ workflowStep: ToolCallWorkflowStep;
title: string;
agentId: string | null;
executionResult: RecordableAgentExecution;
@@ -193,6 +331,7 @@ export class WorkflowAgentConversationWorkspaceService {
turnId,
agentId,
execution: executionResult,
+ workflowStep,
});
if (isAwaitingAnswer) {
@@ -206,8 +345,8 @@ export class WorkflowAgentConversationWorkspaceService {
return isAwaitingAnswer;
}
- // the waiting call is already saved and can be answered from the run, so a failure to
- // surface it in the inbox must not fail the step
+ // the waiting call is already saved and can be answered from the conversation, so a
+ // failure to bring it back to the inbox must not fail the step
private async recordWaitingActivity(args: {
workspaceId: string;
threadId: string;
@@ -221,93 +360,4 @@ export class WorkflowAgentConversationWorkspaceService {
),
);
}
-
- private async openConversation({
- workspaceId,
- workflowRunId,
- stepId,
- title,
- agentId,
- }: {
- workspaceId: string;
- workflowRunId: string;
- stepId: string;
- title: string;
- agentId: string | null;
- }): Promise<{ threadId: string; turnId: string }> {
- const threadId = await this.createRunThread({
- workspaceId,
- workflowRunId,
- title,
- });
-
- const turnId = await this.conversationWriterService.insertTurn({
- workspaceId,
- threadId,
- agentId,
- });
-
- await this.workflowRunWorkspaceService.setStepThreadId({
- stepId,
- threadId,
- workflowRunId,
- workspaceId,
- });
-
- return { threadId, turnId };
- }
-
- // a workflow without a member creator, such as one an application installs, or whose creator
- // cannot use AI, keeps an ownerless conversation
- private async createRunThread({
- workspaceId,
- workflowRunId,
- title,
- }: {
- workspaceId: string;
- workflowRunId: string;
- title: string;
- }): Promise<string> {
- const { coreWorkflowId } =
- await this.workflowRunWorkspaceService.getWorkflowRunOrFail({
- workflowRunId,
- workspaceId,
- });
- const creatorWorkspaceMemberId = isDefined(coreWorkflowId)
- ? await this.workflowRunRecordShareService.findCreatorWorkspaceMemberId({
- workspaceId,
- coreWorkflowId,
- })
- : null;
-
- const ownedThread = isDefined(creatorWorkspaceMemberId)
- ? await this.threadService
- .createThread({
- workspaceId,
- workspaceMemberId: creatorWorkspaceMemberId,
- title,
- workflowRunId,
- })
- .catch((error: unknown) => {
- if (
- error instanceof AiException &&
- error.code === AiExceptionCode.THREAD_NOT_FOUND
- ) {
- return null;
- }
- throw error;
- })
- : null;
-
- if (isDefined(ownedThread)) {
- return ownedThread.id;
- }
-
- const threadInsertResult = await this.threadRepository.insert(workspaceId, {
- title,
- workflowRunId,
- });
-
- return threadInsertResult.identifiers[0].id as string;
- }
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts
index d6f53d1a816..e82d20bee93 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts
@@ -1,5 +1,9 @@
+import { type WorkflowConversation } from 'twenty-shared/workflow';
+
export type WorkflowAiAgentActionInput = {
agentId?: string;
prompt?: string;
humanInputInstructions?: string;
+ workspaceMemberId?: string;
+ conversation?: WorkflowConversation;
};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts
index 8a420c7f309..f15a32b021e 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts
@@ -4,6 +4,7 @@ import { WorkflowRunRecordShareModule } from 'src/engine/core-modules/workflow/w
import { AgentChatThreadModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module';
import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+import { WorkflowRunInboxSenderModule } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.module';
import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
@@ -11,6 +12,7 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow
imports: [
AgentChatThreadModule,
AgentHistoryModule,
+ WorkflowRunInboxSenderModule,
WorkflowRunModule,
WorkflowRunRecordShareModule,
WorkspaceCacheModule,
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.ts
index 178666380dc..aaa71f2f1e5 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
@@ -6,6 +6,7 @@ import { type AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/s
import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { WorkflowStepExecutorExceptionCode } from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
import { type WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
+import { WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';
import { createMockIteratorStep } from 'src/modules/workflow/workflow-executor/utils/create-mock-workflow-steps.util';
import { SendChatMessageWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
@@ -60,11 +61,15 @@ describe('SendChatMessageWorkflowAction', () => {
action = new SendChatMessageWorkflowAction(
{ sendMessage } as unknown as AgentInboxService,
- {
- executeInWorkspaceContext: jest.fn((callback) => callback()),
- getRepository: jest.fn().mockReturnValue({ findOne: findWorkflowRun }),
- } as unknown as WorkspaceOrmManager,
- { findCoreWorkflowById } as unknown as WorkflowCoreSyncService,
+ new WorkflowRunInboxSenderWorkspaceService(
+ {
+ executeInWorkspaceContext: jest.fn((callback) => callback()),
+ getRepository: jest
+ .fn()
+ .mockReturnValue({ findOne: findWorkflowRun }),
+ } as unknown as WorkspaceOrmManager,
+ { findCoreWorkflowById } as unknown as WorkflowCoreSyncService,
+ ),
{} as WorkflowExecutionContextService,
{} as WorkflowRunWorkspaceService,
{} as ToolRegistryService,
@@ -131,6 +136,48 @@ describe('SendChatMessageWorkflowAction', () => {
]);
});
+ it('starts a new conversation each time the step runs when asked to', async () => {
+ await execute({
+ workspaceMemberId: WORKSPACE_MEMBER_ID,
+ title: 'Hello',
+ text: 'Hello',
+ conversation: { scope: 'STEP' },
+ });
+
+ expect(sendMessage.mock.calls[0][0].input).toMatchObject({
+ threadKey: `${WORKFLOW_RUN_ID}:step-1`,
+ idempotencyKey: 'step-1',
+ });
+ });
+
+ it('shares a conversation by its resolved key, keeping each run its own messages', async () => {
+ await execute({
+ workspaceMemberId: WORKSPACE_MEMBER_ID,
+ title: 'Hello',
+ text: 'Hello',
+ conversation: { scope: 'KEY', key: 'deal-{{trigger.name}}' },
+ });
+
+ expect(sendMessage.mock.calls[0][0].input).toMatchObject({
+ threadKey: 'key:deal-Acme',
+ idempotencyKey: `${WORKFLOW_RUN_ID}:step-1`,
+ });
+ });
+
+ it('refuses a shared conversation without a key', async () => {
+ await expect(
+ execute({
+ workspaceMemberId: WORKSPACE_MEMBER_ID,
+ title: 'Hello',
+ text: 'Hello',
+ conversation: { scope: 'KEY', key: '' },
+ }),
+ ).rejects.toMatchObject({
+ code: WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ });
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
it('titles the conversation with the step name when no title is set', async () => {
await execute({
workspaceMemberId: WORKSPACE_MEMBER_ID,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts
index fc178e7d65a..6722955ebed 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts
@@ -1,17 +1,17 @@
import { Module } from '@nestjs/common';
import { ToolProviderModule } from 'src/engine/core-modules/tool-provider/tool-provider.module';
-import { WorkflowCoreModule } from 'src/engine/core-modules/workflow/workflow-core.module';
import { AgentChatThreadModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module';
import { WorkflowExecutionContextModule } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.module';
+import { WorkflowRunInboxSenderModule } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.module';
import { SendChatMessageWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action';
import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
@Module({
imports: [
AgentChatThreadModule,
- WorkflowCoreModule,
WorkflowExecutionContextModule,
+ WorkflowRunInboxSenderModule,
WorkflowRunModule,
ToolProviderModule,
],
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.ts
index db662206d55..6f4a2421fa8 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
@@ -11,27 +11,24 @@ import {
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
-import { type WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/tool-context.type';
-import { 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';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { getRoleIdsFromRolePermissionConfig } from 'src/engine/twenty-orm/utils/get-role-ids-from-role-permission-config.util';
-import { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';
+import { WorkflowRunInboxSenderWorkspaceService } from 'src/modules/workflow/workflow-executor/services/workflow-run-inbox-sender.workspace-service';
import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';
import { 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 { resolveConversationThreadKey } from 'src/modules/workflow/workflow-executor/utils/resolve-conversation-thread-key.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';
@@ -44,8 +41,7 @@ const MAX_SEND_ATTEMPTS = 10;
export class SendChatMessageWorkflowAction implements WorkflowAction {
constructor(
private readonly agentInboxService: AgentInboxService,
- private readonly workspaceOrmManager: WorkspaceOrmManager,
- private readonly workflowCoreSyncService: WorkflowCoreSyncService,
+ private readonly workflowRunInboxSenderService: WorkflowRunInboxSenderWorkspaceService,
private readonly workflowExecutionContextService: WorkflowExecutionContextService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
private readonly toolRegistryService: ToolRegistryService,
@@ -66,10 +62,11 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {
);
}
- const { workspaceMemberId, title, text, toolCall } = resolveInput(
- step.settings.input,
- context,
- ) as WorkflowSendChatMessageActionInput;
+ const { workspaceMemberId, title, text, toolCall, conversation } =
+ resolveInput(
+ step.settings.input,
+ context,
+ ) as WorkflowSendChatMessageActionInput;
if (!isValidUuid(workspaceMemberId)) {
throw new WorkflowStepExecutorException(
@@ -85,7 +82,24 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {
);
}
- const workflow = await this.findRunWorkflowOrThrow(runInfo);
+ const sender =
+ await this.workflowRunInboxSenderService.findRunSenderOrThrow(runInfo);
+ const executionKey = buildStepExecutionKey({
+ stepId: currentStepId,
+ steps,
+ context,
+ });
+ const threadKey = resolveConversationThreadKey({
+ conversation,
+ defaultScope: 'RUN',
+ workflowRunId: runInfo.workflowRunId,
+ stepExecutionKey: executionKey,
+ });
+ // a conversation shared by key holds every run's messages, so each run keys its own
+ const messageKey =
+ conversation?.scope === 'KEY'
+ ? `${runInfo.workflowRunId}:${executionKey}`
+ : executionKey;
let awaitingToolCall:
| ReturnType<SendChatMessageWorkflowAction['resolveAwaitingToolCall']>
| undefined;
@@ -103,37 +117,23 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {
: undefined;
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',
- },
+ sender,
input: {
workspaceMemberId,
- threadKey: runInfo.workflowRunId,
+ threadKey,
idempotencyKey,
title: isNonEmptyString(title) ? title : step.name,
text,
},
buildAwaitingToolCall,
});
- const executionKey = buildStepExecutionKey({
- stepId: currentStepId,
- steps,
- context,
- });
-
// 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}`,
+ attempt === 0 ? messageKey : `${messageKey}:${attempt}`,
);
if (!isDefined(buildAwaitingToolCall)) {
@@ -250,43 +250,4 @@ export class SendChatMessageWorkflowAction implements WorkflowAction {
},
};
}
-
- // Every run carries the core workflow it was started from, which is the
- // identity the executor bills and the conversation is attributed to.
- private async findRunWorkflowOrThrow({
- workflowRunId,
- workspaceId,
- }: WorkflowActionInput['runInfo']): Promise<
- Pick<WorkflowEntity, 'id' | 'name'>
- > {
- const workflowRun =
- await this.workspaceOrmManager.executeInWorkspaceContext(
- () =>
- this.workspaceOrmManager
- .getRepository<WorkflowRunWorkspaceEntity>('workflowRun', {
- shouldBypassPermissionChecks: true,
- })
- .findOne({
- where: { id: workflowRunId },
- select: ['id', 'coreWorkflowId'],
- }),
- buildSystemAuthContext(workspaceId),
- );
-
- const workflow = isDefined(workflowRun?.coreWorkflowId)
- ? await this.workflowCoreSyncService.findCoreWorkflowById(
- workspaceId,
- workflowRun.coreWorkflowId,
- )
- : null;
-
- if (!isDefined(workflow)) {
- throw new WorkflowStepExecutorException(
- 'Workflow run has no workflow',
- WorkflowStepExecutorExceptionCode.INTERNAL_ERROR,
- );
- }
-
- return workflow;
- }
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type.ts
index 09cf1dcec69..6f755d09e89 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type.ts
@@ -1,3 +1,5 @@
+import { type WorkflowConversation } from 'twenty-shared/workflow';
+
export type WorkflowSendChatMessageActionInput = {
workspaceMemberId: string;
title: string;
@@ -6,4 +8,5 @@ export type WorkflowSendChatMessageActionInput = {
toolName: string;
arguments: Record<string, object | string | number | boolean | null>;
};
+ conversation?: WorkflowConversation;
};
diff --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.ts
index 7be0db5d193..9509d322788 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
@@ -32,9 +32,16 @@ describe('WorkflowRunWorkspaceService conversations', () => {
find: jest.fn().mockResolvedValue([
{
id: 'part-id',
+ messageId: 'message-id',
toolName: 'ask_question',
toolInput: QUESTIONS[0],
- toolOutput: { result: { question: QUESTIONS[0], status: 'pending' } },
+ toolOutput: {
+ result: { question: QUESTIONS[0], status: 'pending' },
+ workflowStep: {
+ workflowRunId: 'workflow-run-id',
+ stepId: 'step-id',
+ },
+ },
},
]),
writePart: jest.fn(),
@@ -306,6 +313,29 @@ describe('WorkflowRunWorkspaceService conversations', () => {
});
});
+ it('leaves open a call another run posted in a conversation they share', async () => {
+ const { service, threadRepository, messagePartRepository } =
+ buildService();
+
+ messagePartRepository.find.mockResolvedValue([
+ {
+ id: 'part-id',
+ messageId: 'message-id',
+ toolName: 'ask_question',
+ toolInput: QUESTIONS[0],
+ toolOutput: {
+ result: { question: QUESTIONS[0], status: 'pending' },
+ workflowStep: { workflowRunId: 'other-run-id', stepId: 'step-id' },
+ },
+ },
+ ]);
+
+ await endRun(service);
+
+ expect(threadRepository.update).not.toHaveBeenCalled();
+ expect(messagePartRepository.writePart).not.toHaveBeenCalled();
+ });
+
it('leaves a conversation to the answer holding its claim', async () => {
const { service, threadRepository, messagePartRepository } =
buildService();
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
index cf4f71311b0..f5ab82802d5 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
@@ -754,36 +754,21 @@ export class WorkflowRunWorkspaceService {
workspaceId: string;
stepThreadIds: string[];
}): Promise<void> {
- // An answer holding a conversation's claim closes its calls itself once it finds the run over.
- // A step can also wait in a member's inbox, whose conversation is theirs, not the run's
- const [runThreads, inboxThreads] = await Promise.all([
- this.threadRepository.find(workspaceId, {
- where: {
- workflowRunId,
- pendingQuestionMessageId: Not(IsNull()),
- activeStreamId: IsNull(),
- },
- select: ['id', 'pendingQuestionMessageId'],
- }),
- this.threadRepository.find(workspaceId, {
- where: {
- id: In(stepThreadIds),
- workflowRunId: IsNull(),
- pendingQuestionMessageId: Not(IsNull()),
- activeStreamId: IsNull(),
- },
- select: ['id', 'pendingQuestionMessageId'],
- }),
- ]);
-
- const waitingThreads = [
- ...runThreads,
- ...(await this.filterThreadsWaitingOnRun({
- threads: inboxThreads,
- workflowRunId,
- workspaceId,
- })),
- ];
+ // An answer holding a conversation's claim closes its calls itself once it finds the run over
+ const stepThreads = await this.threadRepository.find(workspaceId, {
+ where: {
+ id: In(stepThreadIds),
+ pendingQuestionMessageId: Not(IsNull()),
+ activeStreamId: IsNull(),
+ },
+ select: ['id', 'pendingQuestionMessageId'],
+ });
+
+ const waitingThreads = await this.filterThreadsWaitingOnRun({
+ threads: stepThreads,
+ workflowRunId,
+ workspaceId,
+ });
for (const { id, pendingQuestionMessageId } of waitingThreads) {
if (!isDefined(pendingQuestionMessageId)) {
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
index 183a925151e..927db087d0a 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
@@ -786,15 +786,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
}) => submitFormStep({ workflowRunId: runId, stepId, response: { answer } });
describe('submitting a form step', () => {
- const countRunConversations = async (runId: string) => {
- const [{ count }] = await global.testDataSource.query(
- `SELECT COUNT(*)::int AS count FROM "${schema}"."agentChatThread" WHERE "workflowRunId" = $1`,
- [runId],
- );
-
- return count;
- };
-
it('waits without a conversation and completes with the submitted values', async () => {
const finalStep = emptyStep();
const form = formStep([finalStep.id]);
@@ -809,7 +800,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
expect((await getRun(runId)).state.stepInfos[form.id].threadId).toBe(
undefined,
);
- expect(await countRunConversations(runId)).toBe(0);
const response = await submitForm({
runId,
@@ -824,7 +814,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
expect(run.state.stepInfos[form.id].result).toEqual({
answer: 'Approved',
});
- expect(await countRunConversations(runId)).toBe(0);
});
it('refuses values for fields the form does not have', async () => {
@@ -1019,6 +1008,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
input: {
prompt: 'Draft the quote',
humanInputInstructions: 'Ask before choosing a plan.',
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
},
},
}) as WorkflowAction;
@@ -1144,7 +1134,22 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
response: { selectedOptionIndices: [0] },
});
- it('records no conversation for an agent that answers without asking', async () => {
+ const getInboxState = async (threadId: string) => {
+ const [state] = await global.testDataSource.query(
+ `SELECT thread."workspaceMemberId", thread."lastMessageText",
+ participant."archivedAt" IS NOT NULL AS "isArchived",
+ thread."lastActivityAt" > participant."archivedAt" AS "isBackInInbox"
+ FROM "${schema}"."agentChatThread" thread
+ LEFT JOIN "${schema}"."agentChatThreadParticipant" participant
+ ON participant."threadId" = thread.id AND participant."workspaceMemberId" = thread."workspaceMemberId"
+ WHERE thread.id = $1`,
+ [threadId],
+ );
+
+ return state;
+ };
+
+ it('records the conversation of an agent that answers without asking, filed under done', async () => {
jest
.spyOn(
getAppProviderByClassName<AgentAsyncExecutorService>(
@@ -1159,22 +1164,61 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
const runId = await runFixture(fixture);
const run = await waitForRun(runId, 'COMPLETED');
+ const threadId: string = run.state.stepInfos[agent.id].threadId;
expect(run.state.stepInfos[agent.id]).toMatchObject({
status: 'SUCCESS',
result: { response: 'Quote sent' },
});
- expect(run.state.stepInfos[agent.id].threadId).toBeUndefined();
+ expect(await getInboxState(threadId)).toMatchObject({
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ isArchived: true,
+ isBackInInbox: false,
+ });
+ expect(
+ (await getConversation(threadId)).messages.map(
+ ({ role }: { role: string }) => role,
+ ),
+ ).toEqual(['user', 'assistant']);
+ });
- const threads = await global.testDataSource.query(
- `SELECT id FROM "${schema}"."agentChatThread" WHERE "workflowRunId" = $1`,
- [runId],
+ it('continues the conversation its key names across runs', async () => {
+ const executeAgent = jest
+ .spyOn(
+ getAppProviderByClassName<AgentAsyncExecutorService>(
+ 'AgentAsyncExecutorService',
+ ),
+ 'executeAgent',
+ )
+ .mockResolvedValueOnce(replyingResult)
+ .mockResolvedValueOnce(replyingResult);
+ const agent = {
+ ...agentStep([]),
+ settings: {
+ ...agentStep([]).settings,
+ input: {
+ ...agentStep([]).settings.input,
+ conversation: { scope: 'KEY', key: 'quotes' },
+ },
+ },
+ } as WorkflowAction;
+ const fixture = await createFixture({ steps: [agent] });
+
+ const firstRun = await waitForRun(await runFixture(fixture), 'COMPLETED');
+ const secondRun = await waitForRun(
+ await runFixture(fixture),
+ 'COMPLETED',
);
+ const threadId: string = firstRun.state.stepInfos[agent.id].threadId;
- expect(threads).toEqual([]);
+ expect(secondRun.state.stepInfos[agent.id].threadId).toBe(threadId);
+ expect(executeAgent.mock.calls[0][0].priorMessages).toEqual([]);
+ expect(
+ JSON.stringify(executeAgent.mock.calls[1][0].priorMessages),
+ ).toContain('Quote sent');
});
- it("routes the waiting conversation to the workflow creator's inbox", async () => {
+ it("routes the waiting conversation to the workflow creator's inbox when the step names no recipient", async () => {
mockAgent();
const [creator] = await global.testDataSource.query(
`SELECT membership.id AS "userWorkspaceId", member.id AS "workspaceMemberId"
@@ -1183,7 +1227,16 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
WHERE membership."workspaceId" = $1 AND membership."deletedAt" IS NULL AND member.id = $2`,
[workspaceId, WORKSPACE_MEMBER_DATA_SEED_IDS.JONY],
);
- const agent = agentStep([]);
+ const agent = {
+ ...agentStep([]),
+ settings: {
+ ...agentStep([]).settings,
+ input: {
+ ...agentStep([]).settings.input,
+ workspaceMemberId: undefined,
+ },
+ },
+ } as WorkflowAction;
const fixture = await createFixture({ steps: [agent] });
await global.testDataSource.query(
@@ -1193,35 +1246,38 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
const runId = await runFixture(fixture);
const run = await waitForStep(runId, agent.id, 'PENDING');
- const [conversation] = await global.testDataSource.query(
- `SELECT "workspaceMemberId", "workflowRunId", "lastActivityAt", "lastMessageText" FROM "${schema}"."agentChatThread" WHERE id = $1`,
- [run.state.stepInfos[agent.id].threadId],
- );
+ const threadId: string = run.state.stepInfos[agent.id].threadId;
- expect(conversation).toMatchObject({
+ expect(await getInboxState(threadId)).toMatchObject({
workspaceMemberId: creator.workspaceMemberId,
- workflowRunId: runId,
lastMessageText: agent.name,
+ isArchived: true,
+ isBackInInbox: true,
});
- expect(conversation.lastActivityAt).not.toBeNull();
const readByAnotherMember = await request(`http://localhost:${APP_PORT}`)
.post('/metadata')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.send({
query: `query ReadRunConversation($threadId: UUID!) { chatMessages(threadId: $threadId) { role } }`,
- variables: { threadId: run.state.stepInfos[agent.id].threadId },
+ variables: { threadId },
});
- expect(readByAnotherMember.body.errors).toBeUndefined();
- expect(readByAnotherMember.body.data.chatMessages.length).toBeGreaterThan(
- 0,
- );
+ expect(readByAnotherMember.body.errors).toBeDefined();
});
it('keeps the conversation of a workflow without a member creator off every inbox', async () => {
mockAgent();
- const agent = agentStep([]);
+ const agent = {
+ ...agentStep([]),
+ settings: {
+ ...agentStep([]).settings,
+ input: {
+ ...agentStep([]).settings.input,
+ workspaceMemberId: undefined,
+ },
+ },
+ } as WorkflowAction;
const fixture = await createFixture({ steps: [agent] });
await global.testDataSource.query(
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
index 7486f41ff7b..8d9a7573e20 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
@@ -771,7 +771,7 @@ describe('core workflow visibility (e2e)', () => {
});
});
- // An agent step's conversation has no grants of its own: it is read through its run, so follows the workflow's visibility.
+ // An agent step's conversation belongs to its recipient, or else the workflow's creator, whatever the workflow's visibility.
describe('the conversation an agent step records on a run', () => {
let conversationCoreWorkflowId: string;
let conversationWorkspaceWorkflowId: string;
@@ -816,11 +816,19 @@ describe('core workflow visibility (e2e)', () => {
'WorkflowAgentConversationWorkspaceService',
);
- const recordedConversation = await conversationService.recordExecution({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workflowRunId,
+ ({ threadId } = await conversationService.openConversation({
+ runInfo: { workspaceId: SEED_APPLE_WORKSPACE_ID, workflowRunId },
stepId: 'trigger',
title: 'Summarize the lead',
+ recipientWorkspaceMemberId: null,
+ threadKey: `${workflowRunId}:trigger`,
+ }));
+
+ await conversationService.recordExecution({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ threadId,
+ workflowStep: { workflowRunId, stepId: 'trigger' },
+ title: 'Summarize the lead',
agentId: null,
prompt: 'Summarize the lead',
initiatorUserWorkspaceId: null,
@@ -830,9 +838,6 @@ describe('core workflow visibility (e2e)', () => {
] as AgentExecutionResult['steps'],
},
});
-
- expect(recordedConversation).not.toBeNull();
- threadId = recordedConversation!.threadId;
});
afterAll(async () => {
@@ -875,82 +880,24 @@ describe('core workflow visibility (e2e)', () => {
).toEqual(['user', 'assistant']);
});
- it('keeps it out of the chat list of someone who can read it', async () => {
- expect(
- await listChatThreadIds(APPLE_JANE_ADMIN_ACCESS_TOKEN),
- ).not.toContain(threadId);
- });
-
- it('refuses to rename or delete it, even for the workflow creator', async () => {
- const renameResponse = await graphqlRequestAs(
- APPLE_JANE_ADMIN_ACCESS_TOKEN,
- `
- mutation RenameRunConversation($threadId: UUID!) {
- updateAgentChatThread(id: $threadId, data: { title: "Renamed" }) {
- id
- }
- }
- `,
- { threadId },
- );
-
- expect(renameResponse.body.errors?.[0]?.extensions?.code).toBe(
- 'FORBIDDEN',
- );
-
- const deleteResponse = await graphqlRequestAs(
- APPLE_JANE_ADMIN_ACCESS_TOKEN,
- `
- mutation DeleteRunConversation($threadId: UUID!) {
- deleteAgentChatThread(id: $threadId) {
- id
- }
- }
- `,
- { threadId },
- );
-
- expect(deleteResponse.body.errors?.[0]?.extensions?.code).toBe(
- 'FORBIDDEN',
+ it("files it under done in the workflow creator's chats", async () => {
+ expect(await listChatThreadIds(APPLE_JANE_ADMIN_ACCESS_TOKEN)).toContain(
+ threadId,
);
- const [storedThread] = await global.testDataSource.query(
- `SELECT title, "deletedAt" FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."agentChatThread" WHERE id = $1`,
+ const [{ archivedAt }] = await global.testDataSource.query(
+ `SELECT "archivedAt" FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."agentChatThreadParticipant" WHERE "threadId" = $1`,
[threadId],
);
- expect(storedThread).toEqual({
- title: 'Summarize the lead',
- deletedAt: null,
- });
+ expect(archivedAt).not.toBeNull();
});
- it('follows the workflow visibility for another member', async () => {
- const whileVisible = await readConversation(
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(whileVisible.body.errors).toBeUndefined();
- expect(whileVisible.body.data.chatThread.id).toBe(threadId);
+ it('keeps it private to its owner even when the workflow is visible', async () => {
+ const response = await readConversation(APPLE_JONY_MEMBER_ACCESS_TOKEN);
- const response = await setVisibility(
- conversationCoreWorkflowId,
- WorkflowVisibility.PRIVATE,
- );
-
- expect(response.body.errors).toBeUndefined();
-
- const whilePrivate = await readConversation(
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(whilePrivate.body.data?.chatThread ?? null).toBeNull();
- expect(whilePrivate.body.errors).toBeDefined();
-
- const asCreator = await readConversation(APPLE_JANE_ADMIN_ACCESS_TOKEN);
-
- expect(asCreator.body.errors).toBeUndefined();
- expect(asCreator.body.data.chatThread.id).toBe(threadId);
+ expect(response.body.data?.chatThread ?? null).toBeNull();
+ expect(response.body.errors).toBeDefined();
});
it('keeps the conversation of an attempt that is retried in the step history', async () => {
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts
index 7df406633a2..5a6e2930cb5 100644
--- a/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts
@@ -143,9 +143,9 @@ describe('versioned agent history upgrade (integration)', () => {
await runner.release();
}
- // Run-owned threads arrived with 2.44 and have no member owner in the core tables 2.42 restores.
+ // Threads no member owns arrived with 2.44 and have no owner in the core tables 2.42 restores.
await dataSource.query(
- `DELETE FROM "${SCHEMA}"."agentChatThread" WHERE "workflowRunId" IS NOT NULL`,
+ `DELETE FROM "${SCHEMA}"."agentChatThread" WHERE "workspaceMemberId" IS NULL`,
);
await runCommand('down');
await dataSource.query(
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts
index bcacd619dcf..d947f886992 100644
--- a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts
@@ -3,17 +3,16 @@ import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
import { MetadataReadability } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-import { LEGACY_CHAT_THREAD_OWNER_FIELD_UNIVERSAL_IDENTIFIER } from 'src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-owner-field-universal-identifier.constant';
+import {
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER,
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_INDEX_UNIVERSAL_IDENTIFIER,
+ LEGACY_WORKFLOW_RUN_AGENT_CHAT_THREADS_FIELD_UNIVERSAL_IDENTIFIER,
+} from 'src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-workflow-run-universal-identifiers.constant';
import { type AddWorkflowRunToChatThreadsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command';
-import { type ApplicationService } from 'src/engine/core-modules/application/application.service';
-import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
-import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
-import { type WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
const RUN_ON_WORKSPACE_ARGS = {
workspaceId: SEED_APPLE_WORKSPACE_ID,
@@ -23,13 +22,13 @@ const RUN_ON_WORKSPACE_ARGS = {
};
const FIELD_UNIVERSAL_IDENTIFIERS = [
- STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier,
- STANDARD_OBJECTS.workflowRun.fields.agentChatThreads.universalIdentifier,
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_FIELD_UNIVERSAL_IDENTIFIER,
+ LEGACY_WORKFLOW_RUN_AGENT_CHAT_THREADS_FIELD_UNIVERSAL_IDENTIFIER,
];
-const INDEX_UNIVERSAL_IDENTIFIER =
- STANDARD_OBJECTS.agentChatThread.indexes.workflowRunIndex.universalIdentifier;
-
+// 2.46 dropped the run link from the standard objects, so a workspace
+// upgrading past 2.44 keeps its threads PRIVATE and unlinked, as a fresh
+// install leaves them.
describe('2-44 workspace command 1790607161319 - AddWorkflowRunToChatThreadsCommand (integration)', () => {
let command: AddWorkflowRunToChatThreadsCommand;
let workspaceOrmManager: WorkspaceOrmManager;
@@ -60,94 +59,24 @@ describe('2-44 workspace command 1790607161319 - AddWorkflowRunToChatThreadsComm
),
).length,
hasIndex: isDefined(
- flatIndexMaps.byUniversalIdentifier[INDEX_UNIVERSAL_IDENTIFIER],
+ flatIndexMaps.byUniversalIdentifier[
+ LEGACY_CHAT_THREAD_WORKFLOW_RUN_INDEX_UNIVERSAL_IDENTIFIER
+ ],
),
- isOwnerRequired:
- flatFieldMetadataMaps.byUniversalIdentifier[
- LEGACY_CHAT_THREAD_OWNER_FIELD_UNIVERSAL_IDENTIFIER
- ]?.isNullable === false,
readability: threadObject?.readability,
readabilityParentFieldUniversalIdentifiers:
threadObject?.readabilityParentFieldUniversalIdentifiers,
};
};
- // Pre-upgrade state: no run link and threads PRIVATE, as 2.43 left them.
- const setPreUpgradeState = async () => {
- const migrationService =
- getAppProviderByClassName<WorkspaceMigrationValidateBuildAndRunService>(
- 'WorkspaceMigrationValidateBuildAndRunService',
- );
- const applicationService =
- getAppProviderByClassName<ApplicationService>('ApplicationService');
- const { twentyStandardFlatApplication } =
- await applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
- { workspaceId: SEED_APPLE_WORKSPACE_ID },
- );
- const { flatObjectMetadataMaps, flatFieldMetadataMaps, flatIndexMaps } =
- await workspaceCacheService.getOrRecompute(SEED_APPLE_WORKSPACE_ID, [
- 'flatObjectMetadataMaps',
- 'flatFieldMetadataMaps',
- 'flatIndexMaps',
- ]);
- const threadObject =
- flatObjectMetadataMaps.byUniversalIdentifier[
- STANDARD_OBJECTS.agentChatThread.universalIdentifier
- ]!;
- const run = async (
- allFlatEntityOperationByMetadataName: Parameters<
- WorkspaceMigrationValidateBuildAndRunService['validateBuildAndRunLegacyWorkspaceMigration']
- >[0]['allFlatEntityOperationByMetadataName'],
- ) => {
- const result =
- await migrationService.validateBuildAndRunLegacyWorkspaceMigration({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- isSystemBuild: true,
- applicationUniversalIdentifier:
- twentyStandardFlatApplication.universalIdentifier,
- allFlatEntityOperationByMetadataName,
- });
-
- expect(result.status).toBe('success');
- };
-
- await run({
- objectMetadata: {
- flatEntityToCreate: [],
- flatEntityToDelete: [],
- flatEntityToUpdate: [
- {
- ...threadObject,
- readability: MetadataReadability.PRIVATE,
- readabilityParentFieldUniversalIdentifiers: null,
- },
- ],
- },
- });
- // Run conversations only exist from 2.44 on; no earlier version can hold them ownerless and unlinked.
- await global.testDataSource.query(
- `DELETE FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."agentChatThread" WHERE "workflowRunId" IS NOT NULL`,
- );
- await run({
- fieldMetadata: {
- flatEntityToCreate: [],
- flatEntityToDelete: FIELD_UNIVERSAL_IDENTIFIERS.map(
- (universalIdentifier) =>
- flatFieldMetadataMaps.byUniversalIdentifier[universalIdentifier],
- ).filter(isDefined) as FlatFieldMetadata[],
- flatEntityToUpdate: [],
- },
- index: {
- flatEntityToCreate: [],
- flatEntityToDelete: [
- flatIndexMaps.byUniversalIdentifier[INDEX_UNIVERSAL_IDENTIFIER],
- ].filter(isDefined) as FlatIndexMetadata[],
- flatEntityToUpdate: [],
- },
- });
+ const UNLINKED_STATE = {
+ fieldCount: 0,
+ hasIndex: false,
+ readability: MetadataReadability.PRIVATE,
+ readabilityParentFieldUniversalIdentifiers: null,
};
- beforeAll(async () => {
+ beforeAll(() => {
command = getAppProviderByClassName<AddWorkflowRunToChatThreadsCommand>(
'AddWorkflowRunToChatThreadsCommand',
);
@@ -157,124 +86,24 @@ describe('2-44 workspace command 1790607161319 - AddWorkflowRunToChatThreadsComm
workspaceCacheService = getAppProviderByClassName<WorkspaceCacheService>(
'WorkspaceCacheService',
);
-
- await setPreUpgradeState();
- });
-
- afterAll(async () => {
- await runCommand();
});
it('starts from a workspace without the run link', async () => {
- expect(await readState()).toMatchObject({
- fieldCount: 0,
- hasIndex: false,
- readability: MetadataReadability.PRIVATE,
- });
+ expect(await readState()).toEqual(UNLINKED_STATE);
});
- it('changes nothing on a dry run', async () => {
- await runCommand({ dryRun: true });
-
- expect(await readState()).toMatchObject({
- fieldCount: 0,
- hasIndex: false,
- readability: MetadataReadability.PRIVATE,
- });
- });
-
- it('links threads to runs and makes them inherit their run readability, as a fresh install does', async () => {
- await runCommand();
-
- expect(await readState()).toEqual({
- fieldCount: FIELD_UNIVERSAL_IDENTIFIERS.length,
- hasIndex: true,
- isOwnerRequired: false,
- readability: MetadataReadability.INHERITED,
- readabilityParentFieldUniversalIdentifiers: [
- STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier,
- ],
- });
- });
-
- it('is a no-op when run again', async () => {
- const before = await readState();
-
+ it('no longer links threads to runs', async () => {
await runCommand();
- expect(await readState()).toEqual(before);
- });
-
- it('leaves threads still under SYSTEM protection as they are', async () => {
- const { flatObjectMetadataMaps } =
- await workspaceCacheService.getOrRecompute(SEED_APPLE_WORKSPACE_ID, [
- 'flatObjectMetadataMaps',
- ]);
- const threadObject =
- flatObjectMetadataMaps.byUniversalIdentifier[
- STANDARD_OBJECTS.agentChatThread.universalIdentifier
- ]!;
- const migrationService =
- getAppProviderByClassName<WorkspaceMigrationValidateBuildAndRunService>(
- 'WorkspaceMigrationValidateBuildAndRunService',
- );
- const applicationService =
- getAppProviderByClassName<ApplicationService>('ApplicationService');
- const { twentyStandardFlatApplication } =
- await applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
- { workspaceId: SEED_APPLE_WORKSPACE_ID },
- );
- const setThreadProtection = async (
- protection: Pick<
- typeof threadObject,
- 'readability' | 'readabilityParentFieldUniversalIdentifiers'
- >,
- ) => {
- const result =
- await migrationService.validateBuildAndRunLegacyWorkspaceMigration({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- isSystemBuild: true,
- applicationUniversalIdentifier:
- twentyStandardFlatApplication.universalIdentifier,
- allFlatEntityOperationByMetadataName: {
- objectMetadata: {
- flatEntityToCreate: [],
- flatEntityToDelete: [],
- flatEntityToUpdate: [{ ...threadObject, ...protection }],
- },
- },
- });
-
- expect(result.status).toBe('success');
- };
-
- await setThreadProtection({
- readability: MetadataReadability.SYSTEM,
- readabilityParentFieldUniversalIdentifiers: null,
- });
- await runCommand();
-
- expect(await readState()).toMatchObject({
- readability: MetadataReadability.SYSTEM,
- });
-
- await setThreadProtection({
- readability: threadObject.readability,
- readabilityParentFieldUniversalIdentifiers:
- threadObject.readabilityParentFieldUniversalIdentifiers,
- });
+ expect(await readState()).toEqual(UNLINKED_STATE);
});
- it('makes threads PRIVATE again on down', async () => {
+ it('keeps threads PRIVATE on down', async () => {
await workspaceOrmManager.executeInWorkspaceContext(
() => command.down(RUN_ON_WORKSPACE_ARGS),
buildSystemAuthContext(SEED_APPLE_WORKSPACE_ID),
);
- expect(await readState()).toMatchObject({
- fieldCount: FIELD_UNIVERSAL_IDENTIFIERS.length,
- readability: MetadataReadability.PRIVATE,
- readabilityParentFieldUniversalIdentifiers: null,
- });
+ expect(await readState()).toEqual(UNLINKED_STATE);
});
});
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.ts
index fcd1d0e5630..d16594187d5 100644
--- a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.ts
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.ts
@@ -22,13 +22,14 @@ const RUN_ON_WORKSPACE_ARGS = {
total: 1,
};
+// 2.46 dropped the run link this command recorded conversations on, so a
+// workspace upgrading past 2.44 keeps answering its forms from their runs.
describe('2-44 workspace command 1790772993322 - RecordPendingFormConversationsCommand (integration)', () => {
let command: RecordPendingFormConversationsCommand;
let workspaceOrmManager: WorkspaceOrmManager;
- let workflowRun: Pick<WorkflowRunWorkspaceEntity, 'id' | 'state'>;
+ let workflowRunId: string;
let formStepId: string;
let originalState: WorkflowRunWorkspaceEntity['state'];
- let seededThreadId: string;
const inWorkspace = <TResult>(work: () => Promise<TResult>) =>
workspaceOrmManager.executeInWorkspaceContext(
@@ -36,39 +37,10 @@ describe('2-44 workspace command 1790772993322 - RecordPendingFormConversationsC
buildSystemAuthContext(SEED_APPLE_WORKSPACE_ID),
);
- const repository = (objectName: string) =>
- workspaceOrmManager.getRepository(objectName, {
- shouldBypassPermissionChecks: true,
- });
-
- const runCommand = (options: { dryRun?: boolean } = {}) =>
- inWorkspace(() =>
- command.runOnWorkspace({ ...RUN_ON_WORKSPACE_ARGS, options }),
- );
-
- const findFormThreadId = async () => {
- const { state } = await inWorkspace(() =>
- repository('workflowRun').findOneOrFail({
- where: { id: workflowRun.id },
- select: { state: true },
- }),
- );
-
- return state?.stepInfos?.[formStepId]?.threadId;
- };
-
- // A form step pending since before this release, with no recorded conversation.
- const forgetFormConversation = () =>
- inWorkspace(() =>
- repository('workflowRun').update(workflowRun.id, {
- state: {
- ...workflowRun.state,
- stepInfos: {
- ...workflowRun.state?.stepInfos,
- [formStepId]: { status: StepStatus.PENDING },
- },
- },
- }),
+ const workflowRunRepository = () =>
+ workspaceOrmManager.getRepository<WorkflowRunWorkspaceEntity>(
+ 'workflowRun',
+ { shouldBypassPermissionChecks: true },
);
beforeAll(async () => {
@@ -79,102 +51,72 @@ describe('2-44 workspace command 1790772993322 - RecordPendingFormConversationsC
'WorkspaceOrmManager',
);
- const [runningWorkflowRun] = (await inWorkspace(() =>
- repository('workflowRun').find({
+ const [runningWorkflowRun] = await inWorkspace(() =>
+ workflowRunRepository().find({
where: { status: WorkflowRunStatus.RUNNING },
select: { id: true, state: true },
take: 1,
}),
- )) as Pick<WorkflowRunWorkspaceEntity, 'id' | 'state'>[];
+ );
if (!isDefined(runningWorkflowRun?.state)) {
throw new Error('The seed has no running workflow run to add a form to');
}
+ workflowRunId = runningWorkflowRun.id;
originalState = runningWorkflowRun.state;
formStepId = randomUUID();
- seededThreadId = randomUUID();
-
- // a form step waiting since before 2.44, with the conversation 2.44 recorded for it
- workflowRun = {
- id: runningWorkflowRun.id,
- state: {
- ...originalState,
- flow: {
- ...originalState.flow,
- steps: [
- ...originalState.flow.steps,
- {
- id: formStepId,
- name: 'Approve the discount',
- type: WorkflowActionType.FORM,
- valid: true,
- settings: {
- input: [
- {
- id: randomUUID(),
- name: 'discount',
- label: 'Discount',
- type: FieldMetadataType.NUMBER,
+
+ // a form step waiting since before 2.44, with no recorded conversation
+ await inWorkspace(() =>
+ workflowRunRepository().update(workflowRunId, {
+ state: {
+ ...originalState,
+ flow: {
+ ...originalState.flow,
+ steps: [
+ ...originalState.flow.steps,
+ {
+ id: formStepId,
+ name: 'Approve the discount',
+ type: WorkflowActionType.FORM,
+ valid: true,
+ settings: {
+ input: [
+ {
+ id: randomUUID(),
+ name: 'discount',
+ label: 'Discount',
+ type: FieldMetadataType.NUMBER,
+ },
+ ],
+ outputSchema: {},
+ errorHandlingOptions: {
+ retryOnFailure: { value: 0 },
+ continueOnFailure: { value: false },
},
- ],
- outputSchema: {},
- errorHandlingOptions: {
- retryOnFailure: { value: 0 },
- continueOnFailure: { value: false },
},
+ nextStepIds: [],
},
- nextStepIds: [],
- },
- ],
- },
- stepInfos: {
- ...originalState.stepInfos,
- [formStepId]: {
- status: StepStatus.PENDING,
- threadId: seededThreadId,
+ ],
+ },
+ stepInfos: {
+ ...originalState.stepInfos,
+ [formStepId]: { status: StepStatus.PENDING },
},
},
- },
- };
-
- await inWorkspace(async () => {
- await repository('workflowRun').update(workflowRun.id, {
- state: workflowRun.state,
- });
- await repository('agentChatThread').insert({
- id: seededThreadId,
- title: 'Approve the discount',
- workflowRunId: workflowRun.id,
- });
- });
+ }),
+ );
});
afterAll(async () => {
- if (!isDefined(workflowRun) || !isDefined(originalState)) {
+ if (!isDefined(workflowRunId) || !isDefined(originalState)) {
return;
}
- await inWorkspace(async () => {
- await repository('agentChatThread').delete({ id: seededThreadId });
- await repository('workflowRun').update(workflowRun.id, {
- state: originalState,
- });
- });
- });
-
- afterEach(async () => {
- const threadId = await findFormThreadId();
-
- await inWorkspace(async () => {
- if (threadId !== undefined && threadId !== seededThreadId) {
- await repository('agentChatThread').delete({ id: threadId });
- }
-
- await repository('workflowRun').update(workflowRun.id, {
- state: workflowRun.state,
- });
- });
+ await inWorkspace(() =>
+ workflowRunRepository().update(workflowRunId, { state: originalState }),
+ );
});
it('is registered in the 2.44 bundle', () => {
@@ -189,51 +131,32 @@ describe('2-44 workspace command 1790772993322 - RecordPendingFormConversationsC
);
});
- it('records nothing on a dry run', async () => {
- await forgetFormConversation();
-
- await runCommand({ dryRun: true });
-
- expect(await findFormThreadId()).toBeUndefined();
- });
-
- it('records a pending request_form call named after the step, that the conversation waits on', async () => {
- await forgetFormConversation();
-
- await runCommand();
-
- const threadId = await findFormThreadId();
-
- const thread = await inWorkspace(() =>
- repository('agentChatThread').findOneOrFail({
- where: { id: threadId },
- select: { workflowRunId: true, pendingQuestionMessageId: true },
- }),
+ it('records no conversation once threads no longer name a run', async () => {
+ const countThreads = () =>
+ inWorkspace(() =>
+ workspaceOrmManager
+ .getRepository('agentChatThread', {
+ shouldBypassPermissionChecks: true,
+ })
+ .count({ withDeleted: true }),
+ );
+ const threadCountBefore = await countThreads();
+
+ await inWorkspace(() =>
+ command.runOnWorkspace({ ...RUN_ON_WORKSPACE_ARGS, options: {} }),
);
- expect(thread.workflowRunId).toBe(workflowRun.id);
+ expect(await countThreads()).toBe(threadCountBefore);
- const parts = await inWorkspace(() =>
- repository('agentMessagePart').find({
- where: { messageId: thread.pendingQuestionMessageId },
- select: { toolName: true, toolCallId: true, toolOutput: true },
+ const { state } = await inWorkspace(() =>
+ workflowRunRepository().findOneOrFail({
+ where: { id: workflowRunId },
+ select: { state: true },
}),
);
- expect(parts).toEqual([
- {
- toolName: 'request_form',
- toolCallId: formStepId,
- toolOutput: expect.objectContaining({
- result: { status: 'pending' },
- }),
- },
- ]);
- });
-
- it('leaves a form whose conversation is recorded alone', async () => {
- await runCommand();
-
- expect(await findFormThreadId()).toBe(seededThreadId);
+ expect(state?.stepInfos?.[formStepId]).toEqual({
+ status: StepStatus.PENDING,
+ });
});
});
diff --git a/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.ts b/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.ts
index 19588bea870..4118423e4cd 100644
--- a/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.ts
+++ b/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.ts
@@ -3,7 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-// Mirrors the chat list: deleted chats stay listed for restore, run conversations are excluded.
+// Mirrors the chat list: deleted chats stay listed for restore.
export const listChatThreadIds = async (
token = APPLE_JANE_ADMIN_ACCESS_TOKEN,
): Promise<string[]> => {
@@ -13,15 +13,7 @@ export const listChatThreadIds = async (
objectMetadataPluralName: 'agentChatThreads',
gqlFields: 'id',
filter: {
- and: [
- { workflowRunId: { is: 'NULL' } },
- {
- or: [
- { deletedAt: { is: 'NULL' } },
- { deletedAt: { is: 'NOT_NULL' } },
- ],
- },
- ],
+ or: [{ deletedAt: { is: 'NULL' } }, { deletedAt: { is: 'NOT_NULL' } }],
},
orderBy: [{ updatedAt: 'DescNullsLast' }],
first: 200,
diff --git a/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap b/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap
index af4126a0c6b..eec10538805 100644
--- a/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap
+++ b/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap
@@ -82,9 +82,6 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e
"userWorkspaceId": {
"universalIdentifier": "bf830886-b6dc-46e9-a229-eecbb0e66032",
},
- "workflowRun": {
- "universalIdentifier": "2187f4c6-bff3-4b80-8585-c82965faf79b",
- },
"workspaceMember": {
"universalIdentifier": "6f3ed3b5-0642-4a2a-9558-98376adb60f4",
},
@@ -96,9 +93,6 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e
"ownerIndex": {
"universalIdentifier": "c97a4c97-266b-490a-a4d6-76274f5de429",
},
- "workflowRunIndex": {
- "universalIdentifier": "cc9f8c37-a1ad-4d8d-8e27-894c2cf01a3b",
- },
"workspaceMemberIndex": {
"universalIdentifier": "079f2dd7-6c11-4eae-be8a-cce2d1bee0fb",
},
@@ -3865,9 +3859,6 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e
},
"workflowRun": {
"fields": {
- "agentChatThreads": {
- "universalIdentifier": "c664a2e7-ef64-4597-9cdf-ded3eae85ae4",
- },
"coreWorkflowId": {
"universalIdentifier": "e07d8ac0-6b6e-4685-81fa-50d82ae7f880",
},
diff --git a/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts
index afe26fc7e2a..a068f871d8e 100644
--- a/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts
+++ b/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts
@@ -47,9 +47,6 @@ export const STANDARD_OBJECT_FIELDS = {
activeStreamId: {
universalIdentifier: 'bcead20f-75b3-45be-92b9-ea7ec4bddfcd',
},
- workflowRun: {
- universalIdentifier: '2187f4c6-bff3-4b80-8585-c82965faf79b',
- },
pendingQuestionMessageId: {
universalIdentifier: '51a9b421-7d90-4a59-9712-036ea9721e65',
},
@@ -1502,9 +1499,6 @@ export const STANDARD_OBJECT_FIELDS = {
coreWorkflowVersionId: {
universalIdentifier: '58e3f476-425d-4c66-b391-779d0412e107',
},
- agentChatThreads: {
- universalIdentifier: 'c664a2e7-ef64-4597-9cdf-ded3eae85ae4',
- },
timelineActivities: {
universalIdentifier: getSystemRelationFieldUniversalIdentifier({
applicationUniversalIdentifier:
diff --git a/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts
index d95732dc44b..a566e5aec31 100644
--- a/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts
+++ b/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts
@@ -1414,9 +1414,6 @@ export const STANDARD_OBJECTS = {
workspaceMemberIndex: {
universalIdentifier: '079f2dd7-6c11-4eae-be8a-cce2d1bee0fb',
},
- workflowRunIndex: {
- universalIdentifier: 'cc9f8c37-a1ad-4d8d-8e27-894c2cf01a3b',
- },
},
},
agentChatThreadParticipant: {
diff --git a/packages/twenty-shared/src/workflow/index.ts b/packages/twenty-shared/src/workflow/index.ts
index 11fda006408..40af1c37535 100644
--- a/packages/twenty-shared/src/workflow/index.ts
+++ b/packages/twenty-shared/src/workflow/index.ts
@@ -103,6 +103,10 @@ export { workflowWaitForEventActionSchema } from './schemas/wait-for-event-actio
export { workflowWaitForEventActionSettingsSchema } from './schemas/wait-for-event-action-settings-schema';
export { workflowWebhookTriggerSchema } from './schemas/webhook-trigger-schema';
export { workflowActionSchema } from './schemas/workflow-action-schema';
+export {
+ workflowConversationScopeSchema,
+ workflowConversationSchema,
+} from './schemas/workflow-conversation-schema';
export { workflowDelayActionSchema } from './schemas/workflow-delay-action-schema';
export { workflowDelayActionSettingsSchema } from './schemas/workflow-delay-action-settings-schema';
export { workflowFileSchema } from './schemas/workflow-file-action-schema';
@@ -134,6 +138,10 @@ export type {
WorkflowClassifyCriterion,
WorkflowClassifyQuestion,
} from './types/WorkflowClassifyQuestion';
+export type {
+ WorkflowConversation,
+ WorkflowConversationScope,
+} from './types/WorkflowConversation';
export type { BodyType } from './types/WorkflowHttpRequestStep';
export type {
WorkflowRunStepInfo,
diff --git a/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
index cd544823bd1..c171e3f71b3 100644
--- a/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
import { baseWorkflowActionSettingsSchema } from './base-workflow-action-settings-schema';
+import { workflowConversationSchema } from './workflow-conversation-schema';
export const workflowAiAgentActionSettingsSchema =
baseWorkflowActionSettingsSchema.extend({
@@ -8,5 +9,9 @@ export const workflowAiAgentActionSettingsSchema =
prompt: z.string().optional(),
// Empty by default: stopping for a person pauses the run, which existing workflows were not built to expect.
humanInputInstructions: z.string().optional(),
+ // the member the agent's conversation is with, the workflow's creator when empty
+ workspaceMemberId: z.string().optional(),
+ // a new conversation each time the step runs when unset
+ conversation: workflowConversationSchema.optional(),
}),
});
diff --git a/packages/twenty-shared/src/workflow/schemas/send-chat-message-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/send-chat-message-action-settings-schema.ts
index 0997c4636ba..1d3b19fef07 100644
--- a/packages/twenty-shared/src/workflow/schemas/send-chat-message-action-settings-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/send-chat-message-action-settings-schema.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
import { baseWorkflowActionSettingsSchema } from './base-workflow-action-settings-schema';
+import { workflowConversationSchema } from './workflow-conversation-schema';
export const workflowSendChatMessageActionSettingsSchema =
baseWorkflowActionSettingsSchema.extend({
@@ -14,5 +15,7 @@ export const workflowSendChatMessageActionSettingsSchema =
arguments: z.record(z.string(), z.any()),
})
.optional(),
+ // one conversation per run when unset
+ conversation: workflowConversationSchema.optional(),
}),
});
diff --git a/packages/twenty-shared/src/workflow/schemas/workflow-conversation-schema.ts b/packages/twenty-shared/src/workflow/schemas/workflow-conversation-schema.ts
new file mode 100644
index 00000000000..885809f728a
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/schemas/workflow-conversation-schema.ts
@@ -0,0 +1,10 @@
+import { z } from 'zod';
+
+// RUN: one conversation per run. STEP: a new one each time the step runs.
+// KEY: steps of the workflow sharing a key write to the same conversation, across runs.
+export const workflowConversationScopeSchema = z.enum(['RUN', 'STEP', 'KEY']);
+
+export const workflowConversationSchema = z.object({
+ scope: workflowConversationScopeSchema,
+ key: z.string().optional(),
+});
diff --git a/packages/twenty-shared/src/workflow/types/WorkflowConversation.ts b/packages/twenty-shared/src/workflow/types/WorkflowConversation.ts
new file mode 100644
index 00000000000..d2db95bdc0e
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/types/WorkflowConversation.ts
@@ -0,0 +1,11 @@
+import {
+ type workflowConversationSchema,
+ type workflowConversationScopeSchema,
+} from '@/workflow/schemas/workflow-conversation-schema';
+import type z from 'zod';
+
+export type WorkflowConversation = z.infer<typeof workflowConversationSchema>;
+
+export type WorkflowConversationScope = z.infer<
+ typeof workflowConversationScopeSchema
+>;
diff --git a/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts b/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts
index 5949dfd5aa6..0a4c511b1cd 100644
--- a/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts
+++ b/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts
@@ -11,6 +11,7 @@ export const NON_ACTIVABLE_WORKFLOW_VALIDATION_ISSUE_CODES: ReadonlySet<Workflow
'ITERATOR_MISSING_LOOP_BODY',
'INCOMPLETE_PICK_RECORD_CONFIG',
'AI_AGENT_MISSING_AGENT',
+ 'CONVERSATION_MISSING_KEY',
'CLASSIFY_MISSING_STATE',
'CLASSIFY_INCOMPLETE_QUESTION',
'VARIABLE_INVALID_PATH',
diff --git a/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts b/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts
index de5a77bb7b4..f4ca317246f 100644
--- a/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts
+++ b/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts
@@ -36,6 +36,7 @@ export type WorkflowValidationIssueCode =
| 'VARIABLE_PATH_NOT_FOUND'
| 'AI_AGENT_MISSING_AGENT'
| 'AI_AGENT_MISSING_OUTPUT_VARIABLE'
+ | 'CONVERSATION_MISSING_KEY'
| 'CLASSIFY_MISSING_STATE'
| 'CLASSIFY_INCOMPLETE_QUESTION';