The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(workflow): stop email steps sending from another member's account (#25709)
Abdellatif Anaflousb453166a78f1
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.tsindex 7023c2cd5d9..1bcddeff7a6 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/draft-email.workflow-action.spec.ts@@ -6,6 +6,7 @@ import { DraftEmailTool } from 'src/engine/core-modules/tool/tools/email-tool/drimport { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';+import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';import { DraftEmailWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action';import { type WorkflowActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';@@ -63,6 +64,14 @@ describe('DraftEmailWorkflowAction', () => {provide: WorkflowRunStepLogWorkspaceService,useValue: { setStepLog: mockSetStepLog },},+ {+ provide: WorkflowExecutionContextService,+ useValue: {+ getExecutionContext: jest+ .fn()+ .mockResolvedValue({ authContext: { type: 'application' } }),+ },+ },{provide: WorkspaceOrmManager,useValue: {diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.tsindex c88c557c372..3b76df5373c 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/__tests__/send-email.workflow-action.spec.ts@@ -6,6 +6,7 @@ import { SendEmailTool } from 'src/engine/core-modules/tool/tools/email-tool/senimport { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';+import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';import { SendEmailWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action';import { type WorkflowActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';@@ -67,6 +68,14 @@ describe('SendEmailWorkflowAction', () => {provide: WorkflowRunStepLogWorkspaceService,useValue: { setStepLog: jest.fn() },},+ {+ provide: WorkflowExecutionContextService,+ useValue: {+ getExecutionContext: jest+ .fn()+ .mockResolvedValue({ authContext: { type: 'application' } }),+ },+ },{provide: WorkspaceOrmManager,useValue: {diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action.tsindex 583b1c8385d..adc0c40ff5c 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action.ts@@ -12,6 +12,7 @@ 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 { EmailWorkflowActionBase } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base';import { isWorkflowDraftEmailAction } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/guards/is-workflow-draft-email-action.guard';import { type EmailStepLogMode } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util';@@ -28,6 +29,7 @@ export class DraftEmailWorkflowAction extends EmailWorkflowActionBase {connectedAccountRepository: Repository<ConnectedAccountEntity>,@InjectRepository(UserWorkspaceEntity)userWorkspaceRepository: Repository<UserWorkspaceEntity>,+ workflowExecutionContextService: WorkflowExecutionContextService,) {super(DraftEmailWorkflowAction.name,@@ -35,6 +37,7 @@ export class DraftEmailWorkflowAction extends EmailWorkflowActionBase {workspaceOrmManager,connectedAccountRepository,userWorkspaceRepository,+ workflowExecutionContextService,);}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.tsindex a40321d33c3..bb80cb73afa 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts@@ -7,6 +7,7 @@ import {} from 'twenty-shared/utils';import { IsNull, type Repository } from 'typeorm';+import { type ToolExecutionContext } from 'src/engine/core-modules/tool/types/tool-execution-context.type';import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';import { type UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';@@ -16,6 +17,9 @@ 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 { type WorkflowRunInfo } from 'src/modules/workflow/workflow-executor/types/workflow-action-input';+import { getUserFromAuthContext } from 'src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util';import { type WorkflowSendEmailActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/types/workflow-send-email-action-input.type';import {buildEmailStepLog,@@ -34,6 +38,7 @@ export abstract class EmailWorkflowActionBase extends ToolBackedWorkflowAction<Wprivate readonly workspaceOrmManager: WorkspaceOrmManager,private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,+ private readonly workflowExecutionContextService: WorkflowExecutionContextService,) {super(loggerName, workflowRunStepLogService);}@@ -68,6 +73,18 @@ export abstract class EmailWorkflowActionBase extends ToolBackedWorkflowAction<W};}+ protected override async buildToolExecutionContext(+ runInfo: WorkflowRunInfo,+ ): Promise<ToolExecutionContext> {+ const { authContext } =+ await this.workflowExecutionContextService.getExecutionContext(runInfo);++ return {+ workspaceId: runInfo.workspaceId,+ ...getUserFromAuthContext(authContext),+ };+ }+protected override async postprocessInput(resolvedInput: WorkflowSendEmailActionInput,workspaceId: string,diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/mail-sender-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/mail-sender-action.module.tsindex a2b0ef2bd80..78bd4fbb592 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/mail-sender-action.module.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/mail-sender-action.module.ts@@ -1,20 +1,33 @@import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';+import { ApplicationModule } from 'src/engine/core-modules/application/application.module';import { ToolModule } from 'src/engine/core-modules/tool/tool.module';import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';+import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';+import { RoleModule } from 'src/engine/metadata-modules/role/role.module';+import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';+import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';import { DraftEmailWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action';import { SendEmailWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action';import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';@Module({imports: [+ ApplicationModule,+ RoleModule,ToolModule,+ UserRoleModule,+ UserWorkspaceModule,WorkflowRunModule,TypeOrmModule.forFeature([ConnectedAccountEntity, UserWorkspaceEntity]),],- providers: [SendEmailWorkflowAction, DraftEmailWorkflowAction],+ providers: [+ WorkflowExecutionContextService,+ SendEmailWorkflowAction,+ DraftEmailWorkflowAction,+ ],exports: [SendEmailWorkflowAction, DraftEmailWorkflowAction],})export class MailSenderActionModule {}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action.tsindex 928391ebfe0..f48199ec29e 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action.ts@@ -12,6 +12,7 @@ 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 { EmailWorkflowActionBase } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base';import { isWorkflowSendEmailAction } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/guards/is-workflow-send-email-action.guard';import { type EmailStepLogMode } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/utils/build-email-step-log.util';@@ -28,6 +29,7 @@ export class SendEmailWorkflowAction extends EmailWorkflowActionBase {connectedAccountRepository: Repository<ConnectedAccountEntity>,@InjectRepository(UserWorkspaceEntity)userWorkspaceRepository: Repository<UserWorkspaceEntity>,+ workflowExecutionContextService: WorkflowExecutionContextService,) {super(SendEmailWorkflowAction.name,@@ -35,6 +37,7 @@ export class SendEmailWorkflowAction extends EmailWorkflowActionBase {workspaceOrmManager,connectedAccountRepository,userWorkspaceRepository,+ workflowExecutionContextService,);}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/tool-backed/tool-backed.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/tool-backed/tool-backed.workflow-action.tsindex 752d5d7019d..ce59dd164da 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/tool-backed/tool-backed.workflow-action.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/tool-backed/tool-backed.workflow-action.ts@@ -3,11 +3,15 @@ import { Logger } from '@nestjs/common';import { resolveInput as resolveWorkflowInput } from 'twenty-shared/utils';import { type WorkflowRunStepLog } from 'twenty-shared/workflow';+import { type ToolExecutionContext } from 'src/engine/core-modules/tool/types/tool-execution-context.type';import { type ToolInput } from 'src/engine/core-modules/tool/types/tool-input.type';import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';import { type Tool } from 'src/engine/core-modules/tool/types/tool.type';import { type WorkflowAction as WorkflowActionContract } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';-import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input';+import {+ type WorkflowActionInput,+ type WorkflowRunInfo,+} from 'src/modules/workflow/workflow-executor/types/workflow-action-input';import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';@@ -60,6 +64,12 @@ export abstract class ToolBackedWorkflowAction<args: BuildStepLogArgs<TInput>,): WorkflowRunStepLog;+ protected buildToolExecutionContext(+ runInfo: WorkflowRunInfo,+ ): Promise<ToolExecutionContext> {+ return Promise.resolve({ workspaceId: runInfo.workspaceId });+ }+async execute({currentStepId,steps,@@ -78,9 +88,10 @@ export abstract class ToolBackedWorkflowAction<);const startedAt = Date.now();- const toolOutput = await this.getTool().execute(resolvedInput, {- workspaceId: runInfo.workspaceId,- });+ const toolOutput = await this.getTool().execute(+ resolvedInput,+ await this.buildToolExecutionContext(runInfo),+ );const durationMs = Date.now() - startedAt;await this.persistStepLog({diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-webhook-triggered-action-step.util.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-webhook-triggered-action-step.util.tsnew file mode 100644index 00000000000..85373fd8d40--- /dev/null+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-webhook-triggered-action-step.util.ts@@ -0,0 +1,207 @@+import gql from 'graphql-tag';+import request from 'supertest';++import { updateWorkflowVersionTrigger } from 'test/integration/graphql/suites/workflow/utils/update-workflow-version-trigger.util';+import {+ destroyWorkflowRun,+ waitForWorkflowCompletion,+ type WorkflowRunStatusType,+} from 'test/integration/graphql/suites/workflow/utils/workflow-run-test.util';+import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';++import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++type WorkflowVersionStep = {+ id: string;+ type: string;+ settings: { input: Record<string, unknown> };+};++export type WebhookTriggeredActionStepRun = {+ status?: WorkflowRunStatusType;+ stepStatus?: string;+ stepResult?: Record<string, unknown>;+ stepError?: string;+};++export const runWebhookTriggeredActionStep = async ({+ name,+ stepType,+ input,+}: {+ name: string;+ stepType: 'SEND_EMAIL' | 'DRAFT_EMAIL';+ input: Record<string, unknown>;+}): Promise<WebhookTriggeredActionStepRun> => {+ const createWorkflowResponse = await makeGraphqlAPIRequest({+ query: gql`+ mutation CreateWorkflow($name: String!) {+ createWorkflow(data: { name: $name }) {+ id+ }+ }+ `,+ variables: { name },+ });++ expect(createWorkflowResponse.body.errors).toBeUndefined();++ const workflowId = createWorkflowResponse.body.data.createWorkflow.id;++ let workflowRunId: string | undefined;++ try {+ const workflowVersionsResponse = await makeGraphqlAPIRequest({+ query: gql`+ query FindDraftWorkflowVersion($workflowId: UUID!) {+ workflowVersions(+ filter: {+ workflowId: { eq: $workflowId }+ status: { in: ["DRAFT"] }+ }+ ) {+ edges {+ node {+ id+ }+ }+ }+ }+ `,+ variables: { workflowId },+ });++ expect(workflowVersionsResponse.body.errors).toBeUndefined();++ const workflowVersionId =+ workflowVersionsResponse.body.data.workflowVersions.edges[0].node.id;++ await updateWorkflowVersionTrigger({+ workflowVersionId,+ trigger: {+ name: 'Webhook Trigger',+ type: 'WEBHOOK',+ settings: {+ outputSchema: {},+ httpMethod: 'GET',+ authentication: null,+ },+ nextStepIds: [],+ position: { x: 0, y: 0 },+ },+ });++ const createStepResponse = await makeGraphqlAPIRequest({+ query: gql`+ mutation CreateWorkflowVersionStep(+ $input: CreateWorkflowVersionStepInput!+ ) {+ createWorkflowVersionStep(input: $input) {+ stepsDiff+ }+ }+ `,+ variables: {+ input: {+ workflowVersionId,+ stepType,+ parentStepId: 'trigger',+ position: { x: 200, y: 0 },+ },+ },+ });++ expect(createStepResponse.body.errors).toBeUndefined();++ const stepsResponse = await makeGraphqlAPIRequest({+ query: gql`+ query FindWorkflowVersionSteps($workflowVersionId: UUID!) {+ workflowVersion(filter: { id: { eq: $workflowVersionId } }) {+ steps+ }+ }+ `,+ variables: { workflowVersionId },+ });++ expect(stepsResponse.body.errors).toBeUndefined();++ const step: WorkflowVersionStep =+ stepsResponse.body.data.workflowVersion.steps.find(+ (workflowVersionStep: WorkflowVersionStep) =>+ workflowVersionStep.type === stepType,+ );++ expect(step).toBeDefined();++ const updateStepResponse = await makeGraphqlAPIRequest({+ query: gql`+ mutation UpdateWorkflowVersionStep(+ $input: UpdateWorkflowVersionStepInput!+ ) {+ updateWorkflowVersionStep(input: $input) {+ id+ }+ }+ `,+ variables: {+ input: {+ workflowVersionId,+ step: {+ ...step,+ settings: {+ ...step.settings,+ input: { ...step.settings.input, ...input },+ },+ },+ },+ },+ });++ expect(updateStepResponse.body.errors).toBeUndefined();++ const activateResponse = await makeGraphqlAPIRequest({+ query: gql`+ mutation ActivateWorkflowVersion($workflowVersionId: UUID!) {+ activateWorkflowVersion(workflowVersionId: $workflowVersionId)+ }+ `,+ variables: { workflowVersionId },+ });++ expect(activateResponse.body.errors).toBeUndefined();++ const webhookResponse = await request(`http://localhost:${APP_PORT}`).get(+ `/webhooks/workflows/${SEED_APPLE_WORKSPACE_ID}/${workflowId}`,+ );++ expect(webhookResponse.body.success).toBe(true);++ workflowRunId = webhookResponse.body.workflowRunId;++ const workflowRun = await waitForWorkflowCompletion(workflowRunId!);+ const stepInfo = workflowRun?.state?.stepInfos?.[step.id];++ return {+ status: workflowRun?.status,+ stepStatus: stepInfo?.status,+ stepResult: stepInfo?.result,+ stepError: stepInfo?.error,+ };+ } finally {+ if (workflowRunId !== undefined) {+ await destroyWorkflowRun(workflowRunId);+ }++ await makeGraphqlAPIRequest({+ query: gql`+ mutation DestroyWorkflow($id: ID!) {+ destroyWorkflow(id: $id) {+ id+ }+ }+ `,+ variables: { id: workflowId },+ });+ }+};diff --git a/packages/twenty-server/test/integration/workflow-actions/caller-connected-account.integration-spec.ts b/packages/twenty-server/test/integration/workflow-actions/caller-connected-account.integration-spec.tsnew file mode 100644index 00000000000..c1c765afbf0--- /dev/null+++ b/packages/twenty-server/test/integration/workflow-actions/caller-connected-account.integration-spec.ts@@ -0,0 +1,268 @@+import { randomUUID } from 'node:crypto';++import { ConnectedAccountProvider } from 'twenty-shared/types';+import { IsNull } from 'typeorm';++import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';+import { runWebhookTriggeredActionStep } from 'test/integration/graphql/suites/workflow/utils/run-webhook-triggered-action-step.util';+import { runWorkflowActionStep } from 'test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util';+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';++import {+ ConnectedAccountEntity,+ type ConnectedAccountVisibility,+} from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';++const OLDEST_HANDLE = '[email protected]';+const CALLER_HANDLE = '[email protected]';+const RECIPIENT = '[email protected]';++const CALLER_USER_WORKSPACE_ID = USER_WORKSPACE_DATA_SEED_IDS.JANE;+const OTHER_MEMBER_USER_WORKSPACE_ID = USER_WORKSPACE_DATA_SEED_IDS.JONY;+const THIRD_MEMBER_USER_WORKSPACE_ID = USER_WORKSPACE_DATA_SEED_IDS.PHIL;++describe('Email workflow actions with no sender configured (integration)', () => {+ const google = setupGoogleMock({ handle: OLDEST_HANDLE });++ const connectedAccounts = () =>+ getCoreRepository<ConnectedAccountEntity>(ConnectedAccountEntity);++ const setAccountOwnership = async ({+ connectedAccountId,+ userWorkspaceId,+ visibility,+ }: {+ connectedAccountId: string;+ userWorkspaceId: string;+ visibility: ConnectedAccountVisibility;+ }) =>+ connectedAccounts().update(+ { id: connectedAccountId },+ { userWorkspaceId, visibility },+ );++ let oldestAccount: Awaited<ReturnType<typeof connectMessagingAccount>>;+ let callerAccount: Awaited<ReturnType<typeof connectMessagingAccount>>;+ let preexistingAccountIds: string[] = [];++ beforeAll(async () => {+ const preexistingAccounts = await connectedAccounts().find({+ where: { workspaceId: SEED_APPLE_WORKSPACE_ID, archivedAt: IsNull() },+ select: { id: true },+ });++ preexistingAccountIds = preexistingAccounts.map(({ id }) => id);++ if (preexistingAccountIds.length > 0) {+ await connectedAccounts().update(preexistingAccountIds, {+ archivedAt: new Date(),+ });+ }++ oldestAccount = await connectMessagingAccount({+ provider: ConnectedAccountProvider.GOOGLE,+ handle: OLDEST_HANDLE,+ });++ google.actAsAccount(CALLER_HANDLE);++ callerAccount = await connectMessagingAccount({+ provider: ConnectedAccountProvider.GOOGLE,+ handle: CALLER_HANDLE,+ });+ }, 120000);++ beforeEach(async () => {+ await setAccountOwnership({+ connectedAccountId: oldestAccount.connectedAccountId,+ userWorkspaceId: OTHER_MEMBER_USER_WORKSPACE_ID,+ visibility: 'user',+ });+ await setAccountOwnership({+ connectedAccountId: callerAccount.connectedAccountId,+ userWorkspaceId: CALLER_USER_WORKSPACE_ID,+ visibility: 'user',+ });+ });++ afterAll(async () => {+ await setAccountOwnership({+ connectedAccountId: oldestAccount.connectedAccountId,+ userWorkspaceId: CALLER_USER_WORKSPACE_ID,+ visibility: 'user',+ }).catch(() => undefined);++ await callerAccount?.cleanup().catch(() => undefined);+ await oldestAccount?.cleanup().catch(() => undefined);++ if (preexistingAccountIds.length > 0) {+ await connectedAccounts().update(preexistingAccountIds, {+ archivedAt: null,+ });+ }+ });++ it('sends from the run caller own account rather than the oldest account of the workspace', async () => {+ const subject = `Caller scoped send ${randomUUID()}`;++ const workflowRun = await runWorkflowActionStep({+ name: 'Caller scoped send email workflow',+ stepType: 'SEND_EMAIL',+ input: {+ connectedAccountId: '',+ recipients: { to: RECIPIENT, cc: '', bcc: '' },+ subject,+ body: '<p>Caller scoped send body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'COMPLETED',+ stepStatus: 'SUCCESS',+ });+ expect(workflowRun.stepResult).toMatchObject({+ subject,+ connectedAccountId: callerAccount.connectedAccountId,+ });+ }, 60000);++ it('drafts from the run caller own account rather than the oldest account of the workspace', async () => {+ const subject = `Caller scoped draft ${randomUUID()}`;++ const workflowRun = await runWorkflowActionStep({+ name: 'Caller scoped draft email workflow',+ stepType: 'DRAFT_EMAIL',+ input: {+ connectedAccountId: '',+ recipients: { to: RECIPIENT, cc: '', bcc: '' },+ subject,+ body: '<p>Caller scoped draft body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'COMPLETED',+ stepStatus: 'SUCCESS',+ });+ expect(workflowRun.stepResult).toMatchObject({+ subject,+ connectedAccountId: callerAccount.connectedAccountId,+ });+ }, 60000);++ it('keeps the account pinned on the step even when another member owns it', async () => {+ const subject = `Pinned sender send ${randomUUID()}`;++ const workflowRun = await runWorkflowActionStep({+ name: 'Pinned sender send email workflow',+ stepType: 'SEND_EMAIL',+ input: {+ connectedAccountId: oldestAccount.connectedAccountId,+ recipients: { to: RECIPIENT, cc: '', bcc: '' },+ subject,+ body: '<p>Pinned sender send body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'COMPLETED',+ stepStatus: 'SUCCESS',+ });+ expect(workflowRun.stepResult).toMatchObject({+ subject,+ connectedAccountId: oldestAccount.connectedAccountId,+ });+ }, 60000);++ it('falls back to a workspace visible account when the run caller owns none', async () => {+ await setAccountOwnership({+ connectedAccountId: callerAccount.connectedAccountId,+ userWorkspaceId: THIRD_MEMBER_USER_WORKSPACE_ID,+ visibility: 'user',+ });+ await setAccountOwnership({+ connectedAccountId: oldestAccount.connectedAccountId,+ userWorkspaceId: OTHER_MEMBER_USER_WORKSPACE_ID,+ visibility: 'workspace',+ });++ const subject = `Workspace visible fallback ${randomUUID()}`;++ const workflowRun = await runWorkflowActionStep({+ name: 'Workspace visible fallback send email workflow',+ stepType: 'SEND_EMAIL',+ input: {+ connectedAccountId: '',+ recipients: { to: RECIPIENT, cc: '', bcc: '' },+ subject,+ body: '<p>Workspace visible fallback body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'COMPLETED',+ stepStatus: 'SUCCESS',+ });+ expect(workflowRun.stepResult).toMatchObject({+ subject,+ connectedAccountId: oldestAccount.connectedAccountId,+ });+ }, 60000);++ it('fails the step rather than sending from a private account of another member', async () => {+ await setAccountOwnership({+ connectedAccountId: callerAccount.connectedAccountId,+ userWorkspaceId: THIRD_MEMBER_USER_WORKSPACE_ID,+ visibility: 'user',+ });++ const sentMessageCount = google.sentMessages.length;++ const workflowRun = await runWorkflowActionStep({+ name: 'No usable account send email workflow',+ stepType: 'SEND_EMAIL',+ input: {+ connectedAccountId: '',+ recipients: { to: RECIPIENT, cc: '', bcc: '' },+ subject: `No usable account ${randomUUID()}`,+ body: '<p>No usable account body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'FAILED',+ stepStatus: 'FAILED',+ stepError: expect.stringContaining(+ `No connected account available for user workspace '${CALLER_USER_WORKSPACE_ID}'`,+ ),+ });+ expect(google.sentMessages).toHaveLength(sentMessageCount);+ }, 60000);++ it('keeps the workspace wide fallback for runs that no user started', async () => {+ const subject = `Webhook triggered send ${randomUUID()}`;++ const workflowRun = await runWebhookTriggeredActionStep({+ name: 'Webhook triggered send email workflow',+ stepType: 'SEND_EMAIL',+ input: {+ connectedAccountId: '',+ recipients: { to: RECIPIENT, cc: '', bcc: '' },+ subject,+ body: '<p>Webhook triggered send body</p>',+ },+ });++ expect(workflowRun).toMatchObject({+ status: 'COMPLETED',+ stepStatus: 'SUCCESS',+ });+ expect(workflowRun.stepResult).toMatchObject({+ subject,+ connectedAccountId: oldestAccount.connectedAccountId,+ });+ }, 60000);+});