Skip to content

The open alternative to Salesforce, designed for AI.

revert(email-tool): restore the default sender resolution (#25972)

Etienne3bb53150a909
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts
index 2bfcd54d2bb..d2974180039 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts
@@ -266,7 +266,6 @@ export class ActionToolProvider implements ToolProvider {
workspaceId: context.workspaceId,
userId: context.userId,
userWorkspaceId: context.userWorkspaceId,
- callerType: context.authContext?.type,
threadId: context.threadId,
onCodeExecutionUpdate: context.onCodeExecutionUpdate,
});
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
index 5ff9d56ea77..24773c631ef 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
@@ -10,13 +10,14 @@ import {
} from 'twenty-shared/types';
import {
canConnectedAccountPerformEmailOperation,
+ getEmailProvidersForOperation,
isDefined,
+ isNonEmptyArray,
isValidUuid,
} from 'twenty-shared/utils';
import { In, IsNull, LessThanOrEqual, type Repository } from 'typeorm';
import { z } from 'zod';
-import { type WorkspaceAuthContextType } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { FileService } from 'src/engine/core-modules/file/services/file.service';
import { compileOutboundEmailContent } from 'src/engine/core-modules/email/utils/compile-outbound-email-content.util';
@@ -31,8 +32,6 @@ import { EmailComposerResult } from 'src/engine/core-modules/tool/tools/email-to
import { parseCommaSeparatedEmails } from 'src/engine/core-modules/tool/tools/email-tool/utils/parse-comma-separated-emails.util';
import { selectConnectedAccountIdForCaller } from 'src/engine/core-modules/tool/tools/email-tool/utils/select-connected-account-id-for-caller.util';
import { type ToolExecutionContext } from 'src/engine/core-modules/tool/types/tool-execution-context.type';
-import { ConnectedAccountMetadataService } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.service';
-import { isCallerBypassingAccountVisibility } from 'src/engine/metadata-modules/connected-account/utils/is-caller-bypassing-account-visibility.util';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
@@ -59,7 +58,6 @@ export class EmailComposerService {
@InjectWorkspaceScopedRepository(FileEntity)
private readonly fileRepository: WorkspaceScopedRepository<FileEntity>,
private readonly fileService: FileService,
- private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,
) {}
private async getConnectedAccountOrThrow({
@@ -117,41 +115,55 @@ export class EmailComposerService {
workspaceId,
userWorkspaceId,
operation,
- callerType,
}: {
workspaceId: string;
userWorkspaceId?: string;
operation: EmailOperation;
- callerType?: WorkspaceAuthContextType;
}): Promise<string> {
- const usableMailboxes = isCallerBypassingAccountVisibility(callerType)
- ? await this.connectedAccountMetadataService.findWorkspaceMailboxes({
- workspaceId,
- operation,
- })
- : await this.connectedAccountMetadataService.findMailboxesUsableByCaller({
+ const authContext = buildSystemAuthContext(workspaceId);
+
+ return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const mailboxes = await this.connectedAccountRepository.find({
+ where: {
workspaceId,
- userWorkspaceId,
+ archivedAt: IsNull(),
+ provider: In(getEmailProvidersForOperation(operation)),
+ },
+ order: { createdAt: 'ASC', id: 'ASC' },
+ });
+
+ const usableMailboxes = mailboxes.filter((connectedAccount) =>
+ canConnectedAccountPerformEmailOperation({
+ connectedAccount,
operation,
- });
+ }),
+ );
- const connectedAccountId = isDefined(userWorkspaceId)
- ? selectConnectedAccountIdForCaller({
- connectedAccounts: usableMailboxes,
- userWorkspaceId,
- })
- : usableMailboxes[0]?.id;
+ if (!isNonEmptyArray(usableMailboxes)) {
+ throw new EmailToolException(
+ `No connected account in this workspace can ${operation.toLowerCase()} email`,
+ EmailToolExceptionCode.NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT,
+ );
+ }
- if (!isDefined(connectedAccountId)) {
- throw new EmailToolException(
- isDefined(userWorkspaceId)
- ? `No connected account available for user workspace '${userWorkspaceId}' that can ${operation.toLowerCase()} email`
- : `No connected account in this workspace can ${operation.toLowerCase()} email`,
- EmailToolExceptionCode.NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT,
- );
- }
+ if (!isDefined(userWorkspaceId)) {
+ return usableMailboxes[0].id;
+ }
+
+ const connectedAccountId = selectConnectedAccountIdForCaller({
+ connectedAccounts: usableMailboxes,
+ userWorkspaceId,
+ });
- return connectedAccountId;
+ if (!isDefined(connectedAccountId)) {
+ throw new EmailToolException(
+ `No connected account available for user workspace '${userWorkspaceId}' that can ${operation.toLowerCase()} email`,
+ EmailToolExceptionCode.NO_EMAIL_CAPABLE_CONNECTED_ACCOUNT,
+ );
+ }
+
+ return connectedAccountId;
+ }, authContext);
}
private normalizeRecipients(parameters: ComposeEmailParams): {
@@ -353,7 +365,7 @@ export class EmailComposerService {
context: ToolExecutionContext;
operation: EmailOperation;
}): Promise<EmailComposerResult> {
- const { workspaceId, userWorkspaceId, callerType } = context;
+ const { workspaceId, userWorkspaceId } = context;
const { subject, body, files, inReplyTo, fromHandle } = parameters;
let { connectedAccountId } = parameters;
@@ -396,7 +408,6 @@ export class EmailComposerService {
workspaceId,
userWorkspaceId,
operation,
- callerType,
});
}
diff --git a/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts b/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts
index 0857e1ea20d..aed3c2a2a8b 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts
@@ -1,11 +1,9 @@
-import { type WorkspaceAuthContextType } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { type CodeExecutionStreamEmitter } from 'src/engine/core-modules/tool-provider/interfaces/code-execution-stream-emitter.type';
export type ToolExecutionContext = {
workspaceId: string;
userId?: string;
userWorkspaceId?: string;
- callerType?: WorkspaceAuthContextType;
threadId?: string;
onCodeExecutionUpdate?: CodeExecutionStreamEmitter;
};
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 697ea1d5800..fc30aa45c0a 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
@@ -50,11 +50,13 @@ export class ConnectedAccountMetadataService {
private readonly workspaceEventEmitter: WorkspaceEventEmitter,
) {}
- async findWorkspaceMailboxes({
+ async findMailboxesUsableByCaller({
workspaceId,
+ userWorkspaceId,
operation,
}: {
workspaceId: string;
+ userWorkspaceId?: string;
operation: EmailOperation;
}): Promise<ConnectedAccountUsableByCaller[]> {
const connectedAccounts = await this.repository.find({
@@ -76,36 +78,21 @@ export class ConnectedAccountMetadataService {
},
});
- return connectedAccounts.filter((connectedAccount) =>
- canConnectedAccountPerformEmailOperation({
- connectedAccount,
- operation,
- }),
- );
- }
-
- async findMailboxesUsableByCaller({
- workspaceId,
- userWorkspaceId,
- operation,
- }: {
- workspaceId: string;
- userWorkspaceId?: string;
- operation: EmailOperation;
- }): Promise<ConnectedAccountUsableByCaller[]> {
- const mailboxes = await this.findWorkspaceMailboxes({
- workspaceId,
- operation,
- });
-
- return mailboxes.filter((connectedAccount) =>
- isDefined(userWorkspaceId)
- ? isConnectedAccountUsableByCaller({
- connectedAccount,
- userWorkspaceId,
- })
- : connectedAccount.visibility === 'workspace',
- );
+ return connectedAccounts
+ .filter((connectedAccount) =>
+ canConnectedAccountPerformEmailOperation({
+ connectedAccount,
+ operation,
+ }),
+ )
+ .filter((connectedAccount) =>
+ isDefined(userWorkspaceId)
+ ? isConnectedAccountUsableByCaller({
+ connectedAccount,
+ userWorkspaceId,
+ })
+ : connectedAccount.visibility === 'workspace',
+ );
}
async findUsableByCaller({
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/__tests__/is-caller-bypassing-account-visibility.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/__tests__/is-caller-bypassing-account-visibility.util.spec.ts
deleted file mode 100644
index 86fd32cd0f6..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/__tests__/is-caller-bypassing-account-visibility.util.spec.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { isCallerBypassingAccountVisibility } from 'src/engine/metadata-modules/connected-account/utils/is-caller-bypassing-account-visibility.util';
-
-describe('isCallerBypassingAccountVisibility', () => {
- it.each(['application', 'system'] as const)(
- 'accepts a %s run, the workspace acts on itself',
- (callerType) => {
- expect(isCallerBypassingAccountVisibility(callerType)).toBe(true);
- },
- );
-
- it.each(['user', 'apiKey', 'pendingActivationUser'] as const)(
- 'rejects a %s caller, it is held to account visibility',
- (callerType) => {
- expect(isCallerBypassingAccountVisibility(callerType)).toBe(false);
- },
- );
-
- it('rejects an unidentified caller', () => {
- expect(isCallerBypassingAccountVisibility(undefined)).toBe(false);
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/is-caller-bypassing-account-visibility.util.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/is-caller-bypassing-account-visibility.util.ts
deleted file mode 100644
index f353eeecec5..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/connected-account/utils/is-caller-bypassing-account-visibility.util.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { type WorkspaceAuthContextType } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-
-export const isCallerBypassingAccountVisibility = (
- callerType?: WorkspaceAuthContextType,
-): boolean => {
- switch (callerType) {
- case 'application':
- case 'system':
- return true;
- default:
- return false;
- }
-};
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.ts
index 7ce8f556024..fb3f95248a3 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
@@ -80,7 +80,6 @@ export abstract class EmailWorkflowActionBase extends ToolBackedWorkflowAction<W
return {
workspaceId: runInfo.workspaceId,
- callerType: authContext.type,
...getUserFromAuthContext(authContext),
};
}
diff --git a/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts b/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts
index 4616f598990..e4c663d9753 100644
--- a/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts
+++ b/packages/twenty-server/test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts
@@ -329,7 +329,7 @@ describe('EmailComposerService connected account resolution (integration)', () =
}
});
- it('skips an older SSO connection on a run that no user started', async () => {
+ it('skips an older SSO connection when there is no caller (workflow run)', async () => {
const oidcConnectedAccountId = '20202020-0000-4000-8000-0000000000a3';
await insertNonMailboxConnectedAccount({
@@ -344,7 +344,7 @@ describe('EmailComposerService connected account resolution (integration)', () =
const result = await service.composeEmail({
parameters: baseParams,
- context: { workspaceId: WORKSPACE_ID, callerType: 'application' },
+ context: { workspaceId: WORKSPACE_ID },
operation: EmailOperation.SEND,
});
@@ -412,13 +412,13 @@ describe('EmailComposerService connected account resolution (integration)', () =
}
});
- it('takes the first workspace account on a run that no user started', async () => {
+ it('takes the first workspace account when there is no caller (workflow run)', async () => {
const firstWorkspaceConnectedAccountId =
await getFirstWorkspaceConnectedAccountId();
const result = await service.composeEmail({
parameters: baseParams,
- context: { workspaceId: WORKSPACE_ID, callerType: 'application' },
+ context: { workspaceId: WORKSPACE_ID },
operation: EmailOperation.SEND,
});
@@ -427,53 +427,5 @@ describe('EmailComposerService connected account resolution (integration)', () =
firstWorkspaceConnectedAccountId,
);
});
-
- it('refuses an unidentified caller when no account is shared with the workspace', async () => {
- const sharedConnectedAccountIds =
- await getWorkspaceSharedConnectedAccountIds();
-
- for (const connectedAccountId of sharedConnectedAccountIds) {
- await setVisibility(connectedAccountId, 'user');
- }
-
- try {
- await expect(
- service.composeEmail({
- parameters: baseParams,
- context: { workspaceId: WORKSPACE_ID },
- operation: EmailOperation.SEND,
- }),
- ).rejects.toThrow(
- 'No connected account in this workspace can send email',
- );
- } finally {
- for (const connectedAccountId of sharedConnectedAccountIds) {
- await setVisibility(connectedAccountId, 'workspace');
- }
- }
- });
-
- it('serves an unidentified caller the account shared with the workspace', async () => {
- const { visibility } = await readConnectedAccountState(
- JONY_CONNECTED_ACCOUNT_ID,
- );
-
- await setVisibility(JONY_CONNECTED_ACCOUNT_ID, 'workspace');
-
- try {
- const result = await service.composeEmail({
- parameters: baseParams,
- context: { workspaceId: WORKSPACE_ID },
- operation: EmailOperation.SEND,
- });
-
- expect(result.success).toBe(true);
- expect(result.success && result.data.connectedAccount.id).toBe(
- JONY_CONNECTED_ACCOUNT_ID,
- );
- } finally {
- await setVisibility(JONY_CONNECTED_ACCOUNT_ID, visibility);
- }
- });
});
});