Skip to content

The open alternative to Salesforce, designed for AI.

Pull and apply email and calendar workflow steps (#29048)

Félix Malfaitce424457f5d0
diff --git a/packages/twenty-agent-skills/references/develop-app/workflows.md b/packages/twenty-agent-skills/references/develop-app/workflows.md
index 29441264dc0..6f53d36f05e 100644
--- a/packages/twenty-agent-skills/references/develop-app/workflows.md
+++ b/packages/twenty-agent-skills/references/develop-app/workflows.md
@@ -6,9 +6,15 @@ See `logic.md` for post-install hooks. See `app-structure.md` for source layout.
## Mental Model
-Twenty workflows are workspace records, not app entities — no `define*` primitive. Ship them via `definePostInstallLogicFunction` and the workspace API.
+Declare app workflows with `defineWorkflow` from `twenty-sdk/define`: one call per workflow, holding a trigger and its steps. `twenty app pull` writes workflows in this form.
-A workflow is a `Workflow` plus at least one `WorkflowVersion`. Creating a `Workflow` auto-creates its draft `v1`; never create a `WorkflowVersion` directly.
+Workflows created at runtime through the workspace API are a `Workflow` plus at least one `WorkflowVersion`. Creating a `Workflow` auto-creates its draft `v1`; never create a `WorkflowVersion` directly.
+
+## Email and Calendar Steps
+
+- `SEND_EMAIL`, `DRAFT_EMAIL` and `CREATE_CALENDAR_EVENT` name their account with exactly one of `connectedAccountId` or `connectedAccountHandle`.
+- Use `connectedAccountHandle` (the account's email address) in app code: ids only exist in one workspace. Apply resolves it to the oldest active account with that address that is shared with the workspace (`WORKSPACE` scope) and can run the step, and fails if none can. A member's private account can't be named by handle.
+- `twenty app pull` writes a shared account's id as its handle. Private account ids, variables and workspace member ids stay `connectedAccountId`.
## Manual Record Trigger
diff --git a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
index 397cb347681..df09dd7d319 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
@@ -106,7 +106,11 @@ Their inputs match the steps of the [workflow builder](/user-guide/workflows/cap
- Form fields of type `RECORD` name their object with `settings.objectUniversalIdentifier`. Fields of type `SELECT` and `MULTI_SELECT` offer the options of an existing field of the same type, named with `settings.selectedFieldUniversalIdentifier`.
- To run your own code, use a `LOGIC_FUNCTION` step. The builder's Code step is not available.
- Email and calendar steps run only if your app's role has the matching permission flag: `SystemPermissionFlag.SEND_EMAIL_TOOL` for `SEND_EMAIL` and `DRAFT_EMAIL`, `SystemPermissionFlag.CREATE_CALENDAR_EVENT_TOOL` for `CREATE_CALENDAR_EVENT`. The workspace grants it by installing the app, and the step can then use any connected account in the workspace, like a workflow built in the app.
-- Connected account ids are local to each workspace, so don't hardcode one. Pass the account as a variable. Email steps also take a workspace member id, such as `{{trigger.properties.after.assigneeId}}`, which resolves to that member's first account able to send.
+- Connected account ids are local to each workspace, so don't hardcode one. Name the account in one of two ways:
+ - `connectedAccountHandle`: the account's email address, such as `'[email protected]'`. When the app is synced, the handle resolves to an account with that address that is shared with the workspace (`WORKSPACE` scope) and can run the step. A member's private account can't be named by handle: pull keeps it as its `connectedAccountId`. If several accounts share the address, for example one mailbox connected by two members or through two providers, the oldest one wins. If none matches, the sync fails and names the handle. This is not `fromHandle`, which picks an alias to send from.
+ - `connectedAccountId`: a variable, such as `{{trigger.properties.after.connectedAccountId}}`. Email steps also take a workspace member id, such as `{{trigger.properties.after.assigneeId}}`, which resolves to that member's first account able to send.
+
+ Set exactly one of the two.
## After install
diff --git a/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx b/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
index 515147d7eb2..0791e0dae81 100644
--- a/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
+++ b/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
@@ -145,7 +145,7 @@ Each entity goes to the file that already defines it, so a second pull rewrites
- **Placed on a default or foreign view** — filters, filter groups, sorts, groups and field groups added to an engine default view, or to a view owned by another application, have no source form yet and are reported. View fields added there are written as standalone files, since the view's identifier is known.
- **Placed on a default or foreign page layout** — tabs and widgets added to an engine default page layout, or to one owned by another application, are written as standalone `definePageLayoutTab()` and `definePageLayoutWidget()` files, since the identifier they attach to is known.
- **Widgets the export cannot carry yet** — on any layout, including your own, a widget of the deprecated `VIEW` type, a widget showing one of your app's own front components or command menu items, or a widget without a position for its tab's layout mode is reported, and the layout or tab is written without it.
-- **Workflows the export cannot carry yet** — a workflow changed in the workflow builder since the last sync, a system or private workflow, one with a Code or chat message step, which application workflows don't support, or an email or calendar step, which export doesn't carry yet, and one calling another app's workflow action are reported and left in place. The workspace custom application is the exception for the first and last cases: the builder publishes its workflows too, and they may call any app's actions, so they are pulled. One of its workflows is reported instead when it has no active version, or when its active version uses settings a definition can't express.
+- **Workflows the export cannot carry yet** — a workflow changed in the workflow builder since the last sync, a system or private workflow, one with a Code or chat message step, which application workflows don't support, and one calling another app's workflow action are reported and left in place. The workspace custom application is the exception for the first and last cases: the builder publishes its workflows too, and they may call any app's actions, so they are pulled. One of its workflows is reported instead when it has no active version, or when its active version uses settings a definition can't express. Email and calendar steps are pulled: an account shared with the workspace is written as its `connectedAccountHandle`, while a member's private account and variables are kept as they are. The workflow is reported instead when a step's account is archived, can no longer run the step, or shares its address with an older account, since applying the handle would pick another account.
- **Agents and skills the export cannot carry yet** — a deactivated skill, and an agent on more than one role or bound to a role pull does not write, are reported and left in place.
- **Workspace runtime state** — member and API-key role assignments, webhooks, per-user navigation and navigation items pinned to a record, all excluded by design.
- **Owned by another application** — reported, never pulled.
diff --git a/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts b/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts
index c27091c80ad..5a4803e1fae 100644
--- a/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts
+++ b/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts
@@ -35,6 +35,22 @@ const withStep = (step: Record<string, unknown>) => ({
},
});
+const withSendEmailStep = (input: Record<string, unknown>) => ({
+ ...workflow,
+ version: {
+ ...workflow.version,
+ steps: [
+ {
+ universalIdentifier: STEP_ID,
+ name: 'Email',
+ type: 'SEND_EMAIL',
+ input: { recipients: { to: '[email protected]' }, ...input },
+ nextStepIds: [],
+ },
+ ],
+ },
+});
+
describe('defineWorkflow', () => {
it('accepts a manual workflow', () => {
expect(defineWorkflow(workflow)).toEqual({
@@ -54,7 +70,24 @@ describe('defineWorkflow', () => {
});
});
+ it('accepts an email step naming its account by handle', () => {
+ const definition = withSendEmailStep({
+ connectedAccountHandle: '[email protected]',
+ }) as WorkflowManifest;
+
+ expect(defineWorkflow(definition).errors).toEqual([]);
+ });
+
it.each([
+ {
+ problem: 'an email step naming its account by both id and handle',
+ definition: withSendEmailStep({
+ connectedAccountId: '{{trigger.accountId}}',
+ connectedAccountHandle: '[email protected]',
+ }),
+ error:
+ 'version.steps.0.input.connectedAccountHandle: Set exactly one of connectedAccountId and connectedAccountHandle',
+ },
{
problem: 'a step type applications cannot use',
definition: withStep({ type: 'CODE' }),
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
index 83e0a90ac93..0233ac339be 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
@@ -240,6 +240,12 @@ export class ApplicationManifestMigrationService {
})
: {};
+ const connectedAccounts = hasWorkflows
+ ? await this.connectedAccountMetadataService.findAllForWorkflowStepResolution(
+ { workspaceId },
+ )
+ : [];
+
const applicationWorkflows = addWorkflowManifestsToFlatEntityMapsOrThrow({
workflows: manifest.workflows ?? [],
ownerFlatApplication,
@@ -249,6 +255,7 @@ export class ApplicationManifestMigrationService {
idByUniversalIdentifierByMetadataName,
isWorkspaceCustomApplication:
ownerFlatApplication.id === workspaceCustomFlatApplication?.id,
+ connectedAccounts,
now,
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/constants/workflow-connected-account-step-capability.constant.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/constants/workflow-connected-account-step-capability.constant.ts
new file mode 100644
index 00000000000..7733d67e055
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/constants/workflow-connected-account-step-capability.constant.ts
@@ -0,0 +1,10 @@
+import { type WorkflowConnectedAccountStepType } from 'src/engine/core-modules/application/application-manifest/types/workflow-connected-account-step-type.type';
+
+export const WORKFLOW_CONNECTED_ACCOUNT_STEP_CAPABILITY: Record<
+ WorkflowConnectedAccountStepType,
+ string
+> = {
+ SEND_EMAIL: 'send email',
+ DRAFT_EMAIL: 'draft email',
+ CREATE_CALENDAR_EVENT: 'create calendar events',
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.ts
index 77f11f46923..d460dd55a7a 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.ts
@@ -4,6 +4,7 @@ import {
type WorkflowTriggerManifest,
} from 'twenty-shared/application';
import {
+ ConnectedAccountProvider,
FieldMetadataType,
RecordFilterGroupLogicalOperator,
RelationType,
@@ -15,7 +16,10 @@ import { WorkflowActionType } from 'twenty-shared/workflow';
import { fromFlatWorkflowToWorkflowManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util';
import { fromWorkflowManifestToUniversalFlatWorkflowOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util';
-import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import {
+ type WorkflowManifestConnectedAccountReference,
+ type WorkflowManifestReferences,
+} from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
import { type FlatWorkflow } from 'src/engine/metadata-modules/flat-workflow/types/flat-workflow.type';
import { type FlatWorkflowVersion } from 'src/engine/metadata-modules/flat-workflow-version/types/flat-workflow-version.type';
@@ -33,7 +37,25 @@ const FUNCTION_ID = '70000000-0000-4000-8000-000000000000';
const AGENT_ID = '80000000-0000-4000-8000-000000000000';
const RECORD_FILTER_ID = '90000000-0000-4000-8000-000000000000';
+const SALES_HANDLE = '[email protected]';
+const WORKSPACE_MEMBER_ID = 'a0000000-0000-4000-8000-000000000000';
+
+const connectedAccount = (
+ overrides: Partial<WorkflowManifestConnectedAccountReference>,
+): WorkflowManifestConnectedAccountReference => ({
+ id: 'sales-account-id',
+ handle: SALES_HANDLE,
+ provider: ConnectedAccountProvider.GOOGLE,
+ connectionParameters: null,
+ archivedAt: null,
+ scopes: ['https://www.googleapis.com/auth/calendar.events'],
+ scope: 'WORKSPACE',
+ calendarChannels: [{ isSyncEnabled: true }],
+ ...overrides,
+});
+
const references: WorkflowManifestReferences = {
+ connectedAccounts: [connectedAccount({})],
logicFunctionIdByUniversalIdentifier: new Map([
[FUNCTION_ID, 'logic-function-id'],
]),
@@ -183,6 +205,27 @@ const STEP_INPUTS = {
recordId: '{{trigger.recordId}}',
timeout: { days: 1 },
},
+ SEND_EMAIL: {
+ connectedAccountHandle: SALES_HANDLE,
+ recipients: { to: '{{trigger.properties.after.email}}', cc: '', bcc: '' },
+ subject: 'Welcome',
+ files: [],
+ },
+ DRAFT_EMAIL: {
+ connectedAccountId: '{{trigger.properties.after.assigneeId}}',
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ files: [],
+ },
+ CREATE_CALENDAR_EVENT: {
+ connectedAccountHandle: SALES_HANDLE,
+ title: 'Kick-off',
+ startsAt: '2026-11-02T09:00:00.000Z',
+ endsAt: '2026-11-02T09:30:00.000Z',
+ isFullDay: false,
+ attendees: '',
+ sendInvitations: true,
+ addConferencing: false,
+ },
EMPTY: {},
};
@@ -217,6 +260,22 @@ const buildWorkflow = ({
version: { trigger, steps },
});
+const sendEmailWorkflow = (accountReference: Record<string, string>) => {
+ const { connectedAccountHandle: _connectedAccountHandle, ...input } =
+ STEP_INPUTS.SEND_EMAIL;
+
+ return buildWorkflow({
+ steps: [
+ buildStep({
+ type: 'SEND_EMAIL',
+ overrides: {
+ input: { ...input, ...accountReference },
+ } as Partial<WorkflowStepManifest>,
+ }),
+ ],
+ });
+};
+
const syncWorkflow = (manifest: WorkflowManifest) => {
const { flatUniversalWorkflowVersion, ...workflow } =
fromWorkflowManifestToUniversalFlatWorkflowOrThrow({
@@ -368,6 +427,44 @@ describe('fromFlatWorkflowToWorkflowManifest', () => {
);
});
+ describe('connected accounts', () => {
+ it('stores the account a handle resolves to and exports its handle back', () => {
+ const synced = syncWorkflow(
+ sendEmailWorkflow({ connectedAccountId: 'sales-account-id' }),
+ );
+
+ expect(
+ synced.flatWorkflowVersion.steps?.[0]?.settings.input,
+ ).toMatchObject({ connectedAccountId: 'sales-account-id' });
+ expect(exportWorkflow(synced)).toEqual({
+ manifest: sendEmailWorkflow({ connectedAccountHandle: SALES_HANDLE }),
+ });
+ });
+
+ it('exports a step on an account private to a member as its id', () => {
+ const manifest = sendEmailWorkflow({
+ connectedAccountId: 'sales-account-id',
+ });
+
+ expect(
+ exportWorkflow({
+ ...syncWorkflow(manifest),
+ exportReferences: {
+ ...references,
+ connectedAccounts: [connectedAccount({ scope: 'USER' })],
+ },
+ }),
+ ).toEqual({ manifest });
+ });
+
+ it.each(['{{trigger.properties.after.assigneeId}}', WORKSPACE_MEMBER_ID])(
+ 'keeps the account value %s as it was declared',
+ (connectedAccountId) => {
+ expectRoundTrip(sendEmailWorkflow({ connectedAccountId }));
+ },
+ );
+ });
+
it('omits values the sync derives', () => {
const result = exportWorkflow(
syncWorkflow(
@@ -490,22 +587,19 @@ describe('fromFlatWorkflowToWorkflowManifest', () => {
});
describe('unsupported workflows', () => {
- it.each([
- WorkflowActionType.CODE,
- WorkflowActionType.SEND_EMAIL,
- WorkflowActionType.DRAFT_EMAIL,
- WorkflowActionType.SEND_CHAT_MESSAGE,
- WorkflowActionType.CREATE_CALENDAR_EVENT,
- ])('reports a %s step', (type) => {
- const synced = syncWorkflow(buildWorkflow({}));
- const [step] = synced.flatWorkflowVersion.steps ?? [];
+ it.each([WorkflowActionType.CODE, WorkflowActionType.SEND_CHAT_MESSAGE])(
+ 'reports a %s step',
+ (type) => {
+ const synced = syncWorkflow(buildWorkflow({}));
+ const [step] = synced.flatWorkflowVersion.steps ?? [];
- Object.assign(step, { type });
+ Object.assign(step, { type });
- expect(exportWorkflow(synced)).toEqual({
- reason: `${type} steps are not supported in application workflows`,
- });
- });
+ expect(exportWorkflow(synced)).toEqual({
+ reason: `${type} steps are not supported in application workflows`,
+ });
+ },
+ );
it('reports a record filter on a field of a related record', () => {
const synced = syncWorkflow(
@@ -644,6 +738,75 @@ describe('fromFlatWorkflowToWorkflowManifest', () => {
).toEqual({ reason: 'workflow watching a field that is not exported' });
});
+ it.each([
+ {
+ case: 'an archived account',
+ account: connectedAccount({ archivedAt: new Date() }),
+ reason: `workflow step on archived connected account ${SALES_HANDLE}`,
+ },
+ {
+ case: 'an account that cannot send email',
+ account: connectedAccount({ provider: ConnectedAccountProvider.OIDC }),
+ reason: `workflow step on connected account ${SALES_HANDLE}, which cannot send email`,
+ },
+ ])('reports a step on $case', ({ account, reason }) => {
+ const synced = syncWorkflow(
+ buildWorkflow({ steps: [buildStep({ type: 'SEND_EMAIL' })] }),
+ );
+
+ expect(
+ exportWorkflow({
+ ...synced,
+ exportReferences: { ...references, connectedAccounts: [account] },
+ }),
+ ).toEqual({ reason });
+ });
+
+ it('reports a calendar step on an account whose calendar sync is disabled', () => {
+ const synced = syncWorkflow(
+ buildWorkflow({
+ steps: [buildStep({ type: 'CREATE_CALENDAR_EVENT' })],
+ }),
+ );
+
+ expect(
+ exportWorkflow({
+ ...synced,
+ exportReferences: {
+ ...references,
+ connectedAccounts: [
+ connectedAccount({
+ calendarChannels: [{ isSyncEnabled: false }],
+ }),
+ ],
+ },
+ }),
+ ).toEqual({
+ reason: `workflow step on connected account ${SALES_HANDLE}, which cannot create calendar events`,
+ });
+ });
+
+ it('reports a step on an account whose handle names an older account', () => {
+ const synced = syncWorkflow(
+ sendEmailWorkflow({ connectedAccountId: 'sales-account-id' }),
+ );
+
+ expect(
+ exportWorkflow({
+ ...synced,
+ exportReferences: {
+ ...references,
+ connectedAccounts: [
+ connectedAccount({ id: 'older-account-id' }),
+ connectedAccount({}),
+ ],
+ },
+ }),
+ ).toEqual({
+ reason: `workflow step on connected account ${SALES_HANDLE}, whose handle names an older account of the workspace`,
+ });
+ });
+
it('reports a version the sync would not reproduce', () => {
const synced = syncWorkflow(buildWorkflow({}));
const trigger = synced.flatWorkflowVersion.triggers?.[0];
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
index 4a653bd6e58..a964128e7cf 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
@@ -1,4 +1,8 @@
-import { FieldMetadataType, ViewFilterOperand } from 'twenty-shared/types';
+import {
+ ConnectedAccountProvider,
+ FieldMetadataType,
+ ViewFilterOperand,
+} from 'twenty-shared/types';
import {
workflowStepManifestSchema,
type WorkflowStepManifest,
@@ -6,6 +10,7 @@ import {
import { WorkflowActionType } from 'twenty-shared/workflow';
import { fromWorkflowStepManifestToActionOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util';
+import { type WorkflowManifestConnectedAccountReference } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
const STEP_ID = '11111111-1111-4111-8111-111111111111';
const REFERENCE_ID = '22222222-2222-4222-8222-222222222222';
@@ -377,6 +382,155 @@ describe('application workflow actions', () => {
).toThrow('does not belong');
});
+ describe('connected accounts', () => {
+ const GOOGLE_CALENDAR_EVENTS_SCOPE =
+ 'https://www.googleapis.com/auth/calendar.events';
+ const connectedAccount = (
+ overrides: Partial<WorkflowManifestConnectedAccountReference>,
+ ): WorkflowManifestConnectedAccountReference => ({
+ id: 'account-id',
+ handle: '[email protected]',
+ provider: ConnectedAccountProvider.GOOGLE,
+ connectionParameters: null,
+ archivedAt: null,
+ scopes: [GOOGLE_CALENDAR_EVENTS_SCOPE],
+ scope: 'WORKSPACE',
+ calendarChannels: [{ isSyncEnabled: true }],
+ ...overrides,
+ });
+ const connectedAccounts = [
+ connectedAccount({ id: 'archived-id', archivedAt: new Date() }),
+ connectedAccount({
+ id: 'imap-id',
+ provider: ConnectedAccountProvider.IMAP_SMTP_CALDAV,
+ connectionParameters: {
+ IMAP: { host: 'imap.example.com', port: 993 },
+ } as WorkflowManifestConnectedAccountReference['connectionParameters'],
+ scopes: null,
+ calendarChannels: [],
+ }),
+ connectedAccount({ id: 'google-id', handle: '[email protected]' }),
+ ];
+ const convertWithHandle = ({
+ type,
+ handle,
+ accounts = connectedAccounts,
+ }: {
+ type: 'SEND_EMAIL' | 'DRAFT_EMAIL' | 'CREATE_CALENDAR_EVENT';
+ handle: string;
+ accounts?: WorkflowManifestConnectedAccountReference[];
+ }) => {
+ const { connectedAccountId: _connectedAccountId, ...input } =
+ inputs[type];
+
+ return fromWorkflowStepManifestToActionOrThrow({
+ step: workflowStepManifestSchema.parse({
+ universalIdentifier: STEP_ID,
+ name: 'Reach out',
+ type,
+ input: { ...input, connectedAccountHandle: handle },
+ nextStepIds: [],
+ }),
+ index: 0,
+ references: { ...references, connectedAccounts: accounts },
+ }).settings.input;
+ };
+
+ it.each([
+ { type: 'SEND_EMAIL' as const, connectedAccountId: 'google-id' },
+ { type: 'DRAFT_EMAIL' as const, connectedAccountId: 'imap-id' },
+ {
+ type: 'CREATE_CALENDAR_EVENT' as const,
+ connectedAccountId: 'google-id',
+ },
+ ])(
+ 'resolves a $type handle to the oldest active account able to run it',
+ ({ type, connectedAccountId }) => {
+ const input = convertWithHandle({ type, handle: '[email protected]' });
+
+ expect(input).toMatchObject({ connectedAccountId });
+ expect(input).not.toHaveProperty('connectedAccountHandle');
+ },
+ );
+
+ it.each([
+ {
+ case: 'calendar sync is disabled',
+ account: connectedAccount({
+ calendarChannels: [{ isSyncEnabled: false }],
+ }),
+ },
+ {
+ case: 'the calendar scope is missing',
+ account: connectedAccount({ scopes: [] }),
+ },
+ ])(
+ 'does not create calendar events with an account whose $case',
+ ({ account }) => {
+ expect(() =>
+ convertWithHandle({
+ type: 'CREATE_CALENDAR_EVENT',
+ handle: '[email protected]',
+ accounts: [account],
+ }),
+ ).toThrow('can create calendar events');
+ },
+ );
+
+ it.each([
+ '{{trigger.properties.after.assigneeId}}',
+ '20202020-0687-4c41-b707-ed1bfca972a7',
+ ])('keeps the account value %s as declared', (connectedAccountId) => {
+ expect(
+ fromWorkflowStepManifestToActionOrThrow({
+ step: workflowStepManifestSchema.parse({
+ universalIdentifier: STEP_ID,
+ name: 'Reach out',
+ type: 'SEND_EMAIL',
+ input: { ...email, connectedAccountId },
+ nextStepIds: [],
+ }),
+ index: 0,
+ references: { ...references, connectedAccounts },
+ }).settings.input,
+ ).toMatchObject({ connectedAccountId });
+ });
+
+ it('fails on a handle no account of the workspace can send from', () => {
+ expect(() =>
+ convertWithHandle({
+ type: 'SEND_EMAIL',
+ handle: '[email protected]',
+ }),
+ ).toThrow(
+ 'Workflow step Reach out: no connected account [email protected] shared with this workspace can send email',
+ );
+ });
+
+ it('does not resolve a handle to an account private to a member', () => {
+ expect(() =>
+ convertWithHandle({
+ type: 'SEND_EMAIL',
+ handle: '[email protected]',
+ accounts: [connectedAccount({ scope: 'USER' })],
+ }),
+ ).toThrow('no connected account [email protected] shared with');
+ });
+
+ it('resolves a handle to a shared account over an older private one', () => {
+ expect(
+ convertWithHandle({
+ type: 'SEND_EMAIL',
+ handle: '[email protected]',
+ accounts: [
+ connectedAccount({ id: 'private-id', scope: 'USER' }),
+ connectedAccount({ id: 'shared-id' }),
+ ],
+ }),
+ ).toMatchObject({ connectedAccountId: 'shared-id' });
+ });
+ });
+
it('preserves branches, loop entries, outputs and error handling', () => {
expect(convert(WorkflowActionType.IF_ELSE).settings.input).toEqual(
inputs.IF_ELSE,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.ts
index f85833f5030..0c5de3c4d16 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.ts
@@ -214,6 +214,19 @@ const fromActionInput = ({
stepFilters: toArray(record.stepFilters).map(resolvers.fieldReference),
};
}
+ case WorkflowActionType.SEND_EMAIL:
+ case WorkflowActionType.DRAFT_EMAIL:
+ case WorkflowActionType.CREATE_CALENDAR_EVENT: {
+ const { connectedAccountId, ...rest } = toRecord(input);
+
+ return {
+ ...rest,
+ ...resolvers.connectedAccountReference({
+ stepType: action.type,
+ connectedAccountId,
+ }),
+ };
+ }
case WorkflowActionType.HTTP_REQUEST:
case WorkflowActionType.CLASSIFY:
case WorkflowActionType.ITERATOR:
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
index fab7044442e..2221fac92f9 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
@@ -22,11 +22,16 @@ export const fromWorkflowStepManifestToActionOrThrow = ({
index: number;
references: WorkflowManifestReferences;
}): WorkflowAction => {
- const { resolve, objectName, field, fieldReference } =
- buildWorkflowManifestReferenceResolvers({
- references,
- subject: `Workflow step ${step.name}`,
- });
+ const {
+ resolve,
+ objectName,
+ field,
+ fieldReference,
+ connectedAccountIdOrThrow,
+ } = buildWorkflowManifestReferenceResolvers({
+ references,
+ subject: `Workflow step ${step.name}`,
+ });
let input: unknown;
switch (step.type) {
case 'LOGIC_FUNCTION':
@@ -194,6 +199,21 @@ export const fromWorkflowStepManifestToActionOrThrow = ({
),
};
break;
+ case 'SEND_EMAIL':
+ case 'DRAFT_EMAIL':
+ case 'CREATE_CALENDAR_EVENT': {
+ const { connectedAccountHandle, ...rest } = step.input;
+ input = isDefined(connectedAccountHandle)
+ ? {
+ ...rest,
+ connectedAccountId: connectedAccountIdOrThrow({
+ stepType: step.type,
+ handle: connectedAccountHandle,
+ }),
+ }
+ : rest;
+ break;
+ }
default:
input = step.input;
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts
index c8224ab20e0..f1c27584fcd 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts
@@ -26,6 +26,7 @@ import {
} from 'src/engine/core-modules/application/application.exception';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { findActiveFlatApplicationByUniversalIdentifier } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-universal-identifier.util';
+import { ConnectedAccountMetadataService } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.service';
import { getMetadataFlatEntityMapsKey } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-flat-entity-maps-key.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { STANDARD_ROLE } from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-role.constant';
@@ -49,6 +50,7 @@ export class ApplicationManifestExportService {
private readonly applicationTranslationCacheService: ApplicationTranslationCacheService,
private readonly applicationRegistrationLookupService: ApplicationRegistrationLookupService,
private readonly applicationService: ApplicationService,
+ private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,
) {}
async exportApplication({
@@ -153,6 +155,10 @@ export class ApplicationManifestExportService {
await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
{ workspaceId },
);
+ const connectedAccounts =
+ await this.connectedAccountMetadataService.findAllForWorkflowStepResolution(
+ { workspaceId },
+ );
const { workflows, coverage: workflowsCoverage } =
reconstructWorkflowsManifest({
applicationAllFlatEntityMaps,
@@ -161,6 +167,7 @@ export class ApplicationManifestExportService {
resolvableFieldUniversalIdentifiers,
isWorkspaceCustomApplication:
flatApplication.id === workspaceCustomFlatApplication.id,
+ connectedAccounts,
});
const { agents, coverage: agentsCoverage } = reconstructAgentsManifest({
applicationAllFlatEntityMaps,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/workflow-connected-account-step-type.type.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/workflow-connected-account-step-type.type.ts
new file mode 100644
index 00000000000..fc753c9c9fd
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/workflow-connected-account-step-type.type.ts
@@ -0,0 +1,4 @@
+export type WorkflowConnectedAccountStepType =
+ | 'SEND_EMAIL'
+ | 'DRAFT_EMAIL'
+ | 'CREATE_CALENDAR_EVENT';
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type.ts
index b5d82a160fe..d0939f29339 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type.ts
@@ -1,4 +1,6 @@
import { type BaseOutputSchemaV2 } from 'twenty-shared/workflow';
+import { type CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
+import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
@@ -25,6 +27,17 @@ export type WorkflowManifestFieldReference = {
> &
Partial<Pick<FlatFieldMetadata, 'universalSettings'>>;
+export type WorkflowManifestConnectedAccountReference = Pick<
+ ConnectedAccountEntity,
+ | 'id'
+ | 'handle'
+ | 'provider'
+ | 'connectionParameters'
+ | 'archivedAt'
+ | 'scopes'
+ | 'scope'
+> & { calendarChannels: Pick<CalendarChannelEntity, 'isSyncEnabled'>[] };
+
export type WorkflowManifestReferences = {
logicFunctionOutputSchemaByUniversalIdentifier?: ReadonlyMap<
string,
@@ -44,4 +57,6 @@ export type WorkflowManifestReferences = {
string,
WorkflowManifestFieldReference
>;
+ // Oldest first, which decides between accounts sharing a handle
+ connectedAccounts?: readonly WorkflowManifestConnectedAccountReference[];
};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/add-workflow-manifests-to-flat-entity-maps-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/add-workflow-manifests-to-flat-entity-maps-or-throw.util.spec.ts
index 11c9d1265cd..38d793e4c48 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/add-workflow-manifests-to-flat-entity-maps-or-throw.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/add-workflow-manifests-to-flat-entity-maps-or-throw.util.spec.ts
@@ -66,6 +66,7 @@ const compute = ({
existingAllFlatEntityMaps: fromAllFlatEntityMaps,
idByUniversalIdentifierByMetadataName: {},
isWorkspaceCustomApplication,
+ connectedAccounts: [],
now: '2026-09-28T00:00:00.000Z',
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts
index 8128b936a8f..354c52b056f 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts
@@ -254,6 +254,7 @@ const reconstruct = ({
exportedObjectUniversalIdentifiers: new Set([TICKET_UID]),
resolvableFieldUniversalIdentifiers: new Set(),
isWorkspaceCustomApplication,
+ connectedAccounts: [],
});
describe('reconstructWorkflowsManifest', () => {
@@ -417,6 +418,7 @@ describe('reconstructWorkflowsManifest', () => {
exportedObjectUniversalIdentifiers: new Set([TICKET_UID]),
resolvableFieldUniversalIdentifiers: new Set(),
isWorkspaceCustomApplication: false,
+ connectedAccounts: [],
}).coverage,
).toEqual([
{
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts
index e1e78af1813..034b597d661 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts
@@ -7,6 +7,7 @@ import {
import { isDefined } from 'twenty-shared/utils';
import { fromWorkflowManifestToUniversalFlatWorkflowOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util';
+import { type WorkflowManifestConnectedAccountReference } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
import { findActiveFlatWorkflowVersionByWorkflowId } from 'src/engine/core-modules/application/application-manifest/utils/find-active-flat-workflow-version-by-workflow-id.util';
import { prepareWorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/utils/prepare-workflow-manifest-references.util';
import { validateWorkflowManifestRecordFields } from 'src/engine/core-modules/application/application-manifest/utils/validate-workflow-manifest-record-fields.util';
@@ -53,6 +54,7 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
existingAllFlatEntityMaps,
idByUniversalIdentifierByMetadataName,
isWorkspaceCustomApplication,
+ connectedAccounts,
now,
}: {
workflows: WorkflowManifest[];
@@ -62,6 +64,7 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
existingAllFlatEntityMaps: AllFlatEntityMaps;
idByUniversalIdentifierByMetadataName: IdByUniversalIdentifierByMetadataName;
isWorkspaceCustomApplication: boolean;
+ connectedAccounts: readonly WorkflowManifestConnectedAccountReference[];
now: string;
}): (UniversalFlatWorkflow & { id: string })[] => {
const applicationUniversalIdentifier =
@@ -69,15 +72,18 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
const applicationWorkflows: (UniversalFlatWorkflow & { id: string })[] = [];
if (workflows.length > 0) {
- const references = prepareWorkflowManifestReferences({
- toAllUniversalFlatEntityMaps,
- existingAllFlatEntityMaps,
- ownerApplicationId: ownerFlatApplication.id,
- idByUniversalIdentifierByMetadataName,
- // Its workflows run as workspace workflows, which may already call any app's actions
- canReferenceOtherApplicationsWorkflowActions:
- isWorkspaceCustomApplication,
- });
+ const references = {
+ ...prepareWorkflowManifestReferences({
+ toAllUniversalFlatEntityMaps,
+ existingAllFlatEntityMaps,
+ ownerApplicationId: ownerFlatApplication.id,
+ idByUniversalIdentifierByMetadataName,
+ // Its workflows run as workspace workflows, which may already call any app's actions
+ canReferenceOtherApplicationsWorkflowActions:
+ isWorkspaceCustomApplication,
+ }),
+ connectedAccounts,
+ };
const activeVersionByWorkflowId = isWorkspaceCustomApplication
? findActiveFlatWorkflowVersionByWorkflowId(
fromAllFlatEntityMaps.flatWorkflowVersionMaps,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.ts
index 7822855ab95..7b939e9fa93 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.ts
@@ -1,6 +1,9 @@
import { isDefined, isPlainObject } from 'twenty-shared/utils';
import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import { WORKFLOW_CONNECTED_ACCOUNT_STEP_CAPABILITY } from 'src/engine/core-modules/application/application-manifest/constants/workflow-connected-account-step-capability.constant';
+import { type WorkflowConnectedAccountStepType } from 'src/engine/core-modules/application/application-manifest/types/workflow-connected-account-step-type.type';
+import { findWorkflowStepConnectedAccount } from 'src/engine/core-modules/application/application-manifest/utils/find-workflow-step-connected-account.util';
import { computeWorkflowWatchedFieldName } from 'src/engine/core-modules/application/application-manifest/utils/compute-workflow-watched-field-name.util';
const UNRESOLVED_REFERENCE = '';
@@ -38,6 +41,14 @@ export const buildWorkflowManifestInverseReferenceResolvers = (
references.agentIdByUniversalIdentifier,
);
+ const connectedAccounts = references.connectedAccounts ?? [];
+ const connectedAccountById = new Map(
+ connectedAccounts.map((connectedAccount) => [
+ connectedAccount.id,
+ connectedAccount,
+ ]),
+ );
+
for (const [
universalIdentifier,
object,
@@ -157,6 +168,52 @@ export const buildWorkflowManifestInverseReferenceResolvers = (
reason: 'workflow step on an agent of another application',
});
+ // Values that are not a shared account of the workspace (variables, member ids, private accounts) are kept as they are
+ const connectedAccountReference = ({
+ stepType,
+ connectedAccountId,
+ }: {
+ stepType: WorkflowConnectedAccountStepType;
+ connectedAccountId: unknown;
+ }): { connectedAccountId: unknown } | { connectedAccountHandle: string } => {
+ const connectedAccount =
+ typeof connectedAccountId === 'string'
+ ? connectedAccountById.get(connectedAccountId)
+ : undefined;
+
+ if (
+ !isDefined(connectedAccount) ||
+ connectedAccount.scope !== 'WORKSPACE'
+ ) {
+ return { connectedAccountId };
+ }
+
+ const { handle } = connectedAccount;
+ const resolvedConnectedAccount = findWorkflowStepConnectedAccount({
+ stepType,
+ handle,
+ connectedAccounts,
+ });
+
+ if (resolvedConnectedAccount?.id === connectedAccount.id) {
+ return { connectedAccountHandle: handle };
+ }
+
+ if (isDefined(connectedAccount.archivedAt)) {
+ markUnsupported(`workflow step on archived connected account ${handle}`);
+ } else if (isDefined(resolvedConnectedAccount)) {
+ markUnsupported(
+ `workflow step on connected account ${handle}, whose handle names an older account of the workspace`,
+ );
+ } else {
+ markUnsupported(
+ `workflow step on connected account ${handle}, which cannot ${WORKFLOW_CONNECTED_ACCOUNT_STEP_CAPABILITY[stepType]}`,
+ );
+ }
+
+ return { connectedAccountHandle: UNRESOLVED_REFERENCE };
+ };
+
const fieldReference = (
reference: unknown,
): Record<string, unknown> | undefined => {
@@ -183,6 +240,7 @@ export const buildWorkflowManifestInverseReferenceResolvers = (
watchedFieldUniversalIdentifier,
logicFunctionUniversalIdentifier,
agentUniversalIdentifier,
+ connectedAccountReference,
markUnsupported,
getUnsupportedReason: (): string | undefined => unsupportedReasons[0],
};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-reference-resolvers.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-reference-resolvers.util.ts
index 3be7aec4b5d..65dd1b55d72 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-reference-resolvers.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-reference-resolvers.util.ts
@@ -2,6 +2,9 @@ import { msg } from '@lingui/core/macro';
import { isDefined } from 'twenty-shared/utils';
import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import { WORKFLOW_CONNECTED_ACCOUNT_STEP_CAPABILITY } from 'src/engine/core-modules/application/application-manifest/constants/workflow-connected-account-step-capability.constant';
+import { type WorkflowConnectedAccountStepType } from 'src/engine/core-modules/application/application-manifest/types/workflow-connected-account-step-type.type';
+import { findWorkflowStepConnectedAccount } from 'src/engine/core-modules/application/application-manifest/utils/find-workflow-step-connected-account.util';
import {
ApplicationException,
ApplicationExceptionCode,
@@ -74,5 +77,35 @@ export const buildWorkflowManifestReferenceResolvers = ({
};
};
- return { resolve, objectName, field, fieldReference };
+ const connectedAccountIdOrThrow = ({
+ stepType,
+ handle,
+ }: {
+ stepType: WorkflowConnectedAccountStepType;
+ handle: string;
+ }) => {
+ const connectedAccount = findWorkflowStepConnectedAccount({
+ stepType,
+ handle,
+ connectedAccounts: references.connectedAccounts ?? [],
+ });
+ if (!isDefined(connectedAccount)) {
+ throw new ApplicationException(
+ `${subject}: no connected account ${handle} shared with this workspace can ${WORKFLOW_CONNECTED_ACCOUNT_STEP_CAPABILITY[stepType]}`,
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`The workflow uses connected account ${handle}, which is not connected and shared in this workspace.`,
+ },
+ );
+ }
+ return connectedAccount.id;
+ };
+
+ return {
+ resolve,
+ objectName,
+ field,
+ fieldReference,
+ connectedAccountIdOrThrow,
+ };
};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/find-workflow-step-connected-account.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/find-workflow-step-connected-account.util.ts
new file mode 100644
index 00000000000..c56f6d397c0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/find-workflow-step-connected-account.util.ts
@@ -0,0 +1,51 @@
+import { EmailOperation } from 'twenty-shared/types';
+import {
+ canConnectedAccountPerformEmailOperation,
+ isDefined,
+} from 'twenty-shared/utils';
+
+import { type WorkflowConnectedAccountStepType } from 'src/engine/core-modules/application/application-manifest/types/workflow-connected-account-step-type.type';
+import { type WorkflowManifestConnectedAccountReference } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import { canConnectedAccountCreateCalendarEvents } from 'src/modules/calendar/calendar-event-creation-manager/utils/can-connected-account-create-calendar-events.util';
+
+const canConnectedAccountRunStep = ({
+ stepType,
+ connectedAccount,
+}: {
+ stepType: WorkflowConnectedAccountStepType;
+ connectedAccount: WorkflowManifestConnectedAccountReference;
+}): boolean => {
+ switch (stepType) {
+ case 'SEND_EMAIL':
+ return canConnectedAccountPerformEmailOperation({
+ connectedAccount,
+ operation: EmailOperation.SEND,
+ });
+ case 'DRAFT_EMAIL':
+ return canConnectedAccountPerformEmailOperation({
+ connectedAccount,
+ operation: EmailOperation.DRAFT,
+ });
+ case 'CREATE_CALENDAR_EVENT':
+ return canConnectedAccountCreateCalendarEvents(connectedAccount);
+ }
+};
+
+// Members can connect the same mailbox, or one address through two providers: the oldest account able to run the step wins
+export const findWorkflowStepConnectedAccount = ({
+ stepType,
+ handle,
+ connectedAccounts,
+}: {
+ stepType: WorkflowConnectedAccountStepType;
+ handle: string;
+ connectedAccounts: readonly WorkflowManifestConnectedAccountReference[];
+}): WorkflowManifestConnectedAccountReference | undefined =>
+ connectedAccounts.find(
+ (connectedAccount) =>
+ // Sync acts for no member, so a handle can only name an account shared with the workspace
+ connectedAccount.scope === 'WORKSPACE' &&
+ !isDefined(connectedAccount.archivedAt) &&
+ connectedAccount.handle.toLowerCase() === handle.toLowerCase() &&
+ canConnectedAccountRunStep({ stepType, connectedAccount }),
+ );
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util.ts
index 5e8745831e4..e20188318e2 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util.ts
@@ -8,6 +8,7 @@ import { isDefined } from 'twenty-shared/utils';
import { WORKFLOW_CHANGED_IN_BUILDER_REASON } from 'src/engine/core-modules/application/application-manifest/constants/workflow-changed-in-builder-reason.constant';
import { fromFlatWorkflowToWorkflowManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util';
import { type ApplicationExportCoverageEntry } from 'src/engine/core-modules/application/application-manifest/types/application-export.type';
+import { type WorkflowManifestConnectedAccountReference } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
import { buildExportedCoverageEntry } from 'src/engine/core-modules/application/application-manifest/utils/build-exported-coverage-entry.util';
import { buildWorkflowManifestExportReferences } from 'src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-export-references.util';
import { sortFlatEntitiesByUniversalIdentifier } from 'src/engine/core-modules/application/application-manifest/utils/sort-flat-entities-by-universal-identifier.util';
@@ -88,25 +89,31 @@ export const reconstructWorkflowsManifest = ({
exportedObjectUniversalIdentifiers,
resolvableFieldUniversalIdentifiers,
isWorkspaceCustomApplication,
+ connectedAccounts,
}: {
applicationAllFlatEntityMaps: AllFlatEntityMaps;
allFlatEntityMaps: AllFlatEntityMaps;
exportedObjectUniversalIdentifiers: ReadonlySet<string>;
resolvableFieldUniversalIdentifiers: ReadonlySet<string>;
isWorkspaceCustomApplication: boolean;
+ connectedAccounts: readonly WorkflowManifestConnectedAccountReference[];
}): {
workflows: WorkflowManifest[];
coverage: ApplicationExportCoverageEntry[];
} => {
const workflows: WorkflowManifest[] = [];
const coverage: ApplicationExportCoverageEntry[] = [];
- const references = buildWorkflowManifestExportReferences({
- applicationAllFlatEntityMaps,
- allFlatEntityMaps,
- exportedObjectUniversalIdentifiers,
- resolvableFieldUniversalIdentifiers,
- canReferenceOtherApplicationsWorkflowActions: isWorkspaceCustomApplication,
- });
+ const references = {
+ ...buildWorkflowManifestExportReferences({
+ applicationAllFlatEntityMaps,
+ allFlatEntityMaps,
+ exportedObjectUniversalIdentifiers,
+ resolvableFieldUniversalIdentifiers,
+ canReferenceOtherApplicationsWorkflowActions:
+ isWorkspaceCustomApplication,
+ }),
+ connectedAccounts,
+ };
const getExclusionReason = (flatWorkflow: FlatWorkflow) => {
if (flatWorkflow.isSystem) {
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts
index 0c98ccc8be8..2e5f79d6c95 100644
--- a/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/connected-account-metadata.service.ts
@@ -313,6 +313,41 @@ export class ConnectedAccountMetadataService {
return connectedAccount;
}
+ async findAllForWorkflowStepResolution({
+ workspaceId,
+ }: {
+ workspaceId: string;
+ }): Promise<
+ (Pick<
+ ConnectedAccountEntity,
+ | 'id'
+ | 'handle'
+ | 'provider'
+ | 'connectionParameters'
+ | 'archivedAt'
+ | 'scopes'
+ | 'scope'
+ > & {
+ calendarChannels: Pick<CalendarChannelEntity, 'isSyncEnabled'>[];
+ })[]
+ > {
+ return this.repository.find({
+ where: { workspaceId },
+ relations: { calendarChannels: true },
+ select: {
+ id: true,
+ handle: true,
+ provider: true,
+ connectionParameters: true,
+ archivedAt: true,
+ scopes: true,
+ scope: true,
+ calendarChannels: { id: true, isSyncEnabled: true },
+ },
+ order: { createdAt: 'ASC', id: 'ASC' },
+ });
+ }
+
async getUserConnectedAccountIds({
userWorkspaceId,
workspaceId,
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/utils/can-connected-account-create-calendar-events.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/utils/can-connected-account-create-calendar-events.util.ts
new file mode 100644
index 00000000000..61998b705b3
--- /dev/null
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/utils/can-connected-account-create-calendar-events.util.ts
@@ -0,0 +1,16 @@
+import { type CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
+import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { getMissingCreateEventScopes } from 'src/modules/calendar/calendar-event-creation-manager/utils/get-missing-create-event-scopes.util';
+import { isCalendarCreationSupportedProvider } from 'src/modules/calendar/calendar-event-creation-manager/utils/is-calendar-creation-supported-provider.util';
+
+// Mirrors CalendarEventComposerService: created events are reconciled by the provider sync, which skips channels whose sync is disabled
+export const canConnectedAccountCreateCalendarEvents = (
+ connectedAccount: Pick<ConnectedAccountEntity, 'provider' | 'scopes'> & {
+ calendarChannels: Pick<CalendarChannelEntity, 'isSyncEnabled'>[];
+ },
+): boolean =>
+ isCalendarCreationSupportedProvider(connectedAccount.provider) &&
+ getMissingCreateEventScopes(connectedAccount).length === 0 &&
+ connectedAccount.calendarChannels.some(
+ (calendarChannel) => calendarChannel.isSyncEnabled,
+ );
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts
index 366d069cd30..36d713be2c7 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts
@@ -96,6 +96,7 @@ import { ApplicationExportCoverageStatus } from 'src/engine/core-modules/applica
import { fromObjectManifestToUniversalFlatObjectMetadata } from 'src/engine/core-modules/application/application-manifest/converters/from-object-manifest-to-universal-flat-object-metadata.util';
import { buildSearchVectorFlatFieldMetadataForCustomObject } from 'src/engine/metadata-modules/object-metadata/utils/build-search-vector-flat-field-metadata-for-custom-object.util';
import { buildSearchVectorGinIndexForCustomObject } from 'src/engine/metadata-modules/object-metadata/utils/build-search-vector-gin-index-for-custom-object.util';
+import { type ConnectedAccountScope } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
const TEST_APP_ID = '7e3d1c2b-0000-4a7b-8c9d-0e1f2a3b4c5d';
const TEST_ROLE_ID = '7e3d1c2b-0001-4a7b-8c9d-0e1f2a3b4c5d';
@@ -1528,6 +1529,8 @@ const ESCALATION_WORKFLOW_ID = '7e3d1c2b-0110-4a7b-8c9d-0e1f2a3b4c5d';
const NOTIFY_WORKFLOW_ID = '7e3d1c2b-0111-4a7b-8c9d-0e1f2a3b4c5d';
const NIGHTLY_WORKFLOW_ID = '7e3d1c2b-0112-4a7b-8c9d-0e1f2a3b4c5d';
const INTAKE_WORKFLOW_ID = '7e3d1c2b-0113-4a7b-8c9d-0e1f2a3b4c5d';
+const OUTREACH_WORKFLOW_ID = '7e3d1c2b-0114-4a7b-8c9d-0e1f2a3b4c5d';
+const SEEDED_CONNECTED_ACCOUNT_HANDLE = '[email protected]';
const workflowNodeIdentifier = (suffix: number) =>
`7e3d1c2b-${(200 + suffix).toString().padStart(4, '0')}-4a7b-8c9d-0e1f2a3b4c5d`;
@@ -1724,8 +1727,76 @@ const EXPORTED_WORKFLOWS: WorkflowManifest[] = [
],
},
},
+ {
+ universalIdentifier: OUTREACH_WORKFLOW_ID,
+ name: 'Reach out to the incident reporter',
+ version: {
+ trigger: {
+ universalIdentifier: workflowNodeIdentifier(40),
+ type: 'MANUAL',
+ nextStepIds: [workflowNodeIdentifier(41)],
+ },
+ steps: [
+ {
+ universalIdentifier: workflowNodeIdentifier(41),
+ name: 'Email the reporter',
+ type: 'SEND_EMAIL',
+ nextStepIds: [workflowNodeIdentifier(42)],
+ input: {
+ connectedAccountHandle: SEEDED_CONNECTED_ACCOUNT_HANDLE,
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ subject: 'We are on it',
+ files: [],
+ },
+ },
+ {
+ universalIdentifier: workflowNodeIdentifier(42),
+ name: 'Book a review',
+ type: 'CREATE_CALENDAR_EVENT',
+ nextStepIds: [],
+ input: {
+ connectedAccountId: '{{trigger.connectedAccountId}}',
+ title: 'Incident review',
+ startsAt: '2026-11-02T09:00:00.000Z',
+ endsAt: '2026-11-02T09:30:00.000Z',
+ isFullDay: false,
+ attendees: '',
+ sendInvitations: false,
+ addConferencing: false,
+ },
+ },
+ ],
+ },
+ },
];
+const withSendEmailConnectedAccountHandle = ({
+ workflow,
+ connectedAccountHandle,
+}: {
+ workflow: WorkflowManifest;
+ connectedAccountHandle: string;
+}): WorkflowManifest => ({
+ ...workflow,
+ version: {
+ ...workflow.version,
+ steps: workflow.version.steps.map((step) => {
+ if (step.type !== 'SEND_EMAIL') {
+ return step;
+ }
+
+ return { ...step, input: { ...step.input, connectedAccountHandle } };
+ }),
+ },
+});
+
+const setSeededConnectedAccountScope = (scope: ConnectedAccountScope) =>
+ globalThis.testDataSource.query(
+ `UPDATE core."connectedAccount" SET scope = $1
+ WHERE handle = $2 AND "workspaceId" = $3`,
+ [scope, SEEDED_CONNECTED_ACCOUNT_HANDLE, SEED_APPLE_WORKSPACE_ID],
+ );
+
const workflowsManifest = buildBaseManifest({
appId: WORKFLOW_TEST_APP_ID,
roleId: WORKFLOW_TEST_ROLE_ID,
@@ -1753,7 +1824,19 @@ const workflowsManifest = buildBaseManifest({
});
describe('Application export - workflows', () => {
+ let seededConnectedAccountScope: ConnectedAccountScope;
+
beforeAll(async () => {
+ const [seededConnectedAccount] = await globalThis.testDataSource.query(
+ `SELECT scope FROM core."connectedAccount"
+ WHERE handle = $1 AND "workspaceId" = $2`,
+ [SEEDED_CONNECTED_ACCOUNT_HANDLE, SEED_APPLE_WORKSPACE_ID],
+ );
+
+ seededConnectedAccountScope = seededConnectedAccount.scope;
+ // A handle only names an account shared with the workspace; the seed connects it for Tim alone
+ await setSeededConnectedAccountScope('WORKSPACE');
+
await cleanupApplicationAndAppRegistration({
applicationUniversalIdentifier: WORKFLOW_TEST_APP_ID,
});
@@ -1774,6 +1857,7 @@ describe('Application export - workflows', () => {
await cleanupApplicationAndAppRegistration({
applicationUniversalIdentifier: WORKFLOW_TEST_APP_ID,
});
+ await setSeededConnectedAccountScope(seededConnectedAccountScope);
});
it('exports the synced workflows as they were declared', async () => {
@@ -1836,6 +1920,43 @@ describe('Application export - workflows', () => {
expect(dryRun.errors).toBeUndefined();
expect(dryRun.data.syncApplication.actions).toEqual([]);
}, 60000);
+
+ it('refuses a step whose connected account handle is not connected in the workspace', async () => {
+ const unknownHandle = '[email protected]';
+ const { errors } = await syncApplication({
+ manifest: {
+ ...workflowsManifest,
+ workflows: EXPORTED_WORKFLOWS.map((workflow) =>
+ workflow.universalIdentifier === OUTREACH_WORKFLOW_ID
+ ? withSendEmailConnectedAccountHandle({
+ workflow,
+ connectedAccountHandle: unknownHandle,
+ })
+ : workflow,
+ ),
+ },
+ dryRun: true,
+ expectToFail: true,
+ });
+
+ expect(errors?.[0]?.message).toContain(unknownHandle);
+ }, 60000);
+
+ it('refuses a step whose connected account handle names an account private to a member', async () => {
+ await setSeededConnectedAccountScope('USER');
+
+ try {
+ const { errors } = await syncApplication({
+ manifest: workflowsManifest,
+ dryRun: true,
+ expectToFail: true,
+ });
+
+ expect(errors?.[0]?.message).toContain(SEEDED_CONNECTED_ACCOUNT_HANDLE);
+ } finally {
+ await setSeededConnectedAccountScope('WORKSPACE');
+ }
+ }, 60000);
});
const findWorkspaceCustomFlatApplication = async () =>
diff --git a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
index dd7eed77dcb..96c861def47 100644
--- a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
+++ b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
@@ -160,6 +160,76 @@ describe('workflow manifest step types', () => {
expect(workflowManifestSchema.safeParse(definition).success).toBe(true);
});
+ describe('connected account reference', () => {
+ const CALENDAR_EVENT = {
+ title: 'Kick-off',
+ startsAt: '2026-11-02T09:00:00.000Z',
+ endsAt: '2026-11-02T09:30:00.000Z',
+ isFullDay: false,
+ sendInvitations: true,
+ addConferencing: false,
+ };
+ const withStep = ({
+ type,
+ input,
+ }: {
+ type: string;
+ input: Record<string, unknown>;
+ }) => {
+ const definition = structuredClone(workflow);
+ Object.assign(getStep(definition, 2), { type, input });
+ return workflowManifestSchema.safeParse(definition);
+ };
+
+ it.each([
+ { type: 'SEND_EMAIL', input: { recipients: { to: '[email protected]' } } },
+ {
+ type: 'DRAFT_EMAIL',
+ input: { recipients: { to: '[email protected]' } },
+ },
+ { type: 'CREATE_CALENDAR_EVENT', input: CALENDAR_EVENT },
+ ])(
+ 'accepts a $type step naming its account by handle',
+ ({ type, input }) => {
+ const result = withStep({
+ type,
+ input: { ...input, connectedAccountHandle: ' [email protected] ' },
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.data?.version.steps[2]?.input).toMatchObject({
+ connectedAccountHandle: '[email protected]',
+ });
+ },
+ );
+
+ it.each([
+ {
+ case: 'both',
+ reference: {
+ connectedAccountId: ASSIGNEE,
+ connectedAccountHandle: '[email protected]',
+ },
+ },
+ { case: 'neither', reference: {} },
+ { case: 'an empty handle', reference: { connectedAccountHandle: ' ' } },
+ ])('rejects $case of the account id and handle', ({ reference }) => {
+ const result = withStep({
+ type: 'CREATE_CALENDAR_EVENT',
+ input: { ...CALENDAR_EVENT, ...reference },
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error?.issues[0]?.path).toEqual([
+ 'version',
+ 'steps',
+ 2,
+ 'input',
+ 'connectedAccountHandle',
+ ]);
+ });
+ });
+
it('rejects a step type applications cannot use', () => {
const invalid = structuredClone(workflow);
Object.assign(getStep(invalid, 2), { type: 'CODE' });
diff --git a/packages/twenty-shared/src/application/workflowStepManifestType.ts b/packages/twenty-shared/src/application/workflowStepManifestType.ts
index baa475efc32..80a0a1327ac 100644
--- a/packages/twenty-shared/src/application/workflowStepManifestType.ts
+++ b/packages/twenty-shared/src/application/workflowStepManifestType.ts
@@ -59,6 +59,34 @@ const recordFilterManifestSchema = recordFilterSchema
const recordObjectShape = { objectUniversalIdentifier: z.uuid() };
+// Connected account ids are local to a workspace; sync resolves a handle to one
+const connectedAccountReferenceShape = {
+ connectedAccountId: z.string().optional(),
+ connectedAccountHandle: z.string().trim().min(1).optional(),
+};
+
+const refineConnectedAccountReference = (
+ input: z.infer<z.ZodObject<typeof connectedAccountReferenceShape>>,
+ context: z.RefinementCtx,
+) => {
+ if (
+ isDefined(input.connectedAccountId) ===
+ isDefined(input.connectedAccountHandle)
+ ) {
+ context.addIssue({
+ code: 'custom',
+ path: ['connectedAccountHandle'],
+ message:
+ 'Set exactly one of connectedAccountId and connectedAccountHandle',
+ });
+ }
+};
+
+const emailStepInputManifestSchema =
+ workflowSendEmailActionSettingsSchema.shape.input
+ .extend(connectedAccountReferenceShape)
+ .superRefine(refineConnectedAccountReference);
+
const workflowStepManifestOptions = [
z.strictObject({
...baseStepShape,
@@ -207,11 +235,13 @@ const workflowStepManifestOptions = [
}),
),
),
- stepSchema('SEND_EMAIL', workflowSendEmailActionSettingsSchema.shape.input),
- stepSchema('DRAFT_EMAIL', workflowSendEmailActionSettingsSchema.shape.input),
+ stepSchema('SEND_EMAIL', emailStepInputManifestSchema),
+ stepSchema('DRAFT_EMAIL', emailStepInputManifestSchema),
stepSchema(
'CREATE_CALENDAR_EVENT',
- workflowCreateCalendarEventActionSettingsSchema.shape.input,
+ workflowCreateCalendarEventActionSettingsSchema.shape.input
+ .extend(connectedAccountReferenceShape)
+ .superRefine(refineConnectedAccountReference),
),
stepSchema(
'AI_AGENT',