Skip to content

The open alternative to Salesforce, designed for AI.

chore(server): remove service unit specs (#27020)

Charles Bochet3198a0ef79d3
diff --git a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration-state.service.spec.ts b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration-state.service.spec.ts
deleted file mode 100644
index 5c2eff147d1..00000000000
--- a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration-state.service.spec.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import { AgentHistoryMigrationStateService } from 'src/database/commands/agent-history/agent-history-migration-state.service';
-import { type AgentHistoryMigrationState } from 'src/database/commands/agent-history/agent-history-migration-state.type';
-
-const WORKSPACE_ID = '20202020-1111-4111-8111-111111111111';
-const TABLE_NAME =
- '"workspace_20202020111141118111111111111111"."agentChatThread"';
-
-describe('AgentHistoryMigrationStateService', () => {
- const service = new AgentHistoryMigrationStateService();
- const query = jest.fn();
- const runner = { query };
-
- beforeEach(() => {
- query.mockReset();
- });
-
- it.each(['clearing', 'copying', 'aborting'] as const)(
- 'retains the %s cursor and rollback retention facts',
- async (phase) => {
- const state: AgentHistoryMigrationState = {
- storage: 'workspace',
- migration: {
- phase,
- target: 'core',
- tableIndex: 5,
- lastId: WORKSPACE_ID,
- },
- verifiedAt: '2026-09-01T00:00:00.000Z',
- cleanedAt: '2026-09-20T00:00:00.000Z',
- };
- query.mockResolvedValue([
- { workspaceId: WORKSPACE_ID, type: 'CONFIG_VARIABLE', value: state },
- ]);
-
- await expect(service.readState(runner, WORKSPACE_ID)).resolves.toEqual(
- state,
- );
- },
- );
-
- it.each([
- { storage: 'unknown' },
- { storage: 'workspace', verifiedAt: 'invalid' },
- { storage: 'workspace', cleanedAt: 'invalid' },
- {
- storage: 'core',
- migration: {
- phase: 'copying',
- target: 'core',
- tableIndex: 0,
- lastId: null,
- },
- },
- {
- storage: 'core',
- migration: {
- phase: 'copying',
- target: 'workspace',
- tableIndex: 6,
- lastId: null,
- },
- },
- {
- storage: 'core',
- migration: {
- phase: 'copying',
- target: 'workspace',
- tableIndex: 1,
- lastId: 'invalid',
- },
- },
- ])('refuses corrupt durable state: %j', async (value) => {
- query.mockResolvedValue([
- { workspaceId: WORKSPACE_ID, type: 'CONFIG_VARIABLE', value },
- ]);
-
- await expect(service.readState(runner, WORKSPACE_ID)).rejects.toMatchObject(
- {
- code: 'INVALID_STATE',
- },
- );
- });
-
- it('refuses a route stored under another key type', async () => {
- query.mockResolvedValue([
- {
- workspaceId: WORKSPACE_ID,
- type: 'USER_VAR',
- value: { storage: 'workspace' },
- },
- ]);
-
- await expect(service.readState(runner, WORKSPACE_ID)).rejects.toMatchObject(
- {
- code: 'INVALID_STATE',
- },
- );
- });
-
- it('starts unrouted history in core when the workspace table does not exist', async () => {
- query.mockResolvedValue([]);
-
- await expect(service.readState(runner, WORKSPACE_ID)).resolves.toEqual({
- storage: 'core',
- });
- });
-
- it('starts unrouted history in core when the workspace table is empty', async () => {
- query
- .mockResolvedValueOnce([])
- .mockResolvedValueOnce([
- { workspaceId: WORKSPACE_ID, tableName: TABLE_NAME },
- ])
- .mockResolvedValueOnce([]);
-
- await expect(service.readState(runner, WORKSPACE_ID)).resolves.toEqual({
- storage: 'core',
- });
- });
-
- it('refuses to select a stale core snapshot when a populated workspace lost its route', async () => {
- query
- .mockResolvedValueOnce([])
- .mockResolvedValueOnce([
- { workspaceId: WORKSPACE_ID, tableName: TABLE_NAME },
- ])
- .mockResolvedValueOnce([{ workspaceId: WORKSPACE_ID }]);
-
- await expect(service.readState(runner, WORKSPACE_ID)).rejects.toMatchObject(
- {
- code: 'MISSING_STATE',
- },
- );
- });
-
- it('writes the durable protocol understood by deployed servers', async () => {
- const state: AgentHistoryMigrationState = {
- storage: 'core',
- migration: {
- phase: 'copying',
- target: 'workspace',
- tableIndex: 2,
- lastId: WORKSPACE_ID,
- },
- };
- query.mockResolvedValue([{ key: 'agent-history-storage-v1' }]);
-
- await service.writeState(runner, WORKSPACE_ID, state);
-
- expect(query).toHaveBeenCalledWith(expect.any(String), [
- 'agent-history-storage-v1',
- WORKSPACE_ID,
- JSON.stringify(state),
- ]);
- });
-
- it('refuses to overwrite a conflicting non-configuration key', async () => {
- query.mockResolvedValue([]);
-
- await expect(
- service.writeState(runner, WORKSPACE_ID, { storage: 'workspace' }),
- ).rejects.toMatchObject({ code: 'INVALID_STATE' });
- });
-});
diff --git a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration-validation.service.spec.ts b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration-validation.service.spec.ts
deleted file mode 100644
index 74ac077cf94..00000000000
--- a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration-validation.service.spec.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { AgentHistoryMigrationValidationService } from 'src/database/commands/agent-history/agent-history-migration-validation.service';
-
-const WORKSPACE_ID = '20202020-0000-4000-8000-000000000001';
-
-const buildRunner = ({
- tableExists,
- liveTargetIds,
-}: {
- tableExists: boolean;
- liveTargetIds: string[];
-}) => ({
- query: jest.fn().mockImplementation(async (sql: string) => {
- if (sql.includes('to_regclass')) {
- return [{ exists: tableExists }];
- }
-
- return liveTargetIds.map((id) => ({ id }));
- }),
-});
-
-describe('Rolling agent history back to core', () => {
- const service = new AgentHistoryMigrationValidationService();
-
- it('refuses while records are still linked to chat threads', async () => {
- const runner = buildRunner({
- tableExists: true,
- liveTargetIds: ['20202020-0000-4000-8000-000000000002'],
- });
-
- await expect(
- service.assertNoThreadTargets({
- runner: runner as never,
- workspaceId: WORKSPACE_ID,
- }),
- ).rejects.toThrow(/Detach them before rolling agent history back to core/);
- });
-
- it('allows the rollback once every link is detached', async () => {
- const runner = buildRunner({ tableExists: true, liveTargetIds: [] });
-
- await expect(
- service.assertNoThreadTargets({
- runner: runner as never,
- workspaceId: WORKSPACE_ID,
- }),
- ).resolves.toBeUndefined();
- });
-
- // A workspace that never got the target object cannot have links, and must
- // not be blocked by a query against a table that does not exist.
- it('allows the rollback in a workspace that has no target table', async () => {
- const runner = buildRunner({ tableExists: false, liveTargetIds: [] });
-
- await expect(
- service.assertNoThreadTargets({
- runner: runner as never,
- workspaceId: WORKSPACE_ID,
- }),
- ).resolves.toBeUndefined();
-
- expect(runner.query).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/packages/twenty-server/src/database/commands/command-runners/__tests__/workspace-iterator.service.spec.ts b/packages/twenty-server/src/database/commands/command-runners/__tests__/workspace-iterator.service.spec.ts
deleted file mode 100644
index 9e9f7aa3389..00000000000
--- a/packages/twenty-server/src/database/commands/command-runners/__tests__/workspace-iterator.service.spec.ts
+++ /dev/null
@@ -1,234 +0,0 @@
-import { Logger } from '@nestjs/common';
-
-import { type DataSource, type Repository } from 'typeorm';
-
-import { type CommandShutdownService } from 'src/database/commands/command-runners/command-shutdown.service';
-import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
-import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
-import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { ViewExceptionCode } from 'src/engine/metadata-modules/view/exceptions/view.exception';
-import { EMPTY_ORCHESTRATOR_FAILURE_REPORT } from 'src/engine/workspace-manager/workspace-migration/constant/empty-orchestrator-failure-report.constant';
-import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';
-
-describe('WorkspaceIteratorService', () => {
- let workspaceRepository: jest.Mocked<
- Pick<Repository<WorkspaceEntity>, 'findOne' | 'exists'>
- >;
- let workspaceCacheService: jest.Mocked<
- Pick<WorkspaceCacheService, 'evictWorkspaceFromLocalCache'>
- >;
- let service: WorkspaceIteratorService;
-
- beforeEach(() => {
- jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
- jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
- jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
-
- workspaceRepository = {
- findOne: jest
- .fn()
- .mockResolvedValue({ databaseSchema: 'workspace_schema' }),
- exists: jest.fn().mockResolvedValue(true),
- };
- const workspaceOrmManager = {
- executeInWorkspaceContext: jest.fn((fn: () => Promise<void>) => fn()),
- } as unknown as WorkspaceOrmManager;
- const commandShutdownService = {
- isShutdownRequested: jest.fn().mockReturnValue(false),
- listenToShutdownSignals: jest.fn(),
- } as unknown as CommandShutdownService;
-
- workspaceCacheService = {
- evictWorkspaceFromLocalCache: jest.fn().mockResolvedValue(undefined),
- };
-
- service = new WorkspaceIteratorService(
- workspaceRepository as unknown as Repository<WorkspaceEntity>,
- {} as DataSource,
- workspaceOrmManager,
- commandShutdownService,
- workspaceCacheService as unknown as WorkspaceCacheService,
- );
- });
-
- afterEach(() => {
- jest.restoreAllMocks();
- });
-
- it('skips a workspace deleted after the target list was captured', async () => {
- workspaceRepository.findOne.mockResolvedValueOnce(null);
- const callback = jest.fn();
-
- const report = await service.iterate({
- workspaceIds: ['deleted-workspace', 'live-workspace'],
- callback,
- });
-
- expect(callback).toHaveBeenCalledTimes(1);
- expect(callback).toHaveBeenCalledWith(
- expect.objectContaining({ workspaceId: 'live-workspace' }),
- );
- expect(report.skipped).toEqual([{ workspaceId: 'deleted-workspace' }]);
- expect(report.success).toEqual([{ workspaceId: 'live-workspace' }]);
- expect(report.fail).toEqual([]);
- });
-
- it.each([
- 'No workspace data source',
- 'migration history foreign key violation',
- ])('skips deletion during execution after %s', async (message) => {
- workspaceRepository.exists.mockResolvedValueOnce(false);
-
- const report = await service.iterate({
- workspaceIds: ['deleted-workspace', 'live-workspace'],
- callback: async ({ workspaceId }) => {
- if (workspaceId === 'deleted-workspace') {
- throw new Error(message);
- }
- },
- });
-
- expect(report.skipped).toEqual([{ workspaceId: 'deleted-workspace' }]);
- expect(report.fail).toEqual([]);
- expect(report.success).toEqual([{ workspaceId: 'live-workspace' }]);
- });
-
- it('retains a missing-data-source failure for an existing workspace', async () => {
- workspaceRepository.findOne.mockResolvedValueOnce({
- databaseSchema: null,
- } as WorkspaceEntity);
- const error = new Error('No workspace data source');
-
- const report = await service.iterate({
- workspaceIds: ['live-workspace'],
- callback: async ({ dataSource }) => {
- expect(dataSource).toBeUndefined();
- throw error;
- },
- });
-
- expect(report.fail).toEqual([{ workspaceId: 'live-workspace', error }]);
- expect(report.skipped).toEqual([]);
- expect(report.success).toEqual([]);
- });
-
- it('does not infer deletion when the existence check fails', async () => {
- workspaceRepository.exists.mockRejectedValueOnce(
- new Error('database unavailable'),
- );
-
- await expect(
- service.iterate({
- workspaceIds: ['live-workspace'],
- callback: async () => {
- throw new Error('command failed');
- },
- }),
- ).rejects.toThrow('database unavailable');
- });
-
- it('evicts each workspace from the local cache once its callback has run', async () => {
- const events: string[] = [];
-
- workspaceCacheService.evictWorkspaceFromLocalCache.mockImplementation(
- async (workspaceId) => {
- events.push(`evict:${workspaceId}`);
- },
- );
-
- const report = await service.iterate({
- workspaceIds: ['workspace-1', 'workspace-2'],
- callback: async ({ workspaceId }) => {
- events.push(`callback:${workspaceId}`);
- },
- });
-
- expect(report.success.map(({ workspaceId }) => workspaceId)).toEqual([
- 'workspace-1',
- 'workspace-2',
- ]);
- expect(events).toEqual([
- 'callback:workspace-1',
- 'evict:workspace-1',
- 'callback:workspace-2',
- 'evict:workspace-2',
- ]);
- });
-
- it('still evicts a workspace whose callback failed', async () => {
- const report = await service.iterate({
- workspaceIds: ['workspace-1'],
- callback: async () => {
- throw new Error('callback failed');
- },
- });
-
- expect(report.fail).toEqual([
- { workspaceId: 'workspace-1', error: new Error('callback failed') },
- ]);
- expect(
- workspaceCacheService.evictWorkspaceFromLocalCache,
- ).toHaveBeenCalledTimes(1);
- expect(
- workspaceCacheService.evictWorkspaceFromLocalCache,
- ).toHaveBeenCalledWith('workspace-1');
- });
-
- it.each([1, 200])(
- 'logs all %s validation errors and the stack when a migration cannot be built',
- async (errorCount) => {
- const error = new WorkspaceMigrationBuilderException(
- {
- status: 'fail',
- report: {
- ...EMPTY_ORCHESTRATOR_FAILURE_REPORT(),
- viewField: [
- {
- metadataName: 'viewField',
- type: 'create',
- flatEntityMinimalInformation: {
- universalIdentifier: 'missing-field-view',
- fieldMetadataUniversalIdentifier: 'missing-field',
- },
- errors: Array.from({ length: errorCount }, (_, index) => ({
- code: ViewExceptionCode.INVALID_VIEW_DATA,
- message: `Field metadata not found ${index}`,
- })),
- },
- ],
- },
- },
- 'Failed to sync the message record page',
- );
-
- const report = await service.iterate({
- workspaceIds: ['workspace-1', 'workspace-2'],
- callback: async ({ workspaceId }) => {
- if (workspaceId === 'workspace-1') {
- throw error;
- }
- },
- });
-
- expect(report.fail).toEqual([{ workspaceId: 'workspace-1', error }]);
- expect(report.success).toEqual([{ workspaceId: 'workspace-2' }]);
- expect(Logger.prototype.error).toHaveBeenCalledWith(
- expect.stringContaining('Field metadata not found'),
- );
- expect(Logger.prototype.error).toHaveBeenCalledWith(
- expect.stringContaining('missing-field'),
- );
- expect(Logger.prototype.error).toHaveBeenCalledWith(
- expect.stringContaining('workspace-1'),
- );
- expect(Logger.prototype.error).toHaveBeenCalledWith(
- `Migration validation report for workspace workspace-1: ${JSON.stringify(error.failedWorkspaceMigrationBuildResult.report, null, 2)}`,
- );
- expect(Logger.prototype.error).toHaveBeenCalledWith(
- 'Error in workspace workspace-1: Failed to sync the message record page',
- error.stack,
- );
- },
- );
-});
diff --git a/packages/twenty-server/src/engine/api/mcp/services/__tests__/mcp-tool-executor.service.spec.ts b/packages/twenty-server/src/engine/api/mcp/services/__tests__/mcp-tool-executor.service.spec.ts
deleted file mode 100644
index 042437cb467..00000000000
--- a/packages/twenty-server/src/engine/api/mcp/services/__tests__/mcp-tool-executor.service.spec.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { type ToolSet } from 'ai';
-
-import { McpToolExecutorService } from 'src/engine/api/mcp/services/mcp-tool-executor.service';
-import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
-import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
-
-describe('McpToolExecutorService', () => {
- let service: McpToolExecutorService;
- let metricsService: jest.Mocked<MetricsService>;
-
- const buildToolSet = (execute: jest.Mock): ToolSet =>
- ({
- create_person: {
- description: 'Create a person',
- inputSchema: {},
- execute,
- },
- }) as unknown as ToolSet;
-
- beforeEach(async () => {
- metricsService = {
- incrementCounterBy: jest.fn(),
- recordHistogram: jest.fn(),
- } as unknown as jest.Mocked<MetricsService>;
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- McpToolExecutorService,
- {
- provide: MetricsService,
- useValue: metricsService,
- },
- ],
- }).compile();
-
- service = module.get(McpToolExecutorService);
- });
-
- afterEach(() => {
- jest.clearAllMocks();
- });
-
- describe('handleToolCall', () => {
- it('should return isError false and count a success when the tool output succeeds', async () => {
- const toolOutput = { success: true, message: 'Created' };
- const toolSet = buildToolSet(jest.fn().mockResolvedValue(toolOutput));
-
- const response = await service.handleToolCall(1, toolSet, {
- name: 'create_person',
- arguments: {},
- });
-
- expect(response).toEqual({
- id: 1,
- jsonrpc: '2.0',
- result: {
- content: [{ type: 'text', text: JSON.stringify(toolOutput) }],
- isError: false,
- },
- });
- expect(metricsService.incrementCounterBy).toHaveBeenCalledWith(
- expect.objectContaining({
- key: MetricsKeys.McpToolExecutionSucceeded,
- }),
- );
- });
-
- it('should return isError true and count a failure when the tool output resolves with success false', async () => {
- const toolOutput = {
- success: false,
- message: 'Validation failed',
- error: 'Missing required field',
- };
- const toolSet = buildToolSet(jest.fn().mockResolvedValue(toolOutput));
-
- const response = await service.handleToolCall(1, toolSet, {
- name: 'create_person',
- arguments: {},
- });
-
- expect(response).toEqual({
- id: 1,
- jsonrpc: '2.0',
- result: {
- content: [{ type: 'text', text: JSON.stringify(toolOutput) }],
- isError: true,
- },
- });
- expect(metricsService.incrementCounterBy).toHaveBeenCalledWith(
- expect.objectContaining({
- key: MetricsKeys.McpToolExecutionFailed,
- }),
- );
- });
-
- it('should return isError true and count a failure when the tool throws', async () => {
- const toolSet = buildToolSet(
- jest.fn().mockRejectedValue(new Error('Database unavailable')),
- );
-
- const response = await service.handleToolCall(1, toolSet, {
- name: 'create_person',
- arguments: {},
- });
-
- expect(response).toEqual({
- id: 1,
- jsonrpc: '2.0',
- result: {
- content: [{ type: 'text', text: 'Database unavailable' }],
- isError: true,
- },
- });
- expect(metricsService.incrementCounterBy).toHaveBeenCalledWith(
- expect.objectContaining({
- key: MetricsKeys.McpToolExecutionFailed,
- }),
- );
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/__tests__/admin-panel-ai-provider.service.spec.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/__tests__/admin-panel-ai-provider.service.spec.ts
deleted file mode 100644
index 3db9571df6c..00000000000
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/__tests__/admin-panel-ai-provider.service.spec.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-/* @license Enterprise */
-
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { AdminPanelAiProviderService } from 'src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service';
-import { MAX_SEATS_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/enterprise/constants/max-seats-without-organization-key.constant';
-import { EnterpriseExceptionCode } from 'src/engine/core-modules/enterprise/enterprise.exception';
-import { CustomAiProviderAccessService } from 'src/engine/core-modules/enterprise/services/custom-ai-provider-access.service';
-import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
-import { DefaultAiCatalogService } from 'src/engine/metadata-modules/ai/ai-models/services/default-ai-catalog.service';
-
-describe('AdminPanelAiProviderService', () => {
- let service: AdminPanelAiProviderService;
- let providers: Record<string, unknown>;
-
- const twentyConfigService = {
- get: jest.fn(),
- set: jest.fn(),
- };
-
- const enterprisePlanService = {
- isValid: jest.fn(),
- getBillableSeatCount: jest.fn(),
- };
-
- const givenInstance = ({
- seatCount,
- isBillingEnabled = false,
- isEnterpriseValid = false,
- }: {
- seatCount: number;
- isBillingEnabled?: boolean;
- isEnterpriseValid?: boolean;
- }) => {
- twentyConfigService.get.mockImplementation((key: string) =>
- key === 'IS_BILLING_ENABLED' ? isBillingEnabled : providers,
- );
- enterprisePlanService.isValid.mockReturnValue(isEnterpriseValid);
- enterprisePlanService.getBillableSeatCount.mockResolvedValue(seatCount);
- };
-
- const addProvider = () =>
- service.addProvider({
- providerName: 'my-gateway',
- providerConfig: {
- npm: '@ai-sdk/openai-compatible',
- baseUrl: 'https://gateway.internal',
- },
- });
-
- beforeEach(async () => {
- jest.clearAllMocks();
- providers = {};
-
- twentyConfigService.set.mockImplementation(
- async (_key: string, value: Record<string, unknown>) => {
- providers = value;
- },
- );
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- AdminPanelAiProviderService,
- // The real gate is registered so these cover the seat rules end to end
- // rather than a stub of the very logic under test.
- CustomAiProviderAccessService,
- { provide: TwentyConfigService, useValue: twentyConfigService },
- { provide: EnterprisePlanService, useValue: enterprisePlanService },
- { provide: AiModelRegistryService, useValue: {} },
- { provide: DefaultAiCatalogService, useValue: {} },
- ],
- }).compile();
-
- service = module.get<AdminPanelAiProviderService>(
- AdminPanelAiProviderService,
- );
- });
-
- describe('addProvider', () => {
- it('persists the provider when the instance is under the seat threshold', async () => {
- givenInstance({ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY - 1 });
-
- await expect(addProvider()).resolves.toBe(true);
- expect(providers).toHaveProperty('my-gateway');
- });
-
- it('refuses and persists nothing above the threshold without an enterprise key', async () => {
- givenInstance({ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1 });
-
- await expect(addProvider()).rejects.toMatchObject({
- code: EnterpriseExceptionCode.ENTERPRISE_SEAT_THRESHOLD_EXCEEDED,
- });
- expect(twentyConfigService.set).not.toHaveBeenCalled();
- });
-
- it('persists the provider above the threshold with a valid enterprise key', async () => {
- givenInstance({
- seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 100,
- isEnterpriseValid: true,
- });
-
- await expect(addProvider()).resolves.toBe(true);
- expect(providers).toHaveProperty('my-gateway');
- });
-
- it('rejects a config whose npm package is not a supported SDK', async () => {
- givenInstance({ seatCount: 1 });
-
- await expect(
- service.addProvider({
- providerName: 'my-gateway',
- providerConfig: { npm: 'not-an-ai-sdk-package' },
- }),
- ).rejects.toThrow('Invalid provider configuration');
- expect(twentyConfigService.set).not.toHaveBeenCalled();
- });
-
- it('rejects a provider name that is not slug-safe', async () => {
- givenInstance({ seatCount: 1 });
-
- await expect(
- service.addProvider({
- providerName: 'not a slug',
- providerConfig: {
- npm: '@ai-sdk/openai-compatible',
- baseUrl: 'https://gateway.internal',
- },
- }),
- ).rejects.toThrow('Invalid provider name');
- });
- });
-
- describe('addModelToProvider', () => {
- it('refuses above the threshold without an enterprise key', async () => {
- givenInstance({ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1 });
-
- await expect(
- service.addModelToProvider({
- providerName: 'my-gateway',
- modelConfig: { name: 'gpt-4o', label: 'GPT-4o' },
- }),
- ).rejects.toMatchObject({
- code: EnterpriseExceptionCode.ENTERPRISE_SEAT_THRESHOLD_EXCEEDED,
- });
- });
- });
-
- describe('removeProvider', () => {
- it('stays available above the threshold so providers can be cleaned up', async () => {
- givenInstance({ seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1 });
- providers = { 'my-gateway': { npm: '@ai-sdk/openai-compatible' } };
-
- await expect(service.removeProvider('my-gateway')).resolves.toBe(true);
- expect(providers).not.toHaveProperty('my-gateway');
- });
- });
-
- describe('getCustomAiProviderAccess', () => {
- it('reports the threshold alongside the current seat count', async () => {
- givenInstance({ seatCount: 42 });
-
- await expect(service.getCustomAiProviderAccess()).resolves.toEqual({
- hasAccess: false,
- seatCount: 42,
- seatThreshold: MAX_SEATS_WITHOUT_ENTERPRISE_KEY,
- });
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-development/__tests__/application-file-upload.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-development/__tests__/application-file-upload.service.spec.ts
deleted file mode 100644
index 5d372ab210b..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/application-development/__tests__/application-file-upload.service.spec.ts
+++ /dev/null
@@ -1,427 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { FileFolder } from 'twenty-shared/types';
-
-import { ApplicationFileUploadService } from 'src/engine/core-modules/application/application-development/application-file-upload.service';
-import { ApplicationRegistrationService } from 'src/engine/core-modules/application/application-registration/application-registration.service';
-import {
- ApplicationException,
- ApplicationExceptionCode,
-} from 'src/engine/core-modules/application/application.exception';
-import { ApplicationService } from 'src/engine/core-modules/application/application.service';
-import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
-import { FileUploadCompletionService } from 'src/engine/core-modules/file/file-upload/services/file-upload-completion.service';
-import { FileUploadTargetService } from 'src/engine/core-modules/file/file-upload/services/file-upload-target.service';
-import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
-
-const WORKSPACE_ID = 'workspace-id';
-const APPLICATION_UNIVERSAL_IDENTIFIER = 'application-uid';
-
-describe('ApplicationFileUploadService', () => {
- let service: ApplicationFileUploadService;
-
- const applicationService = {
- findByUniversalIdentifier: jest.fn().mockResolvedValue({
- id: 'application-id',
- universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- applicationRegistrationId: 'registration-id',
- }),
- };
-
- const applicationRegistrationService = {
- findOneOwnedByWorkspaceOrThrow: jest.fn(),
- };
-
- const fileUploadTargetService = {
- createUploadTargetsBatch: jest.fn(),
- };
-
- const fileUploadCompletionService = {
- completeUploadsBatch: jest.fn(),
- };
-
- const fileRepository = {
- find: jest.fn(),
- };
-
- beforeEach(async () => {
- jest.clearAllMocks();
-
- applicationRegistrationService.findOneOwnedByWorkspaceOrThrow.mockResolvedValue(
- {
- id: 'registration-id',
- ownerWorkspaceId: WORKSPACE_ID,
- },
- );
-
- fileUploadTargetService.createUploadTargetsBatch.mockImplementation(
- (requests: { resourcePath: string }[]) =>
- Promise.resolve(
- requests.map((request, index) => ({
- success: true,
- value: {
- fileId: `file-id-${index}`,
- uploadUrl: `https://storage.tld/${request.resourcePath}`,
- contentType: 'application/octet-stream',
- expiresAt: new Date('2026-01-01T00:00:00.000Z'),
- },
- })),
- ),
- );
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- ApplicationFileUploadService,
- { provide: ApplicationService, useValue: applicationService },
- {
- provide: ApplicationRegistrationService,
- useValue: applicationRegistrationService,
- },
- { provide: FileUploadTargetService, useValue: fileUploadTargetService },
- {
- provide: FileUploadCompletionService,
- useValue: fileUploadCompletionService,
- },
- {
- provide: getWorkspaceScopedRepositoryToken(FileEntity),
- useValue: fileRepository,
- },
- ],
- }).compile();
-
- service = module.get<ApplicationFileUploadService>(
- ApplicationFileUploadService,
- );
- });
-
- describe('createApplicationFileUploads', () => {
- it('should return one upload target per valid file, delegating to the batch primitive', async () => {
- const result = await service.createApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- files: [
- {
- fileFolder: FileFolder.BuiltLogicFunction,
- filePath: 'handler.mjs',
- size: 12,
- },
- {
- fileFolder: FileFolder.PublicAsset,
- filePath: 'logo.png',
- size: 34,
- },
- ],
- });
-
- expect(result.errors).toEqual([]);
- expect(result.targets).toHaveLength(2);
- expect(result.targets[0].filePath).toBe('handler.mjs');
- expect(result.targets[0].fileFolder).toBe(FileFolder.BuiltLogicFunction);
- expect(result.targets[0].uploadUrl).toContain('https://storage.tld/');
- expect(result.targets[1].filePath).toBe('logo.png');
- expect(
- fileUploadTargetService.createUploadTargetsBatch,
- ).toHaveBeenCalledTimes(1);
- });
-
- it('should reserve pending files as octet-stream through the batch primitive', async () => {
- await service.createApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- files: [
- {
- fileFolder: FileFolder.Source,
- filePath: 'src/index.ts',
- size: 12,
- },
- ],
- });
-
- expect(
- fileUploadTargetService.createUploadTargetsBatch,
- ).toHaveBeenCalledWith([
- expect.objectContaining({
- workspaceId: WORKSPACE_ID,
- applicationId: 'application-id',
- fileFolder: FileFolder.Source,
- resourcePath: 'src/index.ts',
- size: 12,
- }),
- ]);
- });
-
- it('should collect a per-file error and skip the batch for a disallowed file folder', async () => {
- const result = await service.createApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- files: [
- {
- fileFolder: FileFolder.FilesField,
- filePath: 'document.pdf',
- size: 12,
- },
- ],
- });
-
- expect(result.targets).toEqual([]);
- expect(result.errors).toEqual([
- {
- fileFolder: FileFolder.FilesField,
- filePath: 'document.pdf',
- message: expect.stringContaining('Invalid fileFolder'),
- },
- ]);
- expect(
- fileUploadTargetService.createUploadTargetsBatch,
- ).toHaveBeenCalledWith([]);
- });
-
- it('should fail slow: a path escaping the folder becomes a per-file error while valid files still upload', async () => {
- const result = await service.createApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- files: [
- {
- fileFolder: FileFolder.Source,
- filePath: 'src/index.ts',
- size: 12,
- },
- {
- fileFolder: FileFolder.Source,
- filePath: '../../../etc/passwd',
- size: 12,
- },
- ],
- });
-
- expect(result.targets).toHaveLength(1);
- expect(result.targets[0].filePath).toBe('src/index.ts');
- expect(result.errors).toHaveLength(1);
- expect(result.errors[0].filePath).toBe('../../../etc/passwd');
- expect(
- fileUploadTargetService.createUploadTargetsBatch,
- ).toHaveBeenCalledWith([
- expect.objectContaining({ resourcePath: 'src/index.ts' }),
- ]);
- });
-
- it('should collect a per-file error for a file larger than the direct upload limit', async () => {
- const result = await service.createApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- files: [
- {
- fileFolder: FileFolder.Source,
- filePath: 'src/index.ts',
- size: 2 * 1024 * 1024 * 1024,
- },
- ],
- });
-
- expect(result.targets).toEqual([]);
- expect(result.errors[0].message).toContain('above the');
- });
-
- it('should surface a batch-primitive failure as a per-file error', async () => {
- fileUploadTargetService.createUploadTargetsBatch.mockResolvedValueOnce([
- { success: false, error: 'storage exploded' },
- ]);
-
- const result = await service.createApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- files: [
- {
- fileFolder: FileFolder.Source,
- filePath: 'src/index.ts',
- size: 12,
- },
- ],
- });
-
- expect(result.targets).toEqual([]);
- expect(result.errors).toEqual([
- {
- fileFolder: FileFolder.Source,
- filePath: 'src/index.ts',
- message: 'storage exploded',
- },
- ]);
- });
-
- it('should throw when the application does not exist in the workspace', async () => {
- applicationService.findByUniversalIdentifier.mockResolvedValueOnce(null);
-
- await expect(
- service.createApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- files: [
- {
- fileFolder: FileFolder.Source,
- filePath: 'src/index.ts',
- size: 12,
- },
- ],
- }),
- ).rejects.toThrow(ApplicationException);
- });
- });
-
- describe('completeApplicationFileUploads', () => {
- const file = {
- id: 'file-id',
- path: `${FileFolder.BuiltLogicFunction}/handler.mjs`,
- size: 12,
- createdAt: new Date('2026-01-01T00:00:00.000Z'),
- };
-
- it('should return the completed files delegated to the batch primitive', async () => {
- fileRepository.find.mockResolvedValueOnce([file]);
- fileUploadCompletionService.completeUploadsBatch.mockResolvedValueOnce([
- {
- success: true,
- value: {
- id: 'file-id',
- path: file.path,
- size: 12,
- createdAt: file.createdAt,
- },
- },
- ]);
-
- const result = await service.completeApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- fileIds: ['file-id'],
- });
-
- expect(result.errors).toEqual([]);
- expect(result.files).toEqual([
- {
- id: 'file-id',
- path: file.path,
- size: 12,
- createdAt: file.createdAt,
- },
- ]);
- expect(
- fileUploadCompletionService.completeUploadsBatch,
- ).toHaveBeenCalledWith([
- expect.objectContaining({ workspaceId: WORKSPACE_ID, file }),
- ]);
- });
-
- it('should surface a batch-primitive completion failure as a per-file error', async () => {
- fileRepository.find.mockResolvedValueOnce([file]);
- fileUploadCompletionService.completeUploadsBatch.mockResolvedValueOnce([
- { success: false, error: 'size mismatch' },
- ]);
-
- const result = await service.completeApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- fileIds: ['file-id'],
- });
-
- expect(result.files).toEqual([]);
- expect(result.errors).toEqual([
- { fileId: 'file-id', message: 'size mismatch' },
- ]);
- });
-
- it('should report file ids that do not belong to the application as errors', async () => {
- fileRepository.find.mockResolvedValueOnce([]);
- fileUploadCompletionService.completeUploadsBatch.mockResolvedValueOnce(
- [],
- );
-
- const result = await service.completeApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- fileIds: ['file-id-from-another-application'],
- });
-
- expect(result.files).toEqual([]);
- expect(result.errors).toEqual([
- {
- fileId: 'file-id-from-another-application',
- message: expect.stringContaining('No pending upload found'),
- },
- ]);
- });
- });
-
- describe('registration ownership', () => {
- const uploadRequest = {
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- files: [
- {
- fileFolder: FileFolder.BuiltLogicFunction,
- filePath: 'handler.mjs',
- size: 12,
- },
- {
- fileFolder: FileFolder.Dependencies,
- filePath: 'package.json',
- size: 12,
- },
- ],
- };
-
- const refuseOwnership = (code: ApplicationExceptionCode) =>
- applicationRegistrationService.findOneOwnedByWorkspaceOrThrow.mockRejectedValueOnce(
- new ApplicationException('Refused', code),
- );
-
- it('should check ownership by universal identifier before creating upload targets', async () => {
- await service.createApplicationFileUploads(uploadRequest);
-
- expect(
- applicationRegistrationService.findOneOwnedByWorkspaceOrThrow,
- ).toHaveBeenCalledWith({
- universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- workspaceId: WORKSPACE_ID,
- });
- });
-
- it('should refuse upload targets when the workspace does not own the registration', async () => {
- refuseOwnership(ApplicationExceptionCode.FORBIDDEN);
-
- await expect(
- service.createApplicationFileUploads(uploadRequest),
- ).rejects.toMatchObject({ code: ApplicationExceptionCode.FORBIDDEN });
- expect(
- fileUploadTargetService.createUploadTargetsBatch,
- ).not.toHaveBeenCalled();
- });
-
- it('should refuse upload targets when no registration matches the application', async () => {
- refuseOwnership(ApplicationExceptionCode.APPLICATION_NOT_FOUND);
-
- await expect(
- service.createApplicationFileUploads(uploadRequest),
- ).rejects.toThrow(ApplicationException);
- expect(
- fileUploadTargetService.createUploadTargetsBatch,
- ).not.toHaveBeenCalled();
- });
-
- it('should refuse to complete uploads when the workspace does not own the registration', async () => {
- refuseOwnership(ApplicationExceptionCode.FORBIDDEN);
-
- await expect(
- service.completeApplicationFileUploads({
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- fileIds: ['file-id'],
- }),
- ).rejects.toMatchObject({ code: ApplicationExceptionCode.FORBIDDEN });
- expect(fileRepository.find).not.toHaveBeenCalled();
- expect(
- fileUploadCompletionService.completeUploadsBatch,
- ).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-health/__tests__/application-health-check.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-health/__tests__/application-health-check.service.spec.ts
deleted file mode 100644
index 6acfe0761f7..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/application-health/__tests__/application-health-check.service.spec.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import { ApplicationHealthCheckService } from 'src/engine/core-modules/application/application-health/application-health-check.service';
-import { ApplicationHealthStatus } from 'twenty-shared/application';
-
-const APPLICATION_ID = 'a7d3f1c2-1111-4222-8333-444455556666';
-const WORKSPACE_ID = 'b7d3f1c2-1111-4222-8333-444455556666';
-const HEALTH_CHECK_ID = 'c7d3f1c2-1111-4222-8333-444455556666';
-
-const buildService = ({
- healthCheckLogicFunctionId = HEALTH_CHECK_ID,
- execute = jest.fn(),
-}: {
- healthCheckLogicFunctionId?: string | null;
- execute?: jest.Mock;
-} = {}) => {
- const applicationService = {
- findOneApplicationWithRelationsOrThrow: jest.fn().mockResolvedValue({
- id: APPLICATION_ID,
- version: '1.0.0',
- healthCheckLogicFunctionId,
- }),
- };
-
- const service = new ApplicationHealthCheckService(
- applicationService as never,
- { execute } as never,
- );
-
- return { service, execute };
-};
-
-const run = (service: ApplicationHealthCheckService) =>
- service.run({ applicationId: APPLICATION_ID, workspaceId: WORKSPACE_ID });
-
-describe('ApplicationHealthCheckService', () => {
- it('should do nothing when the application declares no health check', async () => {
- const { service, execute } = buildService({
- healthCheckLogicFunctionId: null,
- });
-
- expect(await run(service)).toBeNull();
- expect(execute).not.toHaveBeenCalled();
- });
-
- it('should report OK without a title when the app reports ok', async () => {
- const { service } = buildService({
- execute: jest.fn().mockResolvedValue({ data: { status: 'OK' } }),
- });
-
- expect(await run(service)).toEqual({
- status: ApplicationHealthStatus.OK,
- title: null,
- description: null,
- action: null,
- });
- });
-
- it('should report the reported title, description and action label', async () => {
- const { service } = buildService({
- execute: jest.fn().mockResolvedValue({
- data: {
- status: 'ERROR',
- title: 'Your key was revoked',
- description: 'Generate a new one from the provider dashboard.',
- action: { label: 'Reconnect', location: '#variables' },
- },
- }),
- });
-
- expect(await run(service)).toEqual({
- status: ApplicationHealthStatus.ERROR,
- title: 'Your key was revoked',
- description: 'Generate a new one from the provider dashboard.',
- action: { label: 'Reconnect', location: '#variables' },
- });
- });
-
- it.each([
- [ApplicationHealthStatus.SUCCESS],
- [ApplicationHealthStatus.INFO],
- [ApplicationHealthStatus.WARNING],
- [ApplicationHealthStatus.ERROR],
- [ApplicationHealthStatus.NEUTRAL],
- ])('should report a reported %s as is', async (reportedStatus) => {
- const { service } = buildService({
- execute: jest.fn().mockResolvedValue({
- data: { status: reportedStatus, title: 'Expiring' },
- }),
- });
-
- expect(await run(service)).toEqual({
- status: reportedStatus,
- title: 'Expiring',
- description: null,
- action: null,
- });
- });
-
- it.each([
- ['the execution errored', { data: null, error: { errorMessage: 'boom' } }],
- ['the result is unreadable', { data: { status: 'NOPE' } }],
- ['the result has no title', { data: { status: 'ERROR' } }],
- ])('should fall back to UNKNOWN when %s', async (_label, executionResult) => {
- const { service } = buildService({
- execute: jest.fn().mockResolvedValue(executionResult),
- });
-
- expect(await run(service)).toEqual({
- status: ApplicationHealthStatus.UNKNOWN,
- title: null,
- description: null,
- action: null,
- });
- });
-
- it('should fall back to UNKNOWN when the executor throws', async () => {
- const { service } = buildService({
- execute: jest.fn().mockRejectedValue(new Error('unreachable')),
- });
-
- expect(await run(service)).toEqual({
- status: ApplicationHealthStatus.UNKNOWN,
- title: null,
- description: null,
- action: null,
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/services/__tests__/application-lifecycle-job.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/services/__tests__/application-lifecycle-job.service.spec.ts
deleted file mode 100644
index 5b9d880b3a5..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/application-install/services/__tests__/application-lifecycle-job.service.spec.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-import { ApplicationLifecycleJobService } from 'src/engine/core-modules/application/application-install/services/application-lifecycle-job.service';
-import { TriggerInstallApplicationJob } from 'src/engine/core-modules/application/application-install/jobs/trigger-install-application.job';
-import { TriggerUninstallApplicationJob } from 'src/engine/core-modules/application/application-install/jobs/trigger-uninstall-application.job';
-import type { MarketplaceQueryService } from 'src/engine/core-modules/application/application-marketplace/marketplace-query.service';
-import type { ApplicationService } from 'src/engine/core-modules/application/application.service';
-import type { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
-import { JobStateEnum } from 'src/engine/core-modules/message-queue/enums/job-state.enum';
-import type { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
-
-const WORKSPACE_ID = 'workspace-id';
-const UNIVERSAL_IDENTIFIER = 'application-universal-identifier';
-const SUFFIX = '5c98b035-5b09-4550-a4fb-b52056c494d1';
-const INSTALL_JOB_ID_PREFIX = `install-application.${WORKSPACE_ID}.${UNIVERSAL_IDENTIFIER}`;
-const UNINSTALL_JOB_ID_PREFIX = `uninstall-application.${WORKSPACE_ID}.${UNIVERSAL_IDENTIFIER}`;
-const INSTALL_JOB_ID = `${INSTALL_JOB_ID_PREFIX}-${SUFFIX}`;
-const UNINSTALL_JOB_ID = `${UNINSTALL_JOB_ID_PREFIX}-${SUFFIX}`;
-const BROADCAST_TO = { workspaceId: WORKSPACE_ID };
-
-describe('ApplicationLifecycleJobService', () => {
- const applicationService = {
- findOneApplicationWithRelationsOrThrow: jest.fn().mockResolvedValue({}),
- } as unknown as ApplicationService;
- const marketplaceQueryService = {
- findRegistrationByUniversalIdentifier: jest
- .fn()
- .mockResolvedValue({ id: 'application-registration-id' }),
- } as unknown as MarketplaceQueryService;
- const workspaceQueueService = {
- add: jest.fn(),
- getJobs: jest.fn(),
- getInFlightJobs: jest.fn(),
- } as unknown as MessageQueueService;
-
- const cacheLockService = {
- withLock: jest.fn((fn: () => Promise<unknown>) => fn()),
- } as unknown as CacheLockService;
-
- const service = new ApplicationLifecycleJobService(
- applicationService,
- marketplaceQueryService,
- cacheLockService,
- workspaceQueueService,
- );
-
- const target = {
- universalIdentifier: UNIVERSAL_IDENTIFIER,
- workspaceId: WORKSPACE_ID,
- };
-
- beforeEach(() => {
- jest.clearAllMocks();
- jest.spyOn(workspaceQueueService, 'getInFlightJobs').mockResolvedValue([]);
- jest.spyOn(workspaceQueueService, 'getJobs').mockResolvedValue({});
- });
-
- describe('triggerInstallApplicationJob', () => {
- it('queues an installation deduplicated on the workspace and application prefix', async () => {
- jest
- .spyOn(workspaceQueueService, 'add')
- .mockResolvedValue(INSTALL_JOB_ID);
-
- const result = await service.triggerInstallApplicationJob(target);
-
- expect(result).toEqual({ jobId: INSTALL_JOB_ID });
- expect(cacheLockService.withLock).toHaveBeenCalledWith(
- expect.any(Function),
- `application-lifecycle-job:${WORKSPACE_ID}:${UNIVERSAL_IDENTIFIER}`,
- );
- expect(workspaceQueueService.add).toHaveBeenCalledWith(
- TriggerInstallApplicationJob.name,
- {
- applicationRegistrationId: 'application-registration-id',
- workspaceId: WORKSPACE_ID,
- },
- { id: INSTALL_JOB_ID_PREFIX, broadcastTo: BROADCAST_TO },
- );
- });
-
- it('reports the already waiting installation when the queue skips the add', async () => {
- jest.spyOn(workspaceQueueService, 'add').mockResolvedValue(undefined);
- jest.spyOn(workspaceQueueService, 'getInFlightJobs').mockResolvedValue([
- {
- id: `install-application.${WORKSPACE_ID}.other-application`,
- data: {},
- },
- { id: INSTALL_JOB_ID, data: {} },
- ]);
-
- expect(await service.triggerInstallApplicationJob(target)).toEqual({
- jobId: INSTALL_JOB_ID,
- });
- });
-
- it('refuses to queue an installation while an uninstallation is in flight', async () => {
- jest
- .spyOn(workspaceQueueService, 'getInFlightJobs')
- .mockResolvedValue([{ id: UNINSTALL_JOB_ID, data: {} }]);
-
- await expect(
- service.triggerInstallApplicationJob(target),
- ).rejects.toThrow(
- `Cannot install application ${UNIVERSAL_IDENTIFIER} while its uninstall is in progress`,
- );
- expect(workspaceQueueService.add).not.toHaveBeenCalled();
- });
-
- it('fails when the queue skipped the add and no installation is in flight', async () => {
- jest.spyOn(workspaceQueueService, 'add').mockResolvedValue(undefined);
-
- await expect(
- service.triggerInstallApplicationJob(target),
- ).rejects.toThrow(
- `Could not queue the install of application ${UNIVERSAL_IDENTIFIER}`,
- );
- });
- });
-
- describe('triggerUninstallApplicationJob', () => {
- it('queues an uninstallation of an installed application', async () => {
- jest
- .spyOn(workspaceQueueService, 'add')
- .mockResolvedValue(UNINSTALL_JOB_ID);
-
- const result = await service.triggerUninstallApplicationJob(target);
-
- expect(result).toEqual({ jobId: UNINSTALL_JOB_ID });
- expect(
- applicationService.findOneApplicationWithRelationsOrThrow,
- ).toHaveBeenCalledWith(target);
- expect(workspaceQueueService.add).toHaveBeenCalledWith(
- TriggerUninstallApplicationJob.name,
- target,
- { id: UNINSTALL_JOB_ID_PREFIX, broadcastTo: BROADCAST_TO },
- );
- });
-
- it('refuses to queue an uninstallation while an installation is in flight', async () => {
- jest
- .spyOn(workspaceQueueService, 'getInFlightJobs')
- .mockResolvedValue([{ id: INSTALL_JOB_ID, data: {} }]);
-
- await expect(
- service.triggerUninstallApplicationJob(target),
- ).rejects.toThrow(
- `Cannot uninstall application ${UNIVERSAL_IDENTIFIER} while its install is in progress`,
- );
- expect(workspaceQueueService.add).not.toHaveBeenCalled();
- });
-
- it('does not queue anything when the application is not installed', async () => {
- jest
- .spyOn(applicationService, 'findOneApplicationWithRelationsOrThrow')
- .mockRejectedValueOnce(new Error('Application not found'));
-
- await expect(
- service.triggerUninstallApplicationJob(target),
- ).rejects.toThrow('Application not found');
- expect(workspaceQueueService.add).not.toHaveBeenCalled();
- });
- });
-
- describe('job status', () => {
- it('reads back the in-flight job of the requested operation only', async () => {
- jest.spyOn(workspaceQueueService, 'getInFlightJobs').mockResolvedValue([
- { id: INSTALL_JOB_ID, data: {} },
- { id: UNINSTALL_JOB_ID, data: {} },
- ]);
- jest.spyOn(workspaceQueueService, 'getJobs').mockResolvedValue({
- [UNINSTALL_JOB_ID]: {
- id: UNINSTALL_JOB_ID,
- data: {},
- state: 'active',
- attemptsMade: 1,
- timestamp: 1,
- },
- } as never);
-
- expect(await service.findUninstallApplicationJobStatus(target)).toEqual({
- jobId: UNINSTALL_JOB_ID,
- state: JobStateEnum.ACTIVE,
- attemptsMade: 1,
- failedReason: undefined,
- enqueuedAt: 1,
- startedAt: undefined,
- finishedAt: undefined,
- });
- expect(workspaceQueueService.getJobs).toHaveBeenCalledWith([
- UNINSTALL_JOB_ID,
- ]);
- });
-
- it('returns no status when no job of the operation is in flight', async () => {
- jest
- .spyOn(workspaceQueueService, 'getInFlightJobs')
- .mockResolvedValue([{ id: UNINSTALL_JOB_ID, data: {} }]);
-
- expect(await service.findInstallApplicationJobStatus(target)).toBeNull();
- expect(workspaceQueueService.getJobs).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/services/__tests__/application-uninstall-runner.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/services/__tests__/application-uninstall-runner.service.spec.ts
deleted file mode 100644
index 9275010b3ea..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/application-install/services/__tests__/application-uninstall-runner.service.spec.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import type { ApplicationSyncService } from 'src/engine/core-modules/application/application-manifest/application-sync.service';
-import {
- ApplicationException,
- ApplicationExceptionCode,
-} from 'src/engine/core-modules/application/application.exception';
-import type { ApplicationService } from 'src/engine/core-modules/application/application.service';
-import { ApplicationUninstallRunnerService } from 'src/engine/core-modules/application/application-install/services/application-uninstall-runner.service';
-import type { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
-import type { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
-import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
-
-describe('ApplicationUninstallRunnerService', () => {
- const applicationService = {
- findByUniversalIdentifier: jest.fn().mockResolvedValue({
- name: 'Slack',
- sourceType: 'NPM',
- version: '1.2.0',
- }),
- } as unknown as ApplicationService;
- const applicationSyncService = {
- uninstallApplication: jest.fn(),
- } as unknown as ApplicationSyncService;
- const metricsService = {
- incrementCounterBy: jest.fn(),
- } as unknown as MetricsService;
- const cacheLockService = {
- withLock: jest.fn((fn: () => Promise<unknown>) => fn()),
- } as unknown as CacheLockService;
-
- const service = new ApplicationUninstallRunnerService(
- applicationService,
- applicationSyncService,
- metricsService,
- cacheLockService,
- );
-
- const target = {
- universalIdentifier: 'application-universal-identifier',
- workspaceId: 'workspace-id',
- };
-
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('counts a lock acquisition failure as a failed uninstall', async () => {
- jest
- .spyOn(cacheLockService, 'withLock')
- .mockRejectedValueOnce(new Error('Failed to acquire lock'));
-
- await expect(service.uninstallApplication(target)).rejects.toThrow(
- 'Failed to acquire lock',
- );
- expect(applicationSyncService.uninstallApplication).not.toHaveBeenCalled();
- expect(metricsService.incrementCounterBy).toHaveBeenCalledWith(
- expect.objectContaining({
- key: MetricsKeys.AppUninstallFailed,
- attributes: expect.objectContaining({ error_code: 'UNKNOWN' }),
- }),
- );
- });
-
- it('uninstalls the application under the lifecycle lock and counts the success', async () => {
- await service.uninstallApplication(target);
-
- expect(cacheLockService.withLock).toHaveBeenCalledWith(
- expect.any(Function),
- `application-lifecycle:${target.workspaceId}:${target.universalIdentifier}`,
- { ttl: 60_000, ms: 500, maxRetries: 120 },
- );
- expect(applicationSyncService.uninstallApplication).toHaveBeenCalledWith({
- applicationUniversalIdentifier: target.universalIdentifier,
- workspaceId: target.workspaceId,
- });
- expect(metricsService.incrementCounterBy).toHaveBeenCalledWith({
- key: MetricsKeys.AppUninstallSucceeded,
- amount: 1,
- attributes: {
- universal_identifier: target.universalIdentifier,
- app_name: 'Slack',
- source_type: 'NPM',
- version: '1.2.0',
- },
- });
- });
-
- it('counts the failure with its code and rethrows', async () => {
- const error = new ApplicationException(
- 'This application cannot be uninstalled.',
- ApplicationExceptionCode.FORBIDDEN,
- );
-
- jest
- .spyOn(applicationSyncService, 'uninstallApplication')
- .mockRejectedValueOnce(error);
-
- await expect(service.uninstallApplication(target)).rejects.toBe(error);
- expect(metricsService.incrementCounterBy).toHaveBeenCalledWith(
- expect.objectContaining({
- key: MetricsKeys.AppUninstallFailed,
- attributes: expect.objectContaining({
- error_code: ApplicationExceptionCode.FORBIDDEN,
- }),
- }),
- );
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/__tests__/application-manifest-apply.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/__tests__/application-manifest-apply.service.spec.ts
deleted file mode 100644
index e82ca9d9759..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/__tests__/application-manifest-apply.service.spec.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { type Manifest } from 'twenty-shared/application';
-
-import { ApplicationManifestApplyService } from 'src/engine/core-modules/application/application-manifest/application-manifest-apply.service';
-import { ApplicationSyncService } from 'src/engine/core-modules/application/application-manifest/application-sync.service';
-import { ApplicationRegistrationService } from 'src/engine/core-modules/application/application-registration/application-registration.service';
-import { SdkClientGenerationService } from 'src/engine/core-modules/sdk-client/sdk-client-generation.service';
-
-const WORKSPACE_ID = '20202020-0000-0000-0000-000000000001';
-const APPLICATION_ID = '20202020-0000-0000-0000-000000000002';
-
-const application = {
- id: APPLICATION_ID,
- universalIdentifier: 'test-app',
- version: '1.2.3',
-};
-
-const manifest = {
- application: { universalIdentifier: 'test-app' },
-} as Manifest;
-
-describe('ApplicationManifestApplyService', () => {
- let service: ApplicationManifestApplyService;
-
- const applicationSyncService = { synchronizeFromManifest: jest.fn() };
- const sdkClientGenerationService = {
- generateSdkClientForApplication: jest.fn(),
- };
- const applicationRegistrationService = {};
-
- beforeEach(async () => {
- jest.clearAllMocks();
- applicationSyncService.synchronizeFromManifest.mockResolvedValue({
- workspaceMigration: { actions: [] },
- hasSchemaMetadataChanged: false,
- });
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- ApplicationManifestApplyService,
- { provide: ApplicationSyncService, useValue: applicationSyncService },
- {
- provide: SdkClientGenerationService,
- useValue: sdkClientGenerationService,
- },
- {
- provide: ApplicationRegistrationService,
- useValue: applicationRegistrationService,
- },
- ],
- }).compile();
-
- service = module.get(ApplicationManifestApplyService);
- });
-
- it('regenerates the SDK client on install/upgrade even without schema changes', async () => {
- await service.applyManifestToWorkspace({
- workspaceId: WORKSPACE_ID,
- manifest,
- application,
- forceSdkClientGeneration: true,
- });
-
- expect(
- sdkClientGenerationService.generateSdkClientForApplication,
- ).toHaveBeenCalledTimes(1);
- expect(
- sdkClientGenerationService.generateSdkClientForApplication,
- ).toHaveBeenCalledWith({
- workspaceId: WORKSPACE_ID,
- applicationId: APPLICATION_ID,
- applicationUniversalIdentifier: 'test-app',
- trigger: 'manifest-sync',
- });
- });
-
- it('skips SDK client generation on dev sync when the schema is unchanged', async () => {
- await service.applyManifestToWorkspace({
- workspaceId: WORKSPACE_ID,
- manifest,
- application,
- });
-
- expect(
- sdkClientGenerationService.generateSdkClientForApplication,
- ).not.toHaveBeenCalled();
- });
-
- it('regenerates the SDK client on dev sync when the schema changed', async () => {
- applicationSyncService.synchronizeFromManifest.mockResolvedValue({
- workspaceMigration: { actions: [] },
- hasSchemaMetadataChanged: true,
- });
-
- await service.applyManifestToWorkspace({
- workspaceId: WORKSPACE_ID,
- manifest,
- application,
- });
-
- expect(
- sdkClientGenerationService.generateSdkClientForApplication,
- ).toHaveBeenCalledTimes(1);
- });
-
- it('regenerates the SDK client on dev sync first apply even without schema changes', async () => {
- await service.applyManifestToWorkspace({
- workspaceId: WORKSPACE_ID,
- manifest,
- application: { ...application, version: null },
- });
-
- expect(
- sdkClientGenerationService.generateSdkClientForApplication,
- ).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/__tests__/application-sync-media-capabilities.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/__tests__/application-sync-media-capabilities.service.spec.ts
deleted file mode 100644
index 6a77d575d0c..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/__tests__/application-sync-media-capabilities.service.spec.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { Test } from '@nestjs/testing';
-
-import { Readable } from 'stream';
-
-import {
- type ApplicationCapability,
- type Manifest,
-} from 'twenty-shared/application';
-
-import { ApplicationManifestMigrationService } from 'src/engine/core-modules/application/application-manifest/application-manifest-migration.service';
-import { ApplicationSyncService } from 'src/engine/core-modules/application/application-manifest/application-sync.service';
-import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
-import { ApplicationService } from 'src/engine/core-modules/application/application.service';
-import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
-
-describe('ApplicationSyncService media capabilities', () => {
- let service: ApplicationSyncService;
-
- const applicationService = {
- findOneApplicationWithRelationsOrThrow: jest.fn(),
- update: jest.fn(),
- };
-
- beforeEach(async () => {
- jest.clearAllMocks();
- applicationService.update.mockResolvedValue({
- applicationRegistrationId: null,
- });
-
- const module = await Test.createTestingModule({
- providers: [ApplicationSyncService],
- })
- .useMocker((token) => {
- if (token === ApplicationService) {
- return applicationService;
- }
-
- if (token === FileStorageService) {
- return {
- readFile: jest.fn(() =>
- Readable.from([
- Buffer.from(JSON.stringify({ version: '1.2.0' })),
- ]),
- ),
- };
- }
-
- if (token === ApplicationManifestMigrationService) {
- return {
- syncMetadataFromManifest: jest.fn().mockResolvedValue({
- workspaceMigration: { actions: [] },
- hasSchemaMetadataChanged: false,
- }),
- };
- }
-
- return {};
- })
- .compile();
-
- service = module.get(ApplicationSyncService);
- });
-
- it.each<{
- behavior: string;
- sourceType: ApplicationRegistrationSourceType;
- grantedCapabilities: ApplicationCapability[];
- requestedCapabilities?: ApplicationCapability[];
- expectedGrantedCapabilities: ApplicationCapability[];
- }>([
- {
- behavior: 'does not grant additional permissions on package updates',
- sourceType: ApplicationRegistrationSourceType.NPM,
- grantedCapabilities: ['microphone'],
- requestedCapabilities: ['microphone', 'camera'],
- expectedGrantedCapabilities: ['microphone'],
- },
- {
- behavior: 'preserves workspace-approved access when declarations change',
- sourceType: ApplicationRegistrationSourceType.TARBALL,
- grantedCapabilities: ['microphone', 'camera'],
- requestedCapabilities: ['camera'],
- expectedGrantedCapabilities: ['microphone', 'camera'],
- },
- {
- behavior: 'preserves runtime approval for legacy manifests',
- sourceType: ApplicationRegistrationSourceType.NPM,
- grantedCapabilities: ['microphone'],
- expectedGrantedCapabilities: ['microphone'],
- },
- {
- behavior: 'allows workspace-owned development apps to sync permissions',
- sourceType: ApplicationRegistrationSourceType.LOCAL,
- grantedCapabilities: [],
- requestedCapabilities: ['microphone', 'camera'],
- expectedGrantedCapabilities: ['microphone', 'camera'],
- },
- ])(
- '$behavior',
- async ({
- sourceType,
- grantedCapabilities,
- requestedCapabilities,
- expectedGrantedCapabilities,
- }) => {
- applicationService.findOneApplicationWithRelationsOrThrow.mockResolvedValue(
- {
- id: 'application-id',
- sourceType,
- grantedCapabilities,
- applicationRegistrationId: null,
- frontComponentSharedDependenciesChecksum: null,
- },
- );
-
- await service.synchronizeFromManifest({
- workspaceId: 'workspace-id',
- manifest: {
- application: {
- universalIdentifier: 'application-identifier',
- displayName: 'Recording app',
- requestedCapabilities,
- },
- } as Manifest,
- });
-
- expect(applicationService.update).toHaveBeenCalledWith(
- 'application-id',
- expect.objectContaining({
- grantedCapabilities: expectedGrantedCapabilities,
- }),
- );
- },
- );
-});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-translation/__tests__/application-translation-sync.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-translation/__tests__/application-translation-sync.service.spec.ts
deleted file mode 100644
index 8d908595bec..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/application-translation/__tests__/application-translation-sync.service.spec.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-import { getRepositoryToken } from '@nestjs/typeorm';
-
-import { ApplicationTranslationCacheService } from 'src/engine/core-modules/application/application-translation/application-translation-cache.service';
-import { ApplicationTranslationSyncService } from 'src/engine/core-modules/application/application-translation/application-translation-sync.service';
-import { ApplicationTranslationEntity } from 'src/engine/core-modules/application/application-translation/application-translation.entity';
-
-const APPLICATION_REGISTRATION_ID = '20202020-0000-0000-0000-000000000001';
-
-describe('ApplicationTranslationSyncService', () => {
- let service: ApplicationTranslationSyncService;
-
- const repository = {
- find: jest.fn(),
- update: jest.fn(),
- insert: jest.fn(),
- softDelete: jest.fn(),
- };
- const cacheService = { invalidate: jest.fn() };
-
- beforeEach(async () => {
- jest.clearAllMocks();
- repository.find.mockResolvedValue([]);
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- ApplicationTranslationSyncService,
- {
- provide: getRepositoryToken(ApplicationTranslationEntity),
- useValue: repository,
- },
- {
- provide: ApplicationTranslationCacheService,
- useValue: cacheService,
- },
- ],
- }).compile();
-
- service = module.get(ApplicationTranslationSyncService);
- });
-
- it('leaves stored translations alone when the manifest carries none', async () => {
- await service.syncFromManifest({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- translations: undefined,
- });
-
- expect(repository.find).toHaveBeenCalledTimes(0);
- expect(repository.update).toHaveBeenCalledTimes(0);
- expect(repository.insert).toHaveBeenCalledTimes(0);
- expect(repository.softDelete).toHaveBeenCalledTimes(0);
- expect(cacheService.invalidate).toHaveBeenCalledTimes(0);
- });
-
- it('applies the manifest when it declares translations', async () => {
- repository.find.mockResolvedValue([
- { id: 'row-de', locale: 'de-DE', deletedAt: null },
- ]);
-
- await service.syncFromManifest({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- translations: { 'fr-FR': { abc123: 'Entreprise' } },
- });
-
- expect(repository.insert).toHaveBeenCalledTimes(1);
- expect(repository.insert).toHaveBeenCalledWith({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- locale: 'fr-FR',
- messages: { abc123: 'Entreprise' },
- });
- expect(repository.softDelete).toHaveBeenCalledTimes(1);
- expect(repository.softDelete).toHaveBeenCalledWith(['row-de']);
- expect(cacheService.invalidate).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-upgrade/__tests__/application-upgrade.service.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-upgrade/__tests__/application-upgrade.service.spec.ts
deleted file mode 100644
index ff847a5fea5..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/application-upgrade/__tests__/application-upgrade.service.spec.ts
+++ /dev/null
@@ -1,412 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-import { getRepositoryToken } from '@nestjs/typeorm';
-
-import { ApplicationInstallService } from 'src/engine/core-modules/application/application-install/application-install.service';
-import { ApplicationVersionValidationService } from 'src/engine/core-modules/application/application-package/application-version-validation.service';
-import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
-import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
-import { ApplicationUpgradeService } from 'src/engine/core-modules/application/application-upgrade/application-upgrade.service';
-import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
-import {
- UPGRADE_WORKSPACE_APPLICATION_JOB_ENQUEUE_BATCH_SIZE,
- UPGRADE_WORKSPACE_APPLICATION_JOB_NAME,
- UPGRADE_WORKSPACE_APPLICATION_JOB_OPTIONS,
-} from 'src/engine/core-modules/application/jobs/upgrade-workspace-application.job-constants';
-import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
-import { getQueueToken } from 'src/engine/core-modules/message-queue/utils/get-queue-token.util';
-import { WorkspaceVersionService } from 'src/engine/workspace-manager/workspace-version/services/workspace-version.service';
-import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
-
-const APPLICATION_REGISTRATION_ID = '20202020-0000-0000-0000-000000000001';
-const OUTDATED_WORKSPACE_ID = '20202020-0000-0000-0000-000000000002';
-const UP_TO_DATE_WORKSPACE_ID = '20202020-0000-0000-0000-000000000003';
-const NON_PROVISIONED_WORKSPACE_ID = '20202020-0000-0000-0000-000000000004';
-const BEHIND_SERVER_VERSION_WORKSPACE_ID =
- '20202020-0000-0000-0000-100000000000';
-const TARGET_VERSION = '2.0.0';
-
-const appRegistration = {
- id: APPLICATION_REGISTRATION_ID,
- universalIdentifier: 'test-app',
- sourceType: ApplicationRegistrationSourceType.NPM,
- latestAvailableVersion: TARGET_VERSION,
-} as ApplicationRegistrationEntity;
-
-const buildApplication = ({
- workspaceId,
- version,
- autoUpgrade = true,
-}: {
- workspaceId: string;
- version: string | null;
- autoUpgrade?: boolean;
-}) =>
- ({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId,
- version,
- autoUpgrade,
- }) as ApplicationEntity;
-
-describe('ApplicationUpgradeService', () => {
- let service: ApplicationUpgradeService;
-
- const appRegistrationRepository = {
- findOne: jest.fn(),
- findOneOrFail: jest.fn(),
- };
- const applicationRepository = { find: jest.fn(), findOne: jest.fn() };
- const applicationInstallService = { installApplication: jest.fn() };
- const workspaceVersionService = { getProvisionedWorkspaceIds: jest.fn() };
- const applicationVersionValidationService = {
- validateWorkspaceCompatibility: jest.fn(),
- };
- const applicationUpgradeQueueService = { bulkAdd: jest.fn() };
-
- beforeEach(async () => {
- jest.clearAllMocks();
-
- appRegistrationRepository.findOne.mockResolvedValue(appRegistration);
- appRegistrationRepository.findOneOrFail.mockResolvedValue(appRegistration);
- workspaceVersionService.getProvisionedWorkspaceIds.mockResolvedValue([
- OUTDATED_WORKSPACE_ID,
- UP_TO_DATE_WORKSPACE_ID,
- ]);
- applicationUpgradeQueueService.bulkAdd.mockImplementation(
- (_jobName: string, jobs: unknown[]) =>
- jobs.map((_job, index) => `job-${index}`),
- );
- applicationInstallService.installApplication.mockResolvedValue(true);
- applicationVersionValidationService.validateWorkspaceCompatibility.mockImplementation(
- async ({ workspaceId }: { workspaceId: string }) =>
- workspaceId === BEHIND_SERVER_VERSION_WORKSPACE_ID
- ? {
- compatible: false,
- reason: 'WORKSPACE_INCOMPATIBLE',
- message: 'behind',
- }
- : { compatible: true },
- );
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- ApplicationUpgradeService,
- {
- provide: getRepositoryToken(ApplicationRegistrationEntity),
- useValue: appRegistrationRepository,
- },
- {
- provide: getRepositoryToken(ApplicationEntity),
- useValue: applicationRepository,
- },
- {
- provide: getWorkspaceScopedRepositoryToken(ApplicationEntity),
- useValue: applicationRepository,
- },
- {
- provide: ApplicationInstallService,
- useValue: applicationInstallService,
- },
- {
- provide: ApplicationVersionValidationService,
- useValue: applicationVersionValidationService,
- },
- {
- provide: WorkspaceVersionService,
- useValue: workspaceVersionService,
- },
- {
- provide: getQueueToken(MessageQueue.applicationUpgradeQueue),
- useValue: applicationUpgradeQueueService,
- },
- ],
- }).compile();
-
- service = module.get(ApplicationUpgradeService);
- });
-
- describe('enqueueApplicationUpgrades', () => {
- it('enqueues one job per outdated installation on a provisioned workspace', async () => {
- applicationRepository.find.mockResolvedValue([
- buildApplication({
- workspaceId: OUTDATED_WORKSPACE_ID,
- version: '1.0.0',
- }),
- buildApplication({
- workspaceId: UP_TO_DATE_WORKSPACE_ID,
- version: TARGET_VERSION,
- }),
- buildApplication({
- workspaceId: NON_PROVISIONED_WORKSPACE_ID,
- version: '1.0.0',
- }),
- ]);
-
- const jobIds = await service.enqueueApplicationUpgrades({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- onlyAutoUpgrade: true,
- });
-
- expect(jobIds).toEqual(['job-0']);
- expect(applicationUpgradeQueueService.bulkAdd).toHaveBeenCalledTimes(1);
- expect(applicationUpgradeQueueService.bulkAdd).toHaveBeenCalledWith(
- UPGRADE_WORKSPACE_APPLICATION_JOB_NAME,
- [
- {
- data: {
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId: OUTDATED_WORKSPACE_ID,
- onlyAutoUpgrade: true,
- },
- },
- ],
- UPGRADE_WORKSPACE_APPLICATION_JOB_OPTIONS,
- );
- });
-
- it('does not enqueue a workspace that has not finished the server upgrade the target version requires', async () => {
- workspaceVersionService.getProvisionedWorkspaceIds.mockResolvedValue([
- OUTDATED_WORKSPACE_ID,
- BEHIND_SERVER_VERSION_WORKSPACE_ID,
- ]);
- applicationRepository.find.mockResolvedValue([
- buildApplication({
- workspaceId: OUTDATED_WORKSPACE_ID,
- version: '1.0.0',
- }),
- buildApplication({
- workspaceId: BEHIND_SERVER_VERSION_WORKSPACE_ID,
- version: '1.0.0',
- }),
- ]);
-
- const jobIds = await service.enqueueApplicationUpgrades({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- onlyAutoUpgrade: true,
- });
-
- expect(jobIds).toEqual(['job-0']);
- expect(applicationUpgradeQueueService.bulkAdd).toHaveBeenCalledWith(
- UPGRADE_WORKSPACE_APPLICATION_JOB_NAME,
- [
- {
- data: {
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId: OUTDATED_WORKSPACE_ID,
- onlyAutoUpgrade: true,
- },
- },
- ],
- UPGRADE_WORKSPACE_APPLICATION_JOB_OPTIONS,
- );
- });
-
- it('splits a large fan-out into several bulk adds', async () => {
- const workspaceIds = Array.from(
- { length: UPGRADE_WORKSPACE_APPLICATION_JOB_ENQUEUE_BATCH_SIZE + 1 },
- (_, index) =>
- `20202020-0000-0000-0000-${String(index).padStart(12, '0')}`,
- );
-
- workspaceVersionService.getProvisionedWorkspaceIds.mockResolvedValue(
- workspaceIds,
- );
- applicationRepository.find.mockResolvedValue(
- workspaceIds.map((workspaceId) =>
- buildApplication({ workspaceId, version: '1.0.0' }),
- ),
- );
-
- const jobIds = await service.enqueueApplicationUpgrades({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- });
-
- expect(jobIds).toHaveLength(workspaceIds.length);
- expect(applicationUpgradeQueueService.bulkAdd).toHaveBeenCalledTimes(2);
- expect(
- applicationUpgradeQueueService.bulkAdd.mock.calls[0][1],
- ).toHaveLength(UPGRADE_WORKSPACE_APPLICATION_JOB_ENQUEUE_BATCH_SIZE);
- expect(
- applicationUpgradeQueueService.bulkAdd.mock.calls[1][1],
- ).toHaveLength(1);
- });
-
- it('enqueues nothing when every installation already runs the latest version', async () => {
- applicationRepository.find.mockResolvedValue([
- buildApplication({
- workspaceId: UP_TO_DATE_WORKSPACE_ID,
- version: TARGET_VERSION,
- }),
- ]);
-
- const jobIds = await service.enqueueApplicationUpgrades({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- });
-
- expect(jobIds).toEqual([]);
- expect(applicationUpgradeQueueService.bulkAdd).not.toHaveBeenCalled();
- });
-
- it('enqueues nothing when the registration has no latest available version', async () => {
- appRegistrationRepository.findOneOrFail.mockResolvedValue({
- ...appRegistration,
- latestAvailableVersion: null,
- });
-
- const jobIds = await service.enqueueApplicationUpgrades({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- });
-
- expect(jobIds).toEqual([]);
- expect(applicationRepository.find).not.toHaveBeenCalled();
- expect(applicationUpgradeQueueService.bulkAdd).not.toHaveBeenCalled();
- });
- });
-
- describe('upgradeWorkspaceApplicationToLatestVersion', () => {
- it('installs the latest available version on an outdated workspace', async () => {
- applicationRepository.findOne.mockResolvedValue(
- buildApplication({
- workspaceId: OUTDATED_WORKSPACE_ID,
- version: '1.0.0',
- }),
- );
-
- await service.upgradeWorkspaceApplicationToLatestVersion({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId: OUTDATED_WORKSPACE_ID,
- onlyAutoUpgrade: false,
- });
-
- expect(applicationInstallService.installApplication).toHaveBeenCalledWith(
- {
- appRegistrationId: APPLICATION_REGISTRATION_ID,
- version: TARGET_VERSION,
- workspaceId: OUTDATED_WORKSPACE_ID,
- },
- );
- });
-
- it('installs the latest available version on a workspace whose install never completed', async () => {
- applicationRepository.findOne.mockResolvedValue(
- buildApplication({ workspaceId: OUTDATED_WORKSPACE_ID, version: null }),
- );
-
- await service.upgradeWorkspaceApplicationToLatestVersion({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId: OUTDATED_WORKSPACE_ID,
- onlyAutoUpgrade: false,
- });
-
- expect(
- applicationInstallService.installApplication,
- ).toHaveBeenCalledTimes(1);
- });
-
- it('skips an automatic upgrade on a workspace that disabled auto upgrade after the fan-out', async () => {
- applicationRepository.findOne.mockResolvedValue(
- buildApplication({
- workspaceId: OUTDATED_WORKSPACE_ID,
- version: '1.0.0',
- autoUpgrade: false,
- }),
- );
-
- await service.upgradeWorkspaceApplicationToLatestVersion({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId: OUTDATED_WORKSPACE_ID,
- onlyAutoUpgrade: true,
- });
-
- expect(
- applicationInstallService.installApplication,
- ).not.toHaveBeenCalled();
- });
-
- it('still upgrades a workspace that disabled auto upgrade when the upgrade is manual', async () => {
- applicationRepository.findOne.mockResolvedValue(
- buildApplication({
- workspaceId: OUTDATED_WORKSPACE_ID,
- version: '1.0.0',
- autoUpgrade: false,
- }),
- );
-
- await service.upgradeWorkspaceApplicationToLatestVersion({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId: OUTDATED_WORKSPACE_ID,
- onlyAutoUpgrade: false,
- });
-
- expect(
- applicationInstallService.installApplication,
- ).toHaveBeenCalledTimes(1);
- });
-
- it('skips a workspace that already runs the latest available version', async () => {
- applicationRepository.findOne.mockResolvedValue(
- buildApplication({
- workspaceId: UP_TO_DATE_WORKSPACE_ID,
- version: TARGET_VERSION,
- }),
- );
-
- await service.upgradeWorkspaceApplicationToLatestVersion({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId: UP_TO_DATE_WORKSPACE_ID,
- onlyAutoUpgrade: false,
- });
-
- expect(
- applicationInstallService.installApplication,
- ).not.toHaveBeenCalled();
- });
-
- it('skips a workspace where the application is no longer installed', async () => {
- applicationRepository.findOne.mockResolvedValue(null);
-
- await service.upgradeWorkspaceApplicationToLatestVersion({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId: OUTDATED_WORKSPACE_ID,
- onlyAutoUpgrade: false,
- });
-
- expect(
- applicationInstallService.installApplication,
- ).not.toHaveBeenCalled();
- });
-
- it('skips when the registration no longer exists', async () => {
- appRegistrationRepository.findOne.mockResolvedValue(null);
-
- await service.upgradeWorkspaceApplicationToLatestVersion({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId: OUTDATED_WORKSPACE_ID,
- onlyAutoUpgrade: false,
- });
-
- expect(applicationRepository.findOne).not.toHaveBeenCalled();
- expect(
- applicationInstallService.installApplication,
- ).not.toHaveBeenCalled();
- });
-
- it('skips when the registration has no latest available version', async () => {
- appRegistrationRepository.findOne.mockResolvedValue({
- ...appRegistration,
- latestAvailableVersion: null,
- });
-
- await service.upgradeWorkspaceApplicationToLatestVersion({
- applicationRegistrationId: APPLICATION_REGISTRATION_ID,
- workspaceId: OUTDATED_WORKSPACE_ID,
- onlyAutoUpgrade: false,
- });
-
- expect(applicationRepository.findOne).not.toHaveBeenCalled();
- expect(
- applicationInstallService.installApplication,
- ).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/create-sso-connected-account.service.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/services/create-sso-connected-account.service.spec.ts
deleted file mode 100644
index 425ac33f185..00000000000
--- a/packages/twenty-server/src/engine/core-modules/auth/services/create-sso-connected-account.service.spec.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-import { getRepositoryToken } from '@nestjs/typeorm';
-
-import { ConnectedAccountProvider } from 'twenty-shared/types';
-import { type Repository } from 'typeorm';
-
-import { CreateSsoConnectedAccountService } from 'src/engine/core-modules/auth/services/create-sso-connected-account.service';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
-import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
-
-describe('CreateSsoConnectedAccountService', () => {
- let createSsoConnectedAccountService: CreateSsoConnectedAccountService;
- let connectedAccountRepository: Repository<ConnectedAccountEntity>;
- let userWorkspaceRepository: Repository<UserWorkspaceEntity>;
-
- beforeEach(async () => {
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- CreateSsoConnectedAccountService,
- {
- provide: getRepositoryToken(ConnectedAccountEntity),
- useValue: {
- findOneBy: jest.fn(),
- save: jest.fn(),
- update: jest.fn(),
- },
- },
- {
- provide: getRepositoryToken(UserWorkspaceEntity),
- useValue: {
- findOneBy: jest.fn(),
- },
- },
- ],
- }).compile();
-
- createSsoConnectedAccountService =
- module.get<CreateSsoConnectedAccountService>(
- CreateSsoConnectedAccountService,
- );
- connectedAccountRepository = module.get<Repository<ConnectedAccountEntity>>(
- getRepositoryToken(ConnectedAccountEntity),
- );
- userWorkspaceRepository = module.get<Repository<UserWorkspaceEntity>>(
- getRepositoryToken(UserWorkspaceEntity),
- );
- });
-
- it('should preserve mailbox scopes when updating an SSO connected account', async () => {
- const existingScopes = ['Mail.ReadWrite', 'Mail.Send', 'User.Read'];
-
- jest.spyOn(userWorkspaceRepository, 'findOneBy').mockResolvedValue({
- id: 'user-workspace-id',
- } as UserWorkspaceEntity);
- jest.spyOn(connectedAccountRepository, 'findOneBy').mockResolvedValue({
- id: 'connected-account-id',
- scopes: existingScopes,
- } as ConnectedAccountEntity);
-
- await createSsoConnectedAccountService.createOrUpdateSsoConnectedAccount({
- workspaceId: 'workspace-id',
- userId: 'user-id',
- handle: '[email protected]',
- provider: ConnectedAccountProvider.MICROSOFT,
- scopes: ['User.Read'],
- });
-
- expect(connectedAccountRepository.update).toHaveBeenCalledTimes(1);
- expect(connectedAccountRepository.update).toHaveBeenCalledWith(
- 'connected-account-id',
- expect.objectContaining({
- scopes: existingScopes,
- }),
- );
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.spec.ts
deleted file mode 100644
index fbcda789387..00000000000
--- a/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.spec.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { AuthExceptionCode } from 'src/engine/core-modules/auth/auth.exception';
-import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
-
-import { LoginTokenService } from './login-token.service';
-
-describe('LoginTokenService', () => {
- const jwtWrapperService = {
- decode: jest.fn(),
- signAsyncOrThrow: jest.fn(),
- verifyJwtToken: jest.fn(),
- };
- const twentyConfigService = {
- get: jest.fn().mockReturnValue('1h'),
- };
- const service = new LoginTokenService(
- jwtWrapperService as never,
- twentyConfigService as never,
- );
-
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('does not generate a login token without an authentication provider', async () => {
- await expect(
- service.generateLoginToken(
- 'workspace-id',
- undefined as never,
- ),
- ).rejects.toMatchObject({ code: AuthExceptionCode.INVALID_INPUT });
-
- expect(jwtWrapperService.signAsyncOrThrow).not.toHaveBeenCalled();
- });
-
- it('rejects a login token without an authentication provider', async () => {
- jwtWrapperService.decode.mockReturnValue({
- type: JwtTokenTypeEnum.LOGIN,
- workspaceId: 'workspace-id',
- });
-
- await expect(service.verifyLoginToken('login-token')).rejects.toMatchObject(
- {
- code: AuthExceptionCode.UNAUTHENTICATED,
- },
- );
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/__tests__/billing-entitlement-sync.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/__tests__/billing-entitlement-sync.service.spec.ts
deleted file mode 100644
index c8ab50bfe66..00000000000
--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/__tests__/billing-entitlement-sync.service.spec.ts
+++ /dev/null
@@ -1,300 +0,0 @@
-/* @license Enterprise */
-
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { BillingEntitlementSyncService } from 'src/engine/core-modules/billing-webhook/services/billing-entitlement-sync.service';
-import { BillingEntitlementEntity } from 'src/engine/core-modules/billing/entities/billing-entitlement.entity';
-import { BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';
-import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
-import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
-import { RowLevelPermissionPredicateGroupService } from 'src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate-group.service';
-import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-
-const WORKSPACE_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
-const STRIPE_CUSTOMER_ID = 'cus_test';
-const RLS_LOOKUP_KEY = 'RLS';
-
-describe('BillingEntitlementSyncService', () => {
- let service: BillingEntitlementSyncService;
-
- const billingEntitlementRepository = {
- find: jest.fn(),
- upsert: jest.fn(),
- };
-
- const rowLevelPermissionPredicateGroupService = {
- deleteAllRowLevelPermissionPredicateGroups: jest.fn(),
- };
-
- const usageLimitQuotaService = {
- dropIntraWorkspaceLimitCounters: jest.fn(),
- };
-
- const workspaceCacheService = {
- invalidateAndRecompute: jest.fn(),
- };
-
- // A real single-holder lock rather than a pass-through, so a test that runs
- // two syncs concurrently exercises the serialization instead of asserting
- // that a stub was called. Queued rather than spin-waiting so ordering is
- // deterministic.
- const heldLockKeys = new Set<string>();
- const lockQueueByKey = new Map<string, Promise<unknown>>();
- const cacheLockService = {
- withLock: jest.fn(<TResult>(fn: () => Promise<TResult>, key: string) => {
- const runWhenFree = (lockQueueByKey.get(key) ?? Promise.resolve()).then(
- async () => {
- heldLockKeys.add(key);
- try {
- return await fn();
- } finally {
- heldLockKeys.delete(key);
- }
- },
- );
-
- lockQueueByKey.set(
- key,
- runWhenFree.catch(() => undefined),
- );
-
- return runWhenFree;
- }),
- };
-
- const givenStoredEntitlements = (
- entitlements: { key: BillingEntitlementKey; value: boolean }[],
- ) => billingEntitlementRepository.find.mockResolvedValue(entitlements);
-
- beforeEach(async () => {
- jest.clearAllMocks();
- heldLockKeys.clear();
- lockQueueByKey.clear();
- billingEntitlementRepository.upsert.mockResolvedValue(undefined);
- workspaceCacheService.invalidateAndRecompute.mockResolvedValue(undefined);
- usageLimitQuotaService.dropIntraWorkspaceLimitCounters.mockResolvedValue(
- undefined,
- );
- rowLevelPermissionPredicateGroupService.deleteAllRowLevelPermissionPredicateGroups.mockResolvedValue(
- undefined,
- );
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- BillingEntitlementSyncService,
- {
- provide: getWorkspaceScopedRepositoryToken(BillingEntitlementEntity),
- useValue: billingEntitlementRepository,
- },
- {
- provide: RowLevelPermissionPredicateGroupService,
- useValue: rowLevelPermissionPredicateGroupService,
- },
- {
- provide: UsageLimitQuotaService,
- useValue: usageLimitQuotaService,
- },
- {
- provide: CacheLockService,
- useValue: cacheLockService,
- },
- {
- provide: WorkspaceCacheService,
- useValue: workspaceCacheService,
- },
- ],
- }).compile();
-
- service = module.get<BillingEntitlementSyncService>(
- BillingEntitlementSyncService,
- );
- });
-
- const syncEntitlements = (activeLookupKeys: string[]) =>
- service.syncEntitlements({
- workspaceId: WORKSPACE_ID,
- stripeCustomerId: STRIPE_CUSTOMER_ID,
- activeLookupKeys,
- });
-
- it('drops usage-limit counters once when two syncs observe the same grant', async () => {
- givenStoredEntitlements([
- { key: BillingEntitlementKey.USAGE_LIMIT, value: false },
- ]);
-
- // Once the first sync commits, the stored rows read as granted, so the
- // second sync sees no transition. Without the lock both would read the
- // pre-commit state and both would drop, and the later drop would discard
- // usage already recorded under enforcement.
- billingEntitlementRepository.upsert.mockImplementation(async () => {
- givenStoredEntitlements([
- { key: BillingEntitlementKey.USAGE_LIMIT, value: true },
- ]);
- });
-
- await Promise.all([
- syncEntitlements([BillingEntitlementKey.USAGE_LIMIT]),
- syncEntitlements([BillingEntitlementKey.USAGE_LIMIT]),
- ]);
-
- expect(
- usageLimitQuotaService.dropIntraWorkspaceLimitCounters,
- ).toHaveBeenCalledTimes(1);
- });
-
- it('never deletes predicates after a concurrent grant has committed', async () => {
- let isRlsGrantedInStore = true;
-
- billingEntitlementRepository.find.mockImplementation(async () => [
- { key: BillingEntitlementKey.RLS, value: isRlsGrantedInStore },
- ]);
-
- billingEntitlementRepository.upsert.mockImplementation(
- async (
- _workspaceId: string,
- entitlements: { key: BillingEntitlementKey; value: boolean }[],
- ) => {
- isRlsGrantedInStore =
- entitlements.find(
- (entitlement) => entitlement.key === BillingEntitlementKey.RLS,
- )?.value === true;
- },
- );
-
- // Unserialized, both syncs read the same granted state, then each await
- // hands over: the revoke's delete lands after the grant has committed and
- // strips the predicates of a workspace whose feature is back on.
- await Promise.all([
- syncEntitlements([]),
- syncEntitlements([RLS_LOOKUP_KEY]),
- ]);
-
- const grantCommitOrder =
- billingEntitlementRepository.upsert.mock.calls.flatMap((call, index) =>
- call[1].some(
- (entitlement: { key: BillingEntitlementKey; value: boolean }) =>
- entitlement.key === BillingEntitlementKey.RLS && entitlement.value,
- )
- ? [
- billingEntitlementRepository.upsert.mock.invocationCallOrder[
- index
- ],
- ]
- : [],
- );
-
- const deleteOrders =
- rowLevelPermissionPredicateGroupService
- .deleteAllRowLevelPermissionPredicateGroups.mock.invocationCallOrder;
-
- expect(isRlsGrantedInStore).toBe(true);
- expect(grantCommitOrder).toHaveLength(1);
- expect(
- deleteOrders.filter((order) => order > grantCommitOrder[0]),
- ).toHaveLength(0);
- });
-
- it('locks on a key scoped to the workspace', async () => {
- givenStoredEntitlements([]);
-
- const otherWorkspaceId = '20202020-1c25-4d02-bf25-6aeccf7ea420';
- const heldKeysDuringOtherWorkspaceUpsert: string[] = [];
-
- billingEntitlementRepository.upsert.mockImplementation(async () => {
- heldKeysDuringOtherWorkspaceUpsert.push(...heldLockKeys);
- });
-
- await Promise.all([
- syncEntitlements([]),
- service.syncEntitlements({
- workspaceId: otherWorkspaceId,
- stripeCustomerId: STRIPE_CUSTOMER_ID,
- activeLookupKeys: [],
- }),
- ]);
-
- expect(cacheLockService.withLock.mock.calls.map((call) => call[1])).toEqual(
- [
- `billing-entitlement-state:${WORKSPACE_ID}`,
- `billing-entitlement-state:${otherWorkspaceId}`,
- ],
- );
-
- // Two workspaces hold their own keys at once. A constant key would
- // serialize them and never show both held together.
- expect(new Set(heldKeysDuringOtherWorkspaceUpsert).size).toBe(2);
- });
-
- it('refreshes entitlements after persistence and before RLS cleanup', async () => {
- givenStoredEntitlements([]);
-
- await syncEntitlements([]);
-
- expect(workspaceCacheService.invalidateAndRecompute).toHaveBeenCalledWith(
- WORKSPACE_ID,
- ['billingEntitlements'],
- );
- expect(
- workspaceCacheService.invalidateAndRecompute.mock.invocationCallOrder[0],
- ).toBeGreaterThan(
- billingEntitlementRepository.upsert.mock.invocationCallOrder[0],
- );
- expect(
- workspaceCacheService.invalidateAndRecompute.mock.invocationCallOrder[0],
- ).toBeLessThan(
- rowLevelPermissionPredicateGroupService
- .deleteAllRowLevelPermissionPredicateGroups.mock.invocationCallOrder[0],
- );
- });
-
- it('retries cache refresh even when the rows already match after a failed refresh', async () => {
- givenStoredEntitlements([]);
- billingEntitlementRepository.upsert.mockImplementation(async () => {
- givenStoredEntitlements([
- { key: BillingEntitlementKey.USAGE_LIMIT, value: true },
- ]);
- });
- workspaceCacheService.invalidateAndRecompute.mockRejectedValueOnce(
- new Error('cache unavailable'),
- );
-
- await expect(
- syncEntitlements([BillingEntitlementKey.USAGE_LIMIT]),
- ).rejects.toThrow('cache unavailable');
- await syncEntitlements([BillingEntitlementKey.USAGE_LIMIT]);
-
- expect(workspaceCacheService.invalidateAndRecompute).toHaveBeenCalledTimes(
- 2,
- );
- expect(
- usageLimitQuotaService.dropIntraWorkspaceLimitCounters,
- ).toHaveBeenCalledTimes(1);
- });
-
- it('does not refresh the cache if persisting entitlements fails', async () => {
- givenStoredEntitlements([]);
- billingEntitlementRepository.upsert.mockRejectedValueOnce(
- new Error('database unavailable'),
- );
-
- await expect(syncEntitlements([])).rejects.toThrow('database unavailable');
-
- expect(workspaceCacheService.invalidateAndRecompute).not.toHaveBeenCalled();
- });
-
- it('holds the lock for the whole transition', async () => {
- givenStoredEntitlements([]);
-
- let lockHeldDuringUpsert = false;
-
- billingEntitlementRepository.upsert.mockImplementation(async () => {
- lockHeldDuringUpsert = heldLockKeys.size === 1;
- });
-
- await syncEntitlements([]);
-
- expect(lockHeldDuringUpsert).toBe(true);
- expect(heldLockKeys.size).toBe(0);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__tests__/billing-subscription-update.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__tests__/billing-subscription-update.service.spec.ts
deleted file mode 100644
index d665a9b5da6..00000000000
--- a/packages/twenty-server/src/engine/core-modules/billing/services/__tests__/billing-subscription-update.service.spec.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-/* @license Enterprise */
-
-import { Test, type TestingModule } from '@nestjs/testing';
-import { getRepositoryToken } from '@nestjs/typeorm';
-
-import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
-import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';
-import { BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';
-import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';
-import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';
-import { SubscriptionUpdateType } from 'src/engine/core-modules/billing/types/billing-subscription-update.type';
-import { BillingPriceService } from 'src/engine/core-modules/billing/services/billing-price.service';
-import { BillingProductService } from 'src/engine/core-modules/billing/services/billing-product.service';
-import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
-import { BillingSubscriptionUpdateService } from 'src/engine/core-modules/billing/services/billing-subscription-update.service';
-import { StripeInvoiceService } from 'src/engine/core-modules/billing/stripe/services/stripe-invoice.service';
-import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';
-import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
-
-type FixtureProduct = {
- active: true;
- stripeProductId: string;
- metadata: { productKey: BillingProductKey; planKey: BillingPlanKey };
- billingPrices: BillingPriceEntity[];
-};
-
-const baseProduct: FixtureProduct = {
- active: true,
- stripeProductId: 'prod_base',
- metadata: {
- productKey: BillingProductKey.BASE_PRODUCT,
- planKey: BillingPlanKey.PRO,
- },
- billingPrices: [],
-};
-
-const resourceCreditProduct: FixtureProduct = {
- active: true,
- stripeProductId: 'prod_credits',
- metadata: {
- productKey: BillingProductKey.RESOURCE_CREDIT,
- planKey: BillingPlanKey.PRO,
- },
- billingPrices: [],
-};
-
-const buildPrice = ({
- stripePriceId,
- interval,
- product,
- creditAmount,
-}: {
- stripePriceId: string;
- interval: SubscriptionInterval;
- product: FixtureProduct;
- creditAmount?: number;
-}) =>
- ({
- stripePriceId,
- interval,
- active: true,
- metadata: creditAmount ? { credit_amount: String(creditAmount) } : {},
- billingProduct: product,
- }) as unknown as BillingPriceEntity;
-
-const baseProductMonth = buildPrice({
- stripePriceId: 'price_base_month',
- interval: SubscriptionInterval.Month,
- product: baseProduct,
-});
-const baseProductYear = buildPrice({
- stripePriceId: 'price_base_year',
- interval: SubscriptionInterval.Year,
- product: baseProduct,
-});
-
-const creditMonthPackages = [50, 100, 200].map((creditAmount) =>
- buildPrice({
- stripePriceId: `price_credits_month_${creditAmount}`,
- interval: SubscriptionInterval.Month,
- product: resourceCreditProduct,
- creditAmount,
- }),
-);
-const creditYearPackages = [600, 1200, 2400].map((creditAmount) =>
- buildPrice({
- stripePriceId: `price_credits_year_${creditAmount}`,
- interval: SubscriptionInterval.Year,
- product: resourceCreditProduct,
- creditAmount,
- }),
-);
-
-const allPrices = [
- baseProductMonth,
- baseProductYear,
- ...creditMonthPackages,
- ...creditYearPackages,
-];
-
-baseProduct.billingPrices.push(baseProductMonth, baseProductYear);
-resourceCreditProduct.billingPrices.push(
- ...creditMonthPackages,
- ...creditYearPackages,
-);
-
-describe('BillingSubscriptionUpdateService interval switch', () => {
- let service: BillingSubscriptionUpdateService;
-
- const billingPriceRepository = {
- findOneOrFail: jest.fn(
- ({ where }: { where: { stripePriceId: string } }) => {
- const price = allPrices.find(
- (candidate) => candidate.stripePriceId === where.stripePriceId,
- );
-
- if (!price) throw new Error(`no fixture for ${where.stripePriceId}`);
-
- return Promise.resolve(price);
- },
- ),
- };
-
- const billingProductService = {
- getProductPrices: jest.fn(
- ({ interval }: { interval: SubscriptionInterval }) =>
- Promise.resolve(
- allPrices.filter((price) => price.interval === interval),
- ),
- ),
- };
-
- const noop = {};
-
- beforeEach(async () => {
- jest.clearAllMocks();
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- BillingSubscriptionUpdateService,
- {
- provide: BillingPriceService,
- useValue: new BillingPriceService(
- noop as never,
- billingPriceRepository as never,
- billingProductService as never,
- ),
- },
- { provide: BillingProductService, useValue: billingProductService },
- {
- provide: getRepositoryToken(BillingPriceEntity),
- useValue: billingPriceRepository,
- },
- {
- provide: getWorkspaceScopedRepositoryToken(BillingSubscriptionEntity),
- useValue: noop,
- },
- { provide: StripeSubscriptionService, useValue: noop },
- { provide: StripeInvoiceService, useValue: noop },
- { provide: StripeSubscriptionScheduleService, useValue: noop },
- { provide: BillingSubscriptionService, useValue: noop },
- { provide: WorkspaceOrmManager, useValue: noop },
- ],
- }).compile();
-
- service = module.get<BillingSubscriptionUpdateService>(
- BillingSubscriptionUpdateService,
- );
- });
-
- it('moves a monthly package to the yearly package worth twelve months of it', async () => {
- const result = await service.computeSubscriptionPricesUpdate(
- {
- type: SubscriptionUpdateType.INTERVAL,
- newInterval: SubscriptionInterval.Year,
- },
- {
- baseProductPriceId: 'price_base_month',
- resourceCreditPriceId: 'price_credits_month_100',
- seats: 3,
- } as never,
- );
-
- expect(result.resourceCreditPriceId).toBe('price_credits_year_1200');
- expect(result.baseProductPriceId).toBe('price_base_year');
- });
-
- it('moves a yearly package back to the monthly package worth a twelfth of it', async () => {
- const result = await service.computeSubscriptionPricesUpdate(
- {
- type: SubscriptionUpdateType.INTERVAL,
- newInterval: SubscriptionInterval.Month,
- },
- {
- baseProductPriceId: 'price_base_year',
- resourceCreditPriceId: 'price_credits_year_1200',
- seats: 3,
- } as never,
- );
-
- expect(result.resourceCreditPriceId).toBe('price_credits_month_100');
- expect(result.baseProductPriceId).toBe('price_base_month');
- });
-
- it('switches interval on a product holding several packages at that interval', async () => {
- expect(
- resourceCreditProduct.billingPrices.filter(
- (price) => price.interval === SubscriptionInterval.Year,
- ),
- ).toHaveLength(3);
-
- await expect(
- service.computeSubscriptionPricesUpdate(
- {
- type: SubscriptionUpdateType.INTERVAL,
- newInterval: SubscriptionInterval.Year,
- },
- {
- baseProductPriceId: 'price_base_month',
- resourceCreditPriceId: 'price_credits_month_100',
- seats: 1,
- } as never,
- ),
- ).resolves.toBeDefined();
- });
-
- it('leaves the prices untouched when the interval already matches', async () => {
- const currentPrices = {
- baseProductPriceId: 'price_base_month',
- resourceCreditPriceId: 'price_credits_month_100',
- seats: 2,
- };
-
- const result = await service.computeSubscriptionPricesUpdate(
- {
- type: SubscriptionUpdateType.INTERVAL,
- newInterval: SubscriptionInterval.Month,
- },
- currentPrices as never,
- );
-
- expect(result).toEqual(currentPrices);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__tests__/workspace-billing-entitlements-cache.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__tests__/workspace-billing-entitlements-cache.service.spec.ts
deleted file mode 100644
index f466d63e741..00000000000
--- a/packages/twenty-server/src/engine/core-modules/billing/services/__tests__/workspace-billing-entitlements-cache.service.spec.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-/* @license Enterprise */
-
-import { Test } from '@nestjs/testing';
-import { DataSource } from 'typeorm';
-
-import { BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';
-import { WorkspaceBillingEntitlementsCacheService } from 'src/engine/core-modules/billing/services/workspace-billing-entitlements-cache.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { WorkspaceCacheRowsBatchLoader } from 'src/engine/workspace-cache/services/workspace-cache-rows-batch-loader';
-
-const WORKSPACE_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
-
-describe('WorkspaceBillingEntitlementsCacheService', () => {
- let service: WorkspaceBillingEntitlementsCacheService;
- const twentyConfigService = { get: jest.fn() };
-
- const createService = async (isBillingEnabled: boolean) => {
- twentyConfigService.get.mockReturnValue(isBillingEnabled);
- const module = await Test.createTestingModule({
- providers: [
- WorkspaceBillingEntitlementsCacheService,
- { provide: TwentyConfigService, useValue: twentyConfigService },
- ],
- }).compile();
-
- return module.get(WorkspaceBillingEntitlementsCacheService);
- };
-
- beforeEach(async () => {
- service = await createService(true);
- });
-
- it('preserves both granted and revoked entitlements', () => {
- expect(
- service.computeForCache({
- workspaceId: WORKSPACE_ID,
- rows: {
- billingEntitlement: [
- { key: BillingEntitlementKey.USAGE_LIMIT, value: true },
- { key: BillingEntitlementKey.RLS, value: false },
- ],
- },
- }),
- ).toEqual({
- [BillingEntitlementKey.USAGE_LIMIT]: true,
- [BillingEntitlementKey.RLS]: false,
- });
- });
-
- it('returns an empty map for a workspace without entitlement rows', () => {
- expect(
- service.computeForCache({
- workspaceId: WORKSPACE_ID,
- rows: { billingEntitlement: [] },
- }),
- ).toEqual({});
- });
-
- it('loads no rows when billing entities are not registered', async () => {
- service = await createService(false);
- const dataSource = new DataSource({ type: 'postgres', entities: [] });
- const rowsBatchLoader = new WorkspaceCacheRowsBatchLoader(
- dataSource,
- WORKSPACE_ID,
- );
-
- await rowsBatchLoader.loadRows([service.rowsRequirement]);
-
- expect(service.rowsRequirement).toEqual({});
- expect(
- service.computeForCache({
- workspaceId: WORKSPACE_ID,
- rows: rowsBatchLoader.readRows(service.rowsRequirement),
- }),
- ).toEqual({});
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/__tests__/stripe-subscription.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/__tests__/stripe-subscription.service.spec.ts
deleted file mode 100644
index 2f44af4c514..00000000000
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/__tests__/stripe-subscription.service.spec.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-/* @license Enterprise */
-
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';
-import { StripeSDKService } from 'src/engine/core-modules/billing/stripe/stripe-sdk/services/stripe-sdk.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-
-class StripeCardError extends Error {}
-
-describe('StripeSubscriptionService', () => {
- let service: StripeSubscriptionService;
-
- const stripe = {
- errors: { StripeCardError },
- invoices: {
- list: jest.fn(),
- pay: jest.fn(),
- retrieve: jest.fn(),
- },
- };
-
- const givenOpenInvoices = (invoiceIds: string[]) =>
- stripe.invoices.list.mockReturnValue({
- async *[Symbol.asyncIterator]() {
- for (const invoiceId of invoiceIds) {
- yield { id: invoiceId, status: 'open' };
- }
- },
- });
-
- beforeEach(async () => {
- jest.clearAllMocks();
- stripe.invoices.pay.mockResolvedValue({});
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- StripeSubscriptionService,
- {
- provide: TwentyConfigService,
- useValue: {
- get: (key: string) =>
- key === 'IS_BILLING_ENABLED' ? true : 'stripe-api-key',
- },
- },
- { provide: StripeSDKService, useValue: { getStripe: () => stripe } },
- ],
- }).compile();
-
- service = module.get(StripeSubscriptionService);
- });
-
- describe('payOpenInvoices', () => {
- it('should pay every open auto-charged invoice, oldest first, with the new payment method', async () => {
- givenOpenInvoices(['in_newer', 'in_older']);
-
- await service.payOpenInvoices({
- stripeSubscriptionId: 'sub_1',
- stripePaymentMethodId: 'pm_1',
- });
-
- expect(stripe.invoices.list).toHaveBeenCalledWith({
- subscription: 'sub_1',
- status: 'open',
- collection_method: 'charge_automatically',
- limit: 100,
- });
- expect(stripe.invoices.pay.mock.calls).toEqual([
- ['in_older', { payment_method: 'pm_1' }],
- ['in_newer', { payment_method: 'pm_1' }],
- ]);
- });
-
- it('should keep paying the remaining invoices when the card is declined', async () => {
- givenOpenInvoices(['in_newer', 'in_older']);
- stripe.invoices.pay.mockRejectedValueOnce(
- new StripeCardError('Your card was declined.'),
- );
-
- await expect(
- service.payOpenInvoices({
- stripeSubscriptionId: 'sub_1',
- stripePaymentMethodId: 'pm_1',
- }),
- ).resolves.toBeUndefined();
-
- expect(stripe.invoices.pay).toHaveBeenCalledTimes(2);
- });
-
- it('should move on when the invoice was settled in the meantime', async () => {
- givenOpenInvoices(['in_newer', 'in_older']);
- stripe.invoices.pay.mockRejectedValueOnce(
- new Error('This invoice is already paid.'),
- );
- stripe.invoices.retrieve.mockResolvedValue({
- id: 'in_older',
- status: 'paid',
- });
-
- await expect(
- service.payOpenInvoices({
- stripeSubscriptionId: 'sub_1',
- stripePaymentMethodId: 'pm_1',
- }),
- ).resolves.toBeUndefined();
-
- expect(stripe.invoices.retrieve).toHaveBeenCalledWith('in_older');
- expect(stripe.invoices.pay).toHaveBeenCalledTimes(2);
- });
-
- it('should propagate a failure that leaves the invoice open', async () => {
- givenOpenInvoices(['in_1']);
- const stripeError = new Error('Stripe is unavailable');
-
- stripe.invoices.pay.mockRejectedValueOnce(stripeError);
- stripe.invoices.retrieve.mockResolvedValue({
- id: 'in_1',
- status: 'open',
- });
-
- await expect(
- service.payOpenInvoices({
- stripeSubscriptionId: 'sub_1',
- stripePaymentMethodId: 'pm_1',
- }),
- ).rejects.toBe(stripeError);
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/services/__tests__/custom-ai-provider-access.service.spec.ts b/packages/twenty-server/src/engine/core-modules/enterprise/services/__tests__/custom-ai-provider-access.service.spec.ts
deleted file mode 100644
index 35ec16f09e7..00000000000
--- a/packages/twenty-server/src/engine/core-modules/enterprise/services/__tests__/custom-ai-provider-access.service.spec.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-/* @license Enterprise */
-
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS } from 'src/engine/core-modules/enterprise/constants/custom-ai-provider-access-refresh-interval.constant';
-import { CUSTOM_AI_PROVIDER_ACCESS_RETRY_INTERVAL_MS } from 'src/engine/core-modules/enterprise/constants/custom-ai-provider-access-retry-interval.constant';
-import { MAX_SEATS_WITHOUT_ENTERPRISE_KEY } from 'src/engine/core-modules/enterprise/constants/max-seats-without-organization-key.constant';
-import { CustomAiProviderAccessService } from 'src/engine/core-modules/enterprise/services/custom-ai-provider-access.service';
-import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-
-describe('CustomAiProviderAccessService', () => {
- let service: CustomAiProviderAccessService;
-
- const twentyConfigService = { get: jest.fn() };
- const enterprisePlanService = {
- isValid: jest.fn(),
- getBillableSeatCount: jest.fn(),
- };
-
- const givenSeatCount = (seatCount: number) =>
- enterprisePlanService.getBillableSeatCount.mockResolvedValue(seatCount);
-
- // The refresh is deliberately not awaited by its caller, so the assertions
- // that follow one have to let the microtask queue drain first.
- const flushPendingRefresh = () => Promise.resolve();
-
- // The staleness rules are the point of these cases, so the clock is driven
- // rather than mocked per case — reading the real Date.now to build the next
- // value compounds against the previous mock and silently overshoots.
- const START_TIME = 1_700_000_000_000;
- let currentTime = START_TIME;
-
- const advanceClockTo = (millisecondsFromStart: number) => {
- currentTime = START_TIME + millisecondsFromStart;
- };
-
- beforeEach(async () => {
- jest.clearAllMocks();
- currentTime = START_TIME;
- jest.spyOn(Date, 'now').mockImplementation(() => currentTime);
- twentyConfigService.get.mockReturnValue(false);
- enterprisePlanService.isValid.mockReturnValue(false);
- givenSeatCount(1);
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- CustomAiProviderAccessService,
- { provide: TwentyConfigService, useValue: twentyConfigService },
- { provide: EnterprisePlanService, useValue: enterprisePlanService },
- ],
- }).compile();
-
- service = module.get<CustomAiProviderAccessService>(
- CustomAiProviderAccessService,
- );
- });
-
- afterEach(() => {
- jest.restoreAllMocks();
- });
-
- describe('computeAccess', () => {
- it('reports the threshold alongside the seat count it counted', async () => {
- givenSeatCount(MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1);
-
- await expect(service.computeAccess()).resolves.toEqual({
- hasAccess: false,
- seatCount: MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1,
- seatThreshold: MAX_SEATS_WITHOUT_ENTERPRISE_KEY,
- });
- });
- });
-
- describe('getCachedHasAccess', () => {
- it('grants access before any count has come back', () => {
- givenSeatCount(MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1);
-
- expect(service.getCachedHasAccess()).toBe(true);
- });
-
- it('serves the verdict of the refresh it triggered to later callers', async () => {
- givenSeatCount(MAX_SEATS_WITHOUT_ENTERPRISE_KEY + 1);
-
- service.getCachedHasAccess();
- await flushPendingRefresh();
-
- expect(service.getCachedHasAccess()).toBe(false);
- });
-
- it('counts seats once per refresh interval however often it is read', async () => {
- service.getCachedHasAccess();
- await flushPendingRefresh();
- service.getCachedHasAccess();
- service.getCachedHasAccess();
-
- expect(enterprisePlanService.getBillableSeatCount).toHaveBeenCalledTimes(
- 1,
- );
- });
-
- it('counts again once the interval has elapsed', async () => {
- service.getCachedHasAccess();
- await flushPendingRefresh();
-
- advanceClockTo(CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS);
- service.getCachedHasAccess();
- await flushPendingRefresh();
-
- expect(enterprisePlanService.getBillableSeatCount).toHaveBeenCalledTimes(
- 2,
- );
- });
-
- it('retries a failed count on the short interval instead of waiting a full refresh', async () => {
- service.getCachedHasAccess();
- await flushPendingRefresh();
-
- enterprisePlanService.getBillableSeatCount.mockRejectedValue(
- new Error('connection terminated'),
- );
- advanceClockTo(CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS);
- service.getCachedHasAccess();
- await flushPendingRefresh();
-
- expect(enterprisePlanService.getBillableSeatCount).toHaveBeenCalledTimes(
- 2,
- );
-
- // One retry interval past the failed count, and nowhere near another full
- // refresh interval: the stamp taken before that count would otherwise hold
- // the stale verdict for an hour.
- advanceClockTo(
- CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS +
- CUSTOM_AI_PROVIDER_ACCESS_RETRY_INTERVAL_MS,
- );
- service.getCachedHasAccess();
- await flushPendingRefresh();
-
- expect(enterprisePlanService.getBillableSeatCount).toHaveBeenCalledTimes(
- 3,
- );
- });
-
- it('keeps the previous verdict when the count fails, rather than disabling AI', async () => {
- service.getCachedHasAccess();
- await flushPendingRefresh();
-
- enterprisePlanService.getBillableSeatCount.mockRejectedValue(
- new Error('connection terminated'),
- );
- advanceClockTo(CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS);
- service.getCachedHasAccess();
- await flushPendingRefresh();
-
- expect(service.getCachedHasAccess()).toBe(true);
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.service.spec.ts b/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.service.spec.ts
deleted file mode 100644
index d7e0de9db20..00000000000
--- a/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.service.spec.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-import { EventLogTable } from 'twenty-shared/types';
-import { type Repository } from 'typeorm';
-
-import { type ClickHouseService } from 'src/database/clickhouse/clickhouse.service';
-import { type BillingService } from 'src/engine/core-modules/billing/services/billing.service';
-import { type EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
-import { EventLogsService } from 'src/engine/core-modules/event-logs/event-logs.service';
-import { type UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
-
-const CALLING_APPLICATION_ID = 'calling-application-id';
-
-const makeDeletedRecordRow = (recordId: string, timestamp: string) => ({
- event: 'Object Record Deleted',
- timestamp,
- workspaceId: 'workspace-id',
- recordId,
- objectMetadataId: 'company-object-metadata-id',
- properties: {},
-});
-
-const pageRowsEndingOnSharedTimestamp = [
- makeDeletedRecordRow('company-1', '2026-09-24 11:42:31.100'),
- makeDeletedRecordRow('company-2', '2026-09-24 11:42:31.096'),
- makeDeletedRecordRow('company-3', '2026-09-24 11:42:31.096'),
-];
-
-describe('EventLogsService', () => {
- let service: EventLogsService;
- let select: jest.Mock;
-
- beforeEach(() => {
- select = jest.fn();
-
- service = new EventLogsService(
- { getMainClient: () => ({}), select } as unknown as ClickHouseService,
- { hasEntitlement: async () => true } as unknown as BillingService,
- { isValid: () => true } as unknown as EnterprisePlanService,
- {} as Repository<UserWorkspaceEntity>,
- );
- });
-
- it('returns every record sharing the timestamp of the last record of the page', async () => {
- select
- .mockResolvedValueOnce(pageRowsEndingOnSharedTimestamp)
- .mockResolvedValueOnce([{ totalCount: 5 }])
- .mockResolvedValueOnce([
- makeDeletedRecordRow('company-2', '2026-09-24 11:42:31.096'),
- makeDeletedRecordRow('company-3', '2026-09-24 11:42:31.096'),
- makeDeletedRecordRow('company-4', '2026-09-24 11:42:31.096'),
- ]);
-
- const result = await service.queryEventLogs('workspace-id', {
- table: EventLogTable.OBJECT_EVENT,
- first: 2,
- });
-
- expect(result.records.map((record) => record.recordId)).toEqual([
- 'company-1',
- 'company-2',
- 'company-3',
- 'company-4',
- ]);
- expect(result.pageInfo.hasNextPage).toBe(true);
- expect(select).toHaveBeenCalledTimes(3);
- expect(select).toHaveBeenLastCalledWith(
- expect.stringMatching(
- /"timestamp" = \{lastRecordTimestamp:DateTime64\(3\)\}\s+LIMIT \{maxLimit:Int32\}/,
- ),
- expect.objectContaining({
- workspaceId: 'workspace-id',
- lastRecordTimestamp: '2026-09-24 11:42:31.096',
- maxLimit: 10000,
- }),
- );
- });
-
- it('keeps the page as fetched when the lookup at its last timestamp fails', async () => {
- select
- .mockResolvedValueOnce(pageRowsEndingOnSharedTimestamp)
- .mockResolvedValueOnce([{ totalCount: 5 }])
- .mockResolvedValueOnce([]);
-
- const result = await service.queryEventLogs('workspace-id', {
- table: EventLogTable.OBJECT_EVENT,
- first: 2,
- });
-
- expect(result.records.map((record) => record.recordId)).toEqual([
- 'company-1',
- 'company-2',
- ]);
- });
-
- it('keeps the page at the requested size when the next record is older', async () => {
- select
- .mockResolvedValueOnce([
- makeDeletedRecordRow('company-1', '2026-09-24 11:42:31.100'),
- makeDeletedRecordRow('company-2', '2026-09-24 11:42:31.096'),
- makeDeletedRecordRow('company-3', '2026-09-24 11:42:31.090'),
- ])
- .mockResolvedValueOnce([{ totalCount: 3 }]);
-
- const result = await service.queryEventLogs('workspace-id', {
- table: EventLogTable.OBJECT_EVENT,
- first: 2,
- });
-
- expect(result.records.map((record) => record.recordId)).toEqual([
- 'company-1',
- 'company-2',
- ]);
- expect(select).toHaveBeenCalledTimes(2);
- });
-
- it('should scope application logs to the calling application', async () => {
- select.mockResolvedValue([]);
-
- await service.queryEventLogs(
- 'workspace-id',
- { table: EventLogTable.APPLICATION_LOG },
- { callingApplicationId: CALLING_APPLICATION_ID },
- );
-
- expect(select).toHaveBeenCalledTimes(2);
-
- for (const [query, params] of select.mock.calls) {
- expect(query).toContain(
- '"applicationId" = {callingApplicationId:String}',
- );
- expect(params).toMatchObject({
- workspaceId: 'workspace-id',
- callingApplicationId: CALLING_APPLICATION_ID,
- });
- }
- });
-
- it('should keep the application scope when fetching the rows sharing the last timestamp', async () => {
- select
- .mockResolvedValueOnce(pageRowsEndingOnSharedTimestamp)
- .mockResolvedValueOnce([{ totalCount: 5 }])
- .mockResolvedValueOnce([]);
-
- await service.queryEventLogs(
- 'workspace-id',
- { table: EventLogTable.APPLICATION_LOG, first: 2 },
- { callingApplicationId: CALLING_APPLICATION_ID },
- );
-
- expect(select).toHaveBeenCalledTimes(3);
- expect(select).toHaveBeenLastCalledWith(
- expect.stringContaining(
- '"applicationId" = {callingApplicationId:String}',
- ),
- expect.objectContaining({ callingApplicationId: CALLING_APPLICATION_ID }),
- );
- });
-
- it('should return every application log to a caller that is not an application', async () => {
- select.mockResolvedValue([]);
-
- await service.queryEventLogs('workspace-id', {
- table: EventLogTable.APPLICATION_LOG,
- });
-
- for (const [query, params] of select.mock.calls) {
- expect(query).not.toContain('"applicationId"');
- expect(params).not.toHaveProperty('callingApplicationId');
- }
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/services/__tests__/file-storage.service.spec.ts b/packages/twenty-server/src/engine/core-modules/file-storage/services/__tests__/file-storage.service.spec.ts
deleted file mode 100644
index 35a5ccb38d2..00000000000
--- a/packages/twenty-server/src/engine/core-modules/file-storage/services/__tests__/file-storage.service.spec.ts
+++ /dev/null
@@ -1,306 +0,0 @@
-import { type QueryRunner } from 'typeorm';
-import { FileFolder } from 'twenty-shared/types';
-
-import { type FileStorageDriverFactory } from 'src/engine/core-modules/file-storage/file-storage-driver.factory';
-import { FileStorageExceptionCode } from 'src/engine/core-modules/file-storage/interfaces/file-storage-exception';
-import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
-import { type FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
-import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { type UsageLimitStockService } from 'src/engine/core-modules/usage-limit/services/usage-limit-stock.service';
-import { type WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
-
-const WORKSPACE_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
-const APPLICATION_ID = 'b30a4560-fedb-4ccd-904a-3788762c7d33';
-const APPLICATION_UNIVERSAL_IDENTIFIER = 'b30a4560-fedb-4ccd-904a-3788762c7d33';
-
-describe('FileStorageService', () => {
- const buildService = (existingFile: Partial<FileEntity> | null) => {
- const transactionRepository = {
- findOne: jest.fn().mockResolvedValue(existingFile),
- upsertAndReturnOne: jest
- .fn()
- .mockImplementation((_workspaceId, entity) => entity),
- };
-
- const insertQueryBuilder = {
- insert: jest.fn().mockReturnThis(),
- values: jest.fn().mockReturnThis(),
- orIgnore: jest.fn().mockReturnThis(),
- returning: jest.fn().mockReturnThis(),
- execute: jest.fn().mockResolvedValue({ raw: [{ id: 'created-row' }] }),
- };
-
- const fileRepository = {
- findOne: jest.fn().mockResolvedValue(existingFile),
- createQueryBuilder: jest.fn().mockReturnValue(insertQueryBuilder),
- upsertAndReturnOne: jest
- .fn()
- .mockImplementation((_workspaceId, entity) => entity),
- insertAndReturnOne: jest
- .fn()
- .mockImplementation((_workspaceId, entity) => entity),
- withManager: jest.fn().mockReturnValue(transactionRepository),
- };
-
- const driver = {
- writeFile: jest.fn().mockResolvedValue(undefined),
- getFileMetadata: jest.fn().mockResolvedValue({ size: 42 }),
- readFilePrefix: jest
- .fn()
- .mockResolvedValue(Buffer.from('export const main = () => {};')),
- checkFileExists: jest.fn().mockResolvedValue(true),
- copy: jest.fn().mockResolvedValue(undefined),
- };
-
- const usageLimitStockService = {
- assertStockAvailable: jest.fn().mockResolvedValue(undefined),
- acquireStock: jest.fn().mockResolvedValue(undefined),
- };
-
- const service = new FileStorageService(
- {
- getCurrentDriver: () => driver,
- } as unknown as FileStorageDriverFactory,
- fileRepository as unknown as WorkspaceScopedRepository<FileEntity>,
- {
- getOrRecompute: jest.fn().mockResolvedValue({
- flatApplicationMaps: {
- byId: {
- [APPLICATION_ID]: {
- id: APPLICATION_ID,
- universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- deletedAt: null,
- },
- },
- idByUniversalIdentifier: {
- [APPLICATION_UNIVERSAL_IDENTIFIER]: APPLICATION_ID,
- },
- },
- }),
- } as unknown as WorkspaceCacheService,
- usageLimitStockService as unknown as UsageLimitStockService,
- );
-
- return {
- service,
- fileRepository,
- transactionRepository,
- insertQueryBuilder,
- driver,
- usageLimitStockService,
- };
- };
-
- const writeFile = (
- service: FileStorageService,
- fileId: string,
- queryRunner?: QueryRunner,
- ) =>
- service.writeFile({
- sourceFile: '{}',
- fileFolder: FileFolder.Dependencies,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- applicationId: APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- resourcePath: 'package.json',
- fileId,
- settings: { isTemporaryFile: false, toDelete: false },
- queryRunner,
- });
-
- const createPendingFile = (service: FileStorageService, fileId: string) =>
- service.createPendingFile({
- fileFolder: FileFolder.Dependencies,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- applicationId: APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- resourcePath: 'package.json',
- fileId,
- size: 12,
- mimeType: 'application/json',
- settings: { isTemporaryFile: false, toDelete: false },
- });
-
- const copyFileByPath = (service: FileStorageService) =>
- service.copyFileByPath({
- from: {
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- fileFolder: FileFolder.Source,
- resourcePath: 'original/src/index.ts',
- },
- to: {
- workspaceId: WORKSPACE_ID,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- fileFolder: FileFolder.Source,
- resourcePath: 'copy/src/index.ts',
- },
- });
-
- it('should keep the identifier of the row already stored at that path', async () => {
- const { service, fileRepository } = buildService({
- id: 'the-row-the-application-points-at',
- });
-
- await createPendingFile(service, 'a-freshly-generated-identifier');
-
- expect(fileRepository.findOne).toHaveBeenCalledTimes(1);
- expect(fileRepository.upsertAndReturnOne).toHaveBeenCalledTimes(1);
- expect(fileRepository.upsertAndReturnOne).toHaveBeenCalledWith(
- WORKSPACE_ID,
- expect.objectContaining({ id: 'the-row-the-application-points-at' }),
- ['path', 'workspaceId', 'applicationId'],
- );
- });
-
- it('should look the row up including soft-deleted ones, which the unique index still matches', async () => {
- const { service, fileRepository } = buildService(null);
-
- await createPendingFile(service, 'a-freshly-generated-identifier');
-
- expect(fileRepository.findOne).toHaveBeenCalledTimes(1);
- expect(fileRepository.findOne).toHaveBeenCalledWith(
- WORKSPACE_ID,
- expect.objectContaining({ withDeleted: true }),
- );
- });
-
- it('should use the generated identifier when no row is stored at that path', async () => {
- const { service, fileRepository } = buildService(null);
-
- await createPendingFile(service, 'a-freshly-generated-identifier');
-
- expect(fileRepository.findOne).toHaveBeenCalledTimes(1);
- expect(fileRepository.upsertAndReturnOne).toHaveBeenCalledTimes(1);
- expect(fileRepository.upsertAndReturnOne).toHaveBeenCalledWith(
- WORKSPACE_ID,
- expect.objectContaining({ id: 'a-freshly-generated-identifier' }),
- ['path', 'workspaceId', 'applicationId'],
- );
- });
-
- it('should keep the stored identifier when writing the file content again', async () => {
- const { service, fileRepository } = buildService({
- id: 'the-row-the-application-points-at',
- });
-
- await writeFile(service, 'a-freshly-generated-identifier');
-
- expect(fileRepository.upsertAndReturnOne).toHaveBeenCalledTimes(1);
- expect(fileRepository.upsertAndReturnOne).toHaveBeenCalledWith(
- WORKSPACE_ID,
- expect.objectContaining({ id: 'the-row-the-application-points-at' }),
- ['path', 'workspaceId', 'applicationId'],
- );
- });
-
- it('should look the row up through the transaction when one is given', async () => {
- const { service, fileRepository, transactionRepository } = buildService({
- id: 'the-row-the-application-points-at',
- });
- const queryRunner = { manager: {} } as QueryRunner;
-
- await writeFile(service, 'a-freshly-generated-identifier', queryRunner);
-
- expect(transactionRepository.findOne).toHaveBeenCalledTimes(1);
- expect(fileRepository.findOne).not.toHaveBeenCalled();
- expect(transactionRepository.upsertAndReturnOne).toHaveBeenCalledWith(
- WORKSPACE_ID,
- expect.objectContaining({ id: 'the-row-the-application-points-at' }),
- ['path', 'workspaceId', 'applicationId'],
- );
- });
-
- it('should copy a file with the size and mime type of its row', async () => {
- const { service, fileRepository, driver } = buildService({
- mimeType: 'application/typescript',
- size: 12,
- settings: { isTemporaryFile: false, toDelete: false },
- });
-
- await copyFileByPath(service);
-
- expect(driver.getFileMetadata).not.toHaveBeenCalled();
- expect(fileRepository.createQueryBuilder).not.toHaveBeenCalled();
- expect(fileRepository.insertAndReturnOne).toHaveBeenCalledWith(
- WORKSPACE_ID,
- expect.objectContaining({
- path: 'source/copy/src/index.ts',
- mimeType: 'application/typescript',
- size: 12,
- }),
- );
- });
-
- it('should create the missing row of a copied file from the stored file', async () => {
- const { service, fileRepository, insertQueryBuilder, driver } =
- buildService(null);
-
- await copyFileByPath(service);
-
- expect(insertQueryBuilder.values).toHaveBeenCalledWith({
- workspaceId: WORKSPACE_ID,
- path: 'source/original/src/index.ts',
- applicationId: APPLICATION_ID,
- mimeType: 'application/typescript',
- size: 42,
- status: 'UPLOADED',
- settings: { isTemporaryFile: false, toDelete: false },
- });
- expect(insertQueryBuilder.orIgnore).toHaveBeenCalled();
- expect(driver.copy).toHaveBeenCalledTimes(1);
- expect(fileRepository.insertAndReturnOne).toHaveBeenCalledWith(
- WORKSPACE_ID,
- expect.objectContaining({
- path: 'source/copy/src/index.ts',
- mimeType: 'application/typescript',
- size: 42,
- }),
- );
- });
-
- it('should charge the storage stock for both the created row and the copy', async () => {
- const { service, usageLimitStockService } = buildService(null);
-
- await copyFileByPath(service);
-
- expect(usageLimitStockService.acquireStock).toHaveBeenCalledTimes(2);
- expect(usageLimitStockService.acquireStock).toHaveBeenNthCalledWith(
- 1,
- expect.objectContaining({
- spenders: { applicationId: APPLICATION_ID },
- cost: { bytes: 42, quantity: 1 },
- }),
- );
- expect(usageLimitStockService.acquireStock).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({
- spenders: { applicationId: APPLICATION_ID },
- cost: { bytes: 42, quantity: 1 },
- }),
- );
- });
-
- it('should only charge the copy when a concurrent copy already created the missing row', async () => {
- const { service, insertQueryBuilder, usageLimitStockService } =
- buildService(null);
-
- insertQueryBuilder.execute.mockResolvedValue({ raw: [] });
-
- await copyFileByPath(service);
-
- expect(usageLimitStockService.acquireStock).toHaveBeenCalledTimes(1);
- });
-
- it('should fail to copy a file missing from storage', async () => {
- const { service, insertQueryBuilder, driver } = buildService(null);
-
- driver.getFileMetadata.mockResolvedValue(null);
-
- await expect(copyFileByPath(service)).rejects.toMatchObject({
- code: FileStorageExceptionCode.FILE_NOT_FOUND,
- });
- expect(insertQueryBuilder.values).not.toHaveBeenCalled();
- expect(driver.copy).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts
deleted file mode 100644
index 13ccf00d1c1..00000000000
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts
+++ /dev/null
@@ -1,320 +0,0 @@
-import { Readable } from 'stream';
-
-import { FileFolder } from 'twenty-shared/types';
-
-import { type FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
-import { type FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
-import { MAX_SANITIZABLE_SVG_BYTES } from 'src/engine/core-modules/file/file-upload/constants/max-sanitizable-svg-size.constant';
-import { FileUploadExceptionCode } from 'src/engine/core-modules/file/file-upload/file-upload.exception';
-import { FileUploadCompletionService } from 'src/engine/core-modules/file/file-upload/services/file-upload-completion.service';
-import { buildPendingUploadResourcePath } from 'src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util';
-import { FILE_STATUS } from 'src/engine/core-modules/file/types/file-status.type';
-
-describe('FileUploadCompletionService.completeUploadedFile', () => {
- const workspaceId = '20202020-0000-4000-8000-000000000001';
- const fileId = '20202020-0000-4000-8000-000000000002';
-
- const svgContent =
- '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>';
- const pngContent = Buffer.from([
- 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
- 0x49, 0x48, 0x44, 0x52,
- ]);
-
- let fileStorageService: jest.Mocked<FileStorageService>;
-
- const buildStorageLocation = (ext: string) => ({
- fileFolder: FileFolder.FilesField,
- applicationUniversalIdentifier: 'application-universal-identifier',
- workspaceId,
- resourcePath: `${fileId}.${ext}`,
- });
-
- const buildFile = (ext: string, size: number) =>
- ({
- id: fileId,
- path: `${FileFolder.FilesField}/${fileId}.${ext}`,
- size,
- status: FILE_STATUS.PENDING,
- mimeType: 'application/octet-stream',
- createdAt: new Date(),
- }) as FileEntity;
-
- const buildService = () =>
- new FileUploadCompletionService(fileStorageService);
-
- beforeEach(() => {
- fileStorageService = {
- getFileMetadata: jest.fn(),
- readFilePrefix: jest.fn().mockResolvedValue(Buffer.from(svgContent)),
- readFile: jest
- .fn()
- .mockImplementation(async () => Readable.from(Buffer.from(svgContent))),
- writeFileStream: jest.fn().mockResolvedValue(undefined),
- move: jest.fn().mockResolvedValue(undefined),
- deleteFileObject: jest.fn().mockResolvedValue(undefined),
- markFileUploaded: jest.fn().mockResolvedValue({ affected: 1 }),
- } as unknown as jest.Mocked<FileStorageService>;
- });
-
- afterEach(() => {
- jest.clearAllMocks();
- });
-
- it('should refuse an SVG larger than the sanitizable limit without reading it', async () => {
- const size = MAX_SANITIZABLE_SVG_BYTES + 1;
-
- fileStorageService.getFileMetadata.mockResolvedValue({
- size,
- checksum: '"etag-a"',
- });
-
- await expect(
- buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('svg', size),
- storageLocation: buildStorageLocation('svg'),
- }),
- ).rejects.toMatchObject({
- code: FileUploadExceptionCode.FILE_TOO_LARGE,
- });
-
- expect(fileStorageService.readFile).not.toHaveBeenCalled();
- expect(fileStorageService.markFileUploaded).not.toHaveBeenCalled();
- });
-
- it('should report an oversized read as FILE_TOO_LARGE when storage understated the size', async () => {
- const declaredSize = 1024;
-
- fileStorageService.getFileMetadata.mockResolvedValue({
- size: declaredSize,
- checksum: '"etag-a"',
- });
- fileStorageService.readFile.mockResolvedValue(
- Readable.from(Buffer.alloc(MAX_SANITIZABLE_SVG_BYTES + 1)),
- );
-
- await expect(
- buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('svg', declaredSize),
- storageLocation: buildStorageLocation('svg'),
- }),
- ).rejects.toMatchObject({
- code: FileUploadExceptionCode.FILE_TOO_LARGE,
- });
-
- expect(fileStorageService.markFileUploaded).not.toHaveBeenCalled();
- });
-
- it('should refuse to promote a sanitized SVG whose new identity is unreadable', async () => {
- const size = Buffer.byteLength(svgContent);
-
- fileStorageService.getFileMetadata
- .mockResolvedValueOnce({ size, checksum: '"etag-a"' })
- .mockResolvedValueOnce(null);
-
- await expect(
- buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('svg', size),
- storageLocation: buildStorageLocation('svg'),
- }),
- ).rejects.toMatchObject({
- code: FileUploadExceptionCode.STORAGE_INCONSISTENT,
- });
-
- expect(fileStorageService.move).not.toHaveBeenCalled();
- });
-
- it('should refuse to promote a sanitized SVG that lost its version identity', async () => {
- const size = Buffer.byteLength(svgContent);
-
- fileStorageService.getFileMetadata
- .mockResolvedValueOnce({ size, checksum: '"etag-a"' })
- .mockResolvedValueOnce({ size: 10 });
-
- await expect(
- buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('svg', size),
- storageLocation: buildStorageLocation('svg'),
- }),
- ).rejects.toMatchObject({
- code: FileUploadExceptionCode.STORAGE_INCONSISTENT,
- });
-
- expect(fileStorageService.move).not.toHaveBeenCalled();
- });
-
- it('should promote a sanitized SVG under the identity it has after the rewrite', async () => {
- const size = Buffer.byteLength(svgContent);
-
- fileStorageService.getFileMetadata
- .mockResolvedValueOnce({ size, checksum: '"etag-before"' })
- .mockResolvedValueOnce({ size: 10, checksum: '"etag-after"' });
-
- await buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('svg', size),
- storageLocation: buildStorageLocation('svg'),
- });
-
- expect(fileStorageService.move).toHaveBeenCalledWith(
- expect.objectContaining({ ifMatchChecksum: '"etag-after"' }),
- );
- });
-
- it('should sanitize an SVG within the limit and store its new size', async () => {
- const size = Buffer.byteLength(svgContent);
-
- fileStorageService.getFileMetadata.mockResolvedValue({
- size,
- checksum: '"etag-a"',
- });
-
- const completedFile = await buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('svg', size),
- storageLocation: buildStorageLocation('svg'),
- });
-
- expect(completedFile.mimeType).toBe('image/svg+xml');
- expect(completedFile.size).toBeLessThan(size);
- expect(fileStorageService.writeFileStream).toHaveBeenCalledTimes(1);
- expect(fileStorageService.markFileUploaded).toHaveBeenCalledWith(
- expect.objectContaining({
- workspaceId,
- fileId,
- chargedSize: size,
- mimeType: 'image/svg+xml',
- size: completedFile.size,
- }),
- );
- });
-
- it('should not read a file that does not need sanitizing', async () => {
- const size = pngContent.length;
-
- fileStorageService.getFileMetadata.mockResolvedValue({
- size,
- checksum: '"etag-a"',
- });
- fileStorageService.readFilePrefix.mockResolvedValue(pngContent);
-
- const completedFile = await buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('png', size),
- storageLocation: buildStorageLocation('png'),
- });
-
- expect(completedFile.mimeType).toBe('image/png');
- expect(completedFile.size).toBe(size);
- expect(fileStorageService.readFile).not.toHaveBeenCalled();
- expect(fileStorageService.writeFileStream).not.toHaveBeenCalled();
- });
-
- it('should validate the quarantined object and move it to its final path', async () => {
- const size = pngContent.length;
- const storageLocation = buildStorageLocation('png');
- const pendingResourcePath = buildPendingUploadResourcePath({
- fileId,
- resourcePath: storageLocation.resourcePath,
- });
-
- fileStorageService.getFileMetadata.mockResolvedValue({
- size,
- checksum: '"etag-a"',
- });
- fileStorageService.readFilePrefix.mockResolvedValue(pngContent);
-
- await buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('png', size),
- storageLocation,
- });
-
- expect(fileStorageService.getFileMetadata).toHaveBeenCalledWith(
- expect.objectContaining({ resourcePath: pendingResourcePath }),
- );
- expect(fileStorageService.readFilePrefix).toHaveBeenCalledWith(
- expect.objectContaining({ resourcePath: pendingResourcePath }),
- );
- expect(fileStorageService.move).toHaveBeenCalledWith({
- from: expect.objectContaining({ resourcePath: pendingResourcePath }),
- to: storageLocation,
- ifMatchChecksum: '"etag-a"',
- });
- });
-
- it('should not complete an upload from an object left at the final path', async () => {
- const size = pngContent.length;
- const storageLocation = buildStorageLocation('png');
-
- fileStorageService.getFileMetadata.mockImplementation(async (location) =>
- location.resourcePath === storageLocation.resourcePath
- ? { size, checksum: '"etag-of-a-previous-upload"' }
- : null,
- );
-
- await expect(
- buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('png', size),
- storageLocation,
- }),
- ).rejects.toMatchObject({
- code: FileUploadExceptionCode.FILE_NOT_UPLOADED,
- });
-
- expect(fileStorageService.move).not.toHaveBeenCalled();
- expect(fileStorageService.markFileUploaded).not.toHaveBeenCalled();
- });
-
- it('should fail without touching storage when the row was reaped mid-completion', async () => {
- const size = pngContent.length;
-
- fileStorageService.getFileMetadata.mockResolvedValue({
- size,
- checksum: '"etag-a"',
- });
- fileStorageService.readFilePrefix.mockResolvedValue(pngContent);
- fileStorageService.markFileUploaded.mockResolvedValue({
- affected: 0,
- raw: [],
- generatedMaps: [],
- });
-
- await expect(
- buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('png', size),
- storageLocation: buildStorageLocation('png'),
- }),
- ).rejects.toMatchObject({
- code: FileUploadExceptionCode.FILE_NOT_FOUND,
- });
-
- // Deliberately orphaned: this path cannot prove the object is still the
- // one it promoted, and a later upload may own it by now.
- expect(fileStorageService.deleteFileObject).not.toHaveBeenCalled();
- });
-
- it('should leave the promoted object alone on a successful completion', async () => {
- const size = pngContent.length;
-
- fileStorageService.getFileMetadata.mockResolvedValue({
- size,
- checksum: '"etag-a"',
- });
- fileStorageService.readFilePrefix.mockResolvedValue(pngContent);
-
- await buildService().completeUploadedFile({
- workspaceId,
- file: buildFile('png', size),
- storageLocation: buildStorageLocation('png'),
- });
-
- expect(fileStorageService.deleteFileObject).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/frontend/__tests__/frontend.service.spec.ts b/packages/twenty-server/src/engine/core-modules/frontend/__tests__/frontend.service.spec.ts
deleted file mode 100644
index 242327217c8..00000000000
--- a/packages/twenty-server/src/engine/core-modules/frontend/__tests__/frontend.service.spec.ts
+++ /dev/null
@@ -1,539 +0,0 @@
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
-
-import { Controller, Get, type INestApplication } from '@nestjs/common';
-import { Test } from '@nestjs/testing';
-import { HttpAdapterHost } from '@nestjs/core';
-
-import { FrontendModule } from 'src/engine/core-modules/frontend/frontend.module';
-import request from 'supertest';
-
-import { type ClientConfigService } from 'src/engine/core-modules/client-config/services/client-config.service';
-import { type WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
-import { FrontendService } from 'src/engine/core-modules/frontend/frontend.service';
-import { type TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { WorkspaceNotFoundDefaultError } from 'src/engine/core-modules/workspace/workspace.exception';
-
-jest.mock(
- 'src/engine/core-modules/client-config/services/client-config.service',
- () => ({ ClientConfigService: class {} }),
-);
-jest.mock(
- 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service',
- () => ({ WorkspaceDomainsService: class {} }),
-);
-
-jest.mock(
- 'src/engine/core-modules/twenty-config/twenty-config.service',
- () => ({
- TwentyConfigService: class {},
- }),
-);
-
-jest.mock('src/engine/core-modules/client-config/client-config.module', () => ({
- ClientConfigModule: class {},
-}));
-jest.mock(
- 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module',
- () => ({ WorkspaceDomainsModule: class {} }),
-);
-
-@Controller('healthz')
-class HealthController {
- // oxlint-disable-next-line twenty/rest-api-methods-should-be-guarded
- @Get()
- health() {
- return { status: 'ok' };
- }
-}
-
-describe('frontend HTML delivery', () => {
- const config = {
- isMultiWorkspaceEnabled: true,
- frontDomain: 'twenty.test',
- authProviders: { password: true },
- };
- const getClientConfig = jest.fn();
- const resolveWorkspaceAndPublicDomain = jest.fn();
- let directory: string;
- let app: INestApplication;
-
- const createApplication = async (indexUrl?: string) => {
- const service = new FrontendService(
- { getClientConfig } as unknown as ClientConfigService,
- { resolveWorkspaceAndPublicDomain } as unknown as WorkspaceDomainsService,
- directory,
- { get: () => indexUrl } as unknown as TwentyConfigService,
- );
- const module = await Test.createTestingModule({
- imports: [FrontendModule],
- controllers: [HealthController],
- })
- .overrideProvider(FrontendService)
- .useValue(service)
- .compile();
-
- app = module.createNestApplication();
- app.getHttpAdapter().getInstance().set('trust proxy', 'loopback');
- await app.init();
- };
-
- beforeEach(async () => {
- jest.useRealTimers();
- getClientConfig.mockReset().mockResolvedValue(config);
- resolveWorkspaceAndPublicDomain
- .mockReset()
- .mockImplementation(async (origin: string) => ({
- workspace: {
- allowedIframeOrigins:
- origin === 'https://customer.twenty.test'
- ? ['https://portal.customer.com']
- : [],
- },
- isIsolatedOrigin: false,
- }));
- directory = mkdtempSync(join(tmpdir(), 'twenty-frontend-'));
- writeFileSync(
- join(directory, 'index.html'),
- '<html><head><!-- BEGIN: Twenty Config --><script>window._env_={REACT_APP_SERVER_BASE_URL:"wrong"}</script><!-- END: Twenty Config --></head><body><div id="root"></div></body></html>',
- );
- await createApplication();
- });
-
- afterEach(async () => {
- await app.close();
- rmSync(directory, { recursive: true, force: true });
- jest.restoreAllMocks();
- jest.useRealTimers();
- });
-
- it.each([undefined, 'https://frontend.s3.example.com/index.html'])(
- 'initializes CLI application contexts without fetching HTML (origin: %s)',
- async (indexUrl) => {
- const fetchTemplate = jest.spyOn(globalThis, 'fetch');
- const module = await Test.createTestingModule({
- imports: [FrontendModule],
- })
- .overrideProvider(FrontendService)
- .useValue(
- new FrontendService(
- { getClientConfig } as unknown as ClientConfigService,
- {
- resolveWorkspaceAndPublicDomain,
- } as unknown as WorkspaceDomainsService,
- directory,
- { get: () => indexUrl } as unknown as TwentyConfigService,
- ),
- )
- .compile();
- expect(module.get(HttpAdapterHost).httpAdapter).toBeUndefined();
- await expect(module.init()).resolves.toBeDefined();
- expect(fetchTemplate).not.toHaveBeenCalled();
- await module.close();
- },
- );
-
- it('serves bundled HTML without an external request when the URL is unset', async () => {
- const fetchTemplate = jest.spyOn(globalThis, 'fetch');
- const response = await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(200);
- expect(response.text).toContain('<div id="root"></div>');
- expect(response.text).toContain('twenty-client-config');
- expect(fetchTemplate).not.toHaveBeenCalled();
- });
-
- it('preserves API-only development when neither bundled HTML nor a URL exists', async () => {
- await app.close();
- rmSync(join(directory, 'index.html'));
- const fetchTemplate = jest.spyOn(globalThis, 'fetch');
- await createApplication();
- await request(app.getHttpServer()).get('/healthz').expect(200);
- await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(404);
- expect(fetchTemplate).not.toHaveBeenCalled();
- expect(getClientConfig).not.toHaveBeenCalled();
- });
-
- it.each(['/', '/index.html', '/objects/people'])(
- 'bootstraps configuration and applies the hostname policy on %s',
- async (pathname) => {
- const response = await request(app.getHttpServer())
- .get(pathname)
- .set('Accept', 'text/html')
- .set('Host', 'customer.twenty.test')
- .set('X-Forwarded-Proto', 'https')
- .expect(200);
- expect(response.headers['content-security-policy']).toContain(
- "frame-ancestors 'self' https://portal.customer.com;",
- );
- expect(response.headers['x-frame-options']).toBeUndefined();
- expect(response.headers['cache-control']).toBe('no-store');
- expect(response.headers['cdn-cache-control']).toBe('no-store');
- expect(response.text).toContain(
- `type="application/json">${JSON.stringify(config)}</script>`,
- );
- expect(response.text).toContain('window._env_ = {};');
- expect(response.text).not.toContain('wrong');
- },
- );
-
- it('does not borrow a policy from another workspace or a supplied Origin header', async () => {
- const response = await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .set('Host', 'other.twenty.test')
- .set('Origin', 'https://customer.twenty.test')
- .expect(200);
- expect(response.headers['content-security-policy']).toBe(
- "frame-ancestors 'self'; object-src 'none'; base-uri 'self'",
- );
- expect(response.headers['x-frame-options']).toBe('SAMEORIGIN');
- });
-
- it('reads fresh policy and configuration on subsequent documents, even with a conditional request', async () => {
- const initial = await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .set('Host', 'customer.twenty.test')
- .set('X-Forwarded-Proto', 'https');
- expect(initial.headers['content-security-policy']).toContain(
- 'https://portal.customer.com',
- );
- resolveWorkspaceAndPublicDomain.mockResolvedValue({
- workspace: { allowedIframeOrigins: [] },
- isIsolatedOrigin: false,
- });
- const response = await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .set('Host', 'customer.twenty.test')
- .set('X-Forwarded-Proto', 'https')
- .set('If-None-Match', '*')
- .expect(200);
- expect(response.headers['content-security-policy']).not.toContain(
- 'portal.customer.com',
- );
- expect(getClientConfig).toHaveBeenCalledTimes(2);
- });
-
- it('escapes script terminators and preserves literal replacement tokens in configuration', async () => {
- getClientConfig.mockResolvedValue({
- ...config,
- frontDomain: "</script><script>alert(1)</script>$&$'",
- });
- const response = await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(200);
- expect(response.text).not.toContain('<script>alert(1)');
- const serializedConfig = response.text.match(
- /type="application\/json">(.*?)<\/script>/,
- )?.[1];
- expect(JSON.parse(serializedConfig!)).toEqual(await getClientConfig());
- });
-
- it('serves signup on an installation with no workspace', async () => {
- resolveWorkspaceAndPublicDomain.mockRejectedValue(
- WorkspaceNotFoundDefaultError,
- );
- await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(200);
- });
-
- it('fails closed when policy resolution fails', async () => {
- resolveWorkspaceAndPublicDomain.mockRejectedValue(
- new Error('Database unavailable'),
- );
- const response = await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(503);
- expect(response.headers['content-security-policy']).toContain(
- "frame-ancestors 'self'",
- );
- });
-
- it('does not serve the CRM on a public application domain', async () => {
- resolveWorkspaceAndPublicDomain.mockResolvedValue({
- workspace: undefined,
- isIsolatedOrigin: true,
- });
- await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(404);
- });
-
- it.each([
- '/graphql/missing',
- '/rest/missing',
- '/auth/missing',
- '/.well-known/missing',
- ])('does not turn %s into a successful HTML response', async (pathname) => {
- await request(app.getHttpServer())
- .get(pathname)
- .set('Accept', 'text/html')
- .expect(404);
- expect(getClientConfig).not.toHaveBeenCalled();
- });
-
- it.each([
- '*/*',
- 'application/json',
- 'image/avif,image/webp,*/*',
- 'text/html;q=0',
- ])('does not serve a document for Accept: %s', async (accept) => {
- await request(app.getHttpServer())
- .get('/new-asset-directory/missing')
- .set('Accept', accept)
- .expect(404);
- expect(getClientConfig).not.toHaveBeenCalled();
- });
-
- it.each(['script', 'style', 'image', 'font', 'empty'])(
- 'does not serve a document for Sec-Fetch-Dest: %s',
- async (destination) => {
- await request(app.getHttpServer())
- .get('/new-asset-directory/missing')
- .set('Accept', 'text/html')
- .set('Sec-Fetch-Dest', destination)
- .expect(404);
- expect(getClientConfig).not.toHaveBeenCalled();
- },
- );
-
- it.each(['document', 'iframe', 'frame'])(
- 'serves HTML navigation with Sec-Fetch-Dest: %s',
- async (destination) => {
- await request(app.getHttpServer())
- .get('/objects/people')
- .set('Accept', 'text/html,application/xhtml+xml,*/*;q=0.8')
- .set('Sec-Fetch-Dest', destination)
- .expect(200);
- expect(getClientConfig).toHaveBeenCalledTimes(1);
- },
- );
-
- it.each([
- '/invite/apple.dev-invite-hash',
- '/invite/apple.dev-invite-hash/',
- '/settings/domains/crm.example.com',
- ])('serves browser navigation to dotted path %s', async (pathname) => {
- await request(app.getHttpServer())
- .get(pathname)
- .set('Accept', 'text/html,application/xhtml+xml,*/*;q=0.8')
- .set('Sec-Fetch-Dest', 'document')
- .expect(200);
- expect(getClientConfig).toHaveBeenCalledTimes(1);
- });
-
- it.each(['script', 'style', 'empty'])(
- 'does not serve a document for a missing asset with Sec-Fetch-Dest: %s',
- async (destination) => {
- await request(app.getHttpServer())
- .get('/assets/missing.js')
- .set('Accept', 'text/html')
- .set('Sec-Fetch-Dest', destination)
- .expect(404);
- expect(getClientConfig).not.toHaveBeenCalled();
- },
- );
-
- it('serves extensionless static files in arbitrary directories before the SPA fallback', async () => {
- mkdirSync(join(directory, 'new-asset-directory'));
- writeFileSync(
- join(directory, 'new-asset-directory', 'example'),
- 'static content',
- );
- const response = await request(app.getHttpServer())
- .get('/new-asset-directory/example')
- .set('Accept', 'text/html')
- .expect(200);
- expect(response.body.toString()).toBe('static content');
- expect(getClientConfig).not.toHaveBeenCalled();
- });
-
- it('preserves API controller routing', async () => {
- const response = await request(app.getHttpServer())
- .get('/healthz')
- .set('Accept', 'text/html')
- .expect(200);
- expect(response.body).toEqual({ status: 'ok' });
- expect(getClientConfig).not.toHaveBeenCalled();
- });
-
- it('serves static assets and blocks framing of alternate HTML paths', async () => {
- writeFileSync(join(directory, 'example.js'), 'console.log(1);');
- const asset = await request(app.getHttpServer())
- .get('/example.js')
- .set('Accept', 'text/html')
- .expect(200);
- expect(asset.text).toBe('console.log(1);');
- const html = await request(app.getHttpServer())
- .get('/%69ndex.html')
- .set('Accept', 'text/html')
- .expect(200);
- expect(html.headers['content-security-policy']).toBe(
- "frame-ancestors 'none'",
- );
- expect(html.headers['cache-control']).toBe('no-store');
- expect(getClientConfig).not.toHaveBeenCalled();
- });
-
- it('does not serve HTML for POST requests', async () => {
- await request(app.getHttpServer()).post('/objects/people').expect(404);
- });
-
- it('returns the policy for HEAD requests without a response body', async () => {
- const response = await request(app.getHttpServer())
- .head('/')
- .set('Accept', 'text/html')
- .expect(200);
- expect(response.headers['content-security-policy']).toContain(
- "frame-ancestors 'self'",
- );
- expect(response.text).toBeUndefined();
- });
-
- describe('remote HTML template', () => {
- const indexUrl = 'https://frontend.s3.example.com/index.html';
- const remoteTemplate =
- '<html><head></head><body>Remote release</body></html>';
- let fetchTemplate: jest.SpiedFunction<typeof fetch>;
-
- beforeEach(async () => {
- await app.close();
- rmSync(join(directory, 'index.html'));
- fetchTemplate = jest
- .spyOn(globalThis, 'fetch')
- .mockImplementation(async () => new Response(remoteTemplate));
- await createApplication(indexUrl);
- });
-
- it('fetches the current HTML per document and applies each workspace policy', async () => {
- expect(fetchTemplate).not.toHaveBeenCalled();
- for (const host of ['customer.twenty.test', 'other.twenty.test']) {
- fetchTemplate.mockResolvedValueOnce(
- new Response(`<head></head><body>Latest ${host}</body>`),
- );
- const response = await request(app.getHttpServer())
- .get('/')
- .set('Host', host)
- .set('X-Forwarded-Proto', 'https')
- .set('Accept', 'text/html')
- .expect(200);
- expect(response.text).toContain(`Latest ${host}`);
- expect(response.text).toContain('twenty-client-config');
- expect(response.headers['cache-control']).toBe('no-store');
- expect(response.headers['content-security-policy']).toBe(
- host === 'customer.twenty.test'
- ? "frame-ancestors 'self' https://portal.customer.com; object-src 'none'; base-uri 'self'"
- : "frame-ancestors 'self'; object-src 'none'; base-uri 'self'",
- );
- }
- expect(fetchTemplate).toHaveBeenCalledTimes(2);
- expect(fetchTemplate).toHaveBeenCalledWith(indexUrl, {
- signal: expect.any(AbortSignal),
- redirect: 'error',
- });
- });
-
- it('rejects isolated origins without contacting an unavailable HTML origin', async () => {
- resolveWorkspaceAndPublicDomain.mockResolvedValue({
- workspace: undefined,
- isIsolatedOrigin: true,
- });
- fetchTemplate.mockRejectedValue(new Error('Origin unavailable'));
- await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(404);
- expect(fetchTemplate).not.toHaveBeenCalled();
- expect(getClientConfig).not.toHaveBeenCalled();
- });
-
- it.each([undefined, '1'])(
- 'stops oversized HTML downloads independently of Content-Length: %s',
- async (contentLength) => {
- const cancel = jest.fn();
- const body = new ReadableStream<Uint8Array>({
- pull(controller) {
- controller.enqueue(
- Buffer.from('<head></head>' + 'x'.repeat(64 * 1024)),
- );
- },
- cancel,
- });
- fetchTemplate.mockResolvedValueOnce(
- new Response(body, {
- headers: contentLength ? { 'Content-Length': contentLength } : {},
- }),
- );
- const response = await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(503);
- expect(response.headers['cache-control']).toBe('no-store');
- expect(response.headers['x-frame-options']).toBe('SAMEORIGIN');
- expect(cancel).toHaveBeenCalled();
- },
- );
-
- it.each(['network', 'http', 'invalid HTML'])(
- 'returns 503 on %s failure and recovers on the next request',
- async (failure) => {
- if (failure === 'network') {
- fetchTemplate.mockRejectedValueOnce(new Error('Origin unavailable'));
- } else {
- fetchTemplate.mockResolvedValueOnce(
- new Response('Invalid template', {
- status: failure === 'http' ? 503 : 200,
- }),
- );
- }
- const response = await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(503);
- expect(response.headers['cache-control']).toBe('no-store');
- expect(response.headers['x-frame-options']).toBe('SAMEORIGIN');
- const recovered = await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(200);
- expect(recovered.text).toContain('Remote release');
- },
- );
-
- it('bounds the wait for an unresponsive origin', async () => {
- fetchTemplate.mockImplementationOnce(
- async (_url, options) =>
- new Promise((_resolve, reject) => {
- options?.signal?.addEventListener('abort', () =>
- reject(options.signal?.reason),
- );
- }),
- );
- await request(app.getHttpServer())
- .get('/')
- .set('Accept', 'text/html')
- .expect(503);
- }, 10_000);
-
- it('does not fetch HTML for health checks or missing API routes', async () => {
- await request(app.getHttpServer()).get('/healthz').expect(200);
- await request(app.getHttpServer())
- .get('/graphql/missing')
- .set('Accept', 'text/html')
- .expect(404);
- expect(fetchTemplate).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/__tests__/lambda-layer-manager.service.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/__tests__/lambda-layer-manager.service.spec.ts
deleted file mode 100644
index 9ea91ded841..00000000000
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/__tests__/lambda-layer-manager.service.spec.ts
+++ /dev/null
@@ -1,208 +0,0 @@
-import {
- DeleteLayerVersionCommand,
- ListLayerVersionsCommand,
- PublishLayerVersionCommand,
-} from '@aws-sdk/client-lambda';
-
-import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
-import { type CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
-import { type LambdaAwsClientService } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-aws-client.service';
-import { LambdaLayerManagerService } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-layer-manager.service';
-import { type LambdaToolFunctionsService } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-tool-functions.service';
-import { type LogicFunctionResourceService } from 'src/engine/core-modules/logic-function/logic-function-resource/logic-function-resource.service';
-import { type SdkClientArchiveService } from 'src/engine/core-modules/sdk-client/sdk-client-archive.service';
-import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-
-jest.mock(
- 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/utils/reprefix-lambda-zip-entries.util',
- () => ({
- reprefixLambdaZipEntries: jest.fn(async ({ sourceBuffer }) => sourceBuffer),
- }),
-);
-
-const WORKSPACE_ID = '20202020-0000-0000-0000-000000000001';
-const APPLICATION_ID = '20202020-0000-0000-0000-000000000002';
-const APPLICATION_UNIVERSAL_IDENTIFIER = 'test-app';
-
-describe('LambdaLayerManagerService.ensureSdkLayer', () => {
- let flatApplication: FlatApplication;
- let publishedVersion: number;
- let liveVersions: number[];
- let publishInFlight: Promise<void>;
- let resolvePublish: () => void;
-
- const send = jest.fn();
- const awsClient = {
- getLambdaClient: async () => ({ send }),
- getExistingLayerArn: jest.fn(),
- };
- const sdkClientArchiveService = {
- downloadArchiveBuffer: jest.fn(async () => Buffer.from('zip')),
- markSdkLayerFresh: jest.fn(async () => {
- flatApplication = { ...flatApplication, isSdkLayerStale: false };
- }),
- };
- const workspaceCacheService = {
- getOrRecompute: jest.fn(async () => ({
- flatApplicationMaps: { byId: { [APPLICATION_ID]: flatApplication } },
- })),
- };
- const lockChains = new Map<string, Promise<unknown>>();
- const cacheLockService = {
- withLock: jest.fn(async <T>(fn: () => Promise<T>, key: string) => {
- const previous = lockChains.get(key) ?? Promise.resolve();
- const run = previous.then(fn, fn);
-
- lockChains.set(
- key,
- run.catch(() => undefined),
- );
-
- return run;
- }),
- };
-
- const buildService = () =>
- new LambdaLayerManagerService(
- { layerBucket: 'bucket', resourceNamespace: 'test' },
- awsClient as unknown as LambdaAwsClientService,
- {} as LambdaToolFunctionsService,
- {} as LogicFunctionResourceService,
- sdkClientArchiveService as unknown as SdkClientArchiveService,
- cacheLockService as unknown as CacheLockService,
- workspaceCacheService as unknown as WorkspaceCacheService,
- );
-
- beforeEach(() => {
- jest.clearAllMocks();
- lockChains.clear();
- awsClient.getExistingLayerArn.mockImplementation(
- async (layerName: string) =>
- liveVersions.length > 0
- ? `arn:${layerName}:${liveVersions[liveVersions.length - 1]}`
- : undefined,
- );
- flatApplication = {
- id: APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- isSdkLayerStale: true,
- } as FlatApplication;
- publishedVersion = 0;
- liveVersions = [1];
- publishInFlight = new Promise((resolve) => {
- resolvePublish = resolve;
- });
-
- send.mockImplementation(async (command) => {
- if (command instanceof ListLayerVersionsCommand) {
- return {
- LayerVersions: liveVersions.map((version) => ({ Version: version })),
- };
- }
-
- if (command instanceof DeleteLayerVersionCommand) {
- liveVersions = liveVersions.filter(
- (version) => version !== command.input.VersionNumber,
- );
-
- return {};
- }
-
- if (command instanceof PublishLayerVersionCommand) {
- await publishInFlight;
- publishedVersion += 1;
- liveVersions = [...liveVersions, publishedVersion + 1];
-
- return {
- LayerVersionArn: `arn:${command.input.LayerName}:${publishedVersion + 1}`,
- };
- }
-
- throw new Error(`Unexpected command ${command.constructor.name}`);
- });
- });
-
- it('returns the existing layer without touching AWS when the layer is fresh', async () => {
- flatApplication = { ...flatApplication, isSdkLayerStale: false };
-
- const arn = await buildService().ensureSdkLayer({
- flatApplication,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- });
-
- expect(arn).toMatch(/:1$/);
- expect(send).not.toHaveBeenCalled();
- expect(cacheLockService.withLock).not.toHaveBeenCalled();
- });
-
- it('creates the dependencies layer once when two functions of the application build concurrently', async () => {
- const service = buildService();
- let depsLayerExists = false;
- let finishCreation: () => void = () => undefined;
- const creationInFlight = new Promise<void>((resolve) => {
- finishCreation = resolve;
- });
- const createDepsLayer = jest
- .spyOn(
- service as unknown as { createDepsLayer: () => Promise<void> },
- 'createDepsLayer',
- )
- .mockImplementation(async () => {
- await creationInFlight;
- depsLayerExists = true;
- });
-
- awsClient.getExistingLayerArn.mockImplementation(
- async (layerName: string) =>
- depsLayerExists ? `arn:${layerName}:1` : undefined,
- );
-
- const context = {
- flatApplication,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- };
-
- const firstBuild = service.ensureDepsLayer(context);
- const secondBuild = service.ensureDepsLayer(context);
-
- finishCreation();
-
- const [firstArn, secondArn] = await Promise.all([firstBuild, secondBuild]);
-
- expect(firstArn).toBe(secondArn);
- expect(createDepsLayer).toHaveBeenCalledTimes(1);
- });
-
- it('publishes the stale layer once when two functions of the application build concurrently', async () => {
- const service = buildService();
- const context = {
- flatApplication,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- };
-
- const firstBuild = service.ensureSdkLayer(context);
- const secondBuild = service.ensureSdkLayer(context);
-
- resolvePublish();
-
- const [firstArn, secondArn] = await Promise.all([firstBuild, secondBuild]);
-
- expect(firstArn).toBe(secondArn);
- expect(
- send.mock.calls.filter(
- ([command]) => command instanceof PublishLayerVersionCommand,
- ),
- ).toHaveLength(1);
- expect(
- send.mock.calls.filter(
- ([command]) => command instanceof DeleteLayerVersionCommand,
- ),
- ).toHaveLength(1);
- expect(sdkClientArchiveService.markSdkLayerFresh).toHaveBeenCalledTimes(1);
- expect(cacheLockService.withLock).toHaveBeenCalledTimes(2);
- expect(cacheLockService.withLock.mock.calls[0][1]).toBe(
- cacheLockService.withLock.mock.calls[1][1],
- );
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.spec.ts
deleted file mode 100644
index 10b44622348..00000000000
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.spec.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { mkdtemp, rm, writeFile } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-
-import { LocalChildProcessRunnerService } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service';
-
-describe('LocalChildProcessRunnerService', () => {
- it('preserves a thrown error name in the child-process result', async () => {
- jest.useRealTimers();
-
- const logicFunctionDirectory = await mkdtemp(
- join(tmpdir(), 'twenty-retryable-logic-function-'),
- );
-
- try {
- const builtLogicFunctionPath = join(
- logicFunctionDirectory,
- 'logic-function.mjs',
- );
-
- await writeFile(
- builtLogicFunctionPath,
- `export const main = async (_payload, context) => {
- const retryableError = new Error('Dependency unavailable on retry ' + context.retryCount);
- retryableError.name = 'RetryableLogicFunctionError';
- throw retryableError;
- };`,
- 'utf8',
- );
-
- const localChildProcessRunnerService =
- new LocalChildProcessRunnerService();
- const runnerPath =
- await localChildProcessRunnerService.writeBootstrapRunner({
- dir: logicFunctionDirectory,
- builtFileAbsPath: builtLogicFunctionPath,
- handlerName: 'main',
- });
-
- const executionResult =
- await localChildProcessRunnerService.runChildWithEnv({
- runnerPath,
- env: {},
- payload: {},
- context: {
- retryCount: 2,
- maxRetries: 3,
- workspaceId: 'workspace-1',
- userWorkspaceId: null,
- workspaceMemberId: null,
- },
- timeoutMs: 5_000,
- });
-
- expect(executionResult).toMatchObject({
- ok: false,
- errorType: 'RetryableLogicFunctionError',
- error: 'Dependency unavailable on retry 2',
- });
- } finally {
- await rm(logicFunctionDirectory, { recursive: true, force: true });
- jest.useFakeTimers();
- }
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/__tests__/logic-function-prebuilt-warm-up.service.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/__tests__/logic-function-prebuilt-warm-up.service.spec.ts
deleted file mode 100644
index a174fa04c1e..00000000000
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/__tests__/logic-function-prebuilt-warm-up.service.spec.ts
+++ /dev/null
@@ -1,251 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN } from 'src/engine/core-modules/logic-function/logic-function-drivers/constants/logic-function-driver-factory.token';
-import { LogicFunctionPrebuiltWarmUpService } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service';
-import { LogicFunctionExecutionMode } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-
-const WORKSPACE_ID = '20202020-0000-0000-0000-000000000001';
-const APPLICATION_ID = '20202020-0000-0000-0000-000000000002';
-const OTHER_APPLICATION_ID = '20202020-0000-0000-0000-000000000003';
-
-const flatApplication = {
- id: APPLICATION_ID,
- universalIdentifier: 'test-app',
-};
-
-const ALL_UNIVERSAL_IDENTIFIERS = [
- 'universal-ready-1',
- 'universal-ready-2',
- 'universal-live',
- 'universal-not-built',
- 'universal-other-app',
- 'universal-installed',
- 'universal-outdated',
- 'universal-failing',
- 'universal-unknown',
-];
-
-const buildFlatLogicFunction = (overrides: {
- id: string;
- applicationId?: string;
- checksum?: string | null;
- executionMode?: LogicFunctionExecutionMode;
- isBuildUpToDate?: boolean;
-}) => ({
- universalIdentifier: `universal-${overrides.id}`,
- applicationId: APPLICATION_ID,
- checksum: 'checksum-new',
- executionMode: LogicFunctionExecutionMode.PREBUILT,
- isBuildUpToDate: true,
- ...overrides,
-});
-
-describe('LogicFunctionPrebuiltWarmUpService', () => {
- let service: LogicFunctionPrebuiltWarmUpService;
-
- const workspaceCacheService = { getOrRecompute: jest.fn() };
- const driver = {
- getInstalledBundleChecksum: jest.fn(),
- installPrebuiltBundle: jest.fn(),
- };
- const logicFunctionDriverFactory = { getCurrentDriver: () => driver };
-
- const setFlatLogicFunctions = (
- flatLogicFunctions: ReturnType<typeof buildFlatLogicFunction>[],
- options: { withApplication?: boolean } = {},
- ) => {
- workspaceCacheService.getOrRecompute.mockResolvedValue({
- flatApplicationMaps: {
- byId:
- options.withApplication === false
- ? {}
- : { [APPLICATION_ID]: flatApplication },
- },
- flatLogicFunctionMaps: {
- byUniversalIdentifier: Object.fromEntries(
- flatLogicFunctions.map((flatLogicFunction) => [
- flatLogicFunction.universalIdentifier,
- flatLogicFunction,
- ]),
- ),
- universalIdentifiersByApplicationId: {
- [APPLICATION_ID]: flatLogicFunctions
- .filter(
- (flatLogicFunction) =>
- flatLogicFunction.applicationId === APPLICATION_ID,
- )
- .map((flatLogicFunction) => flatLogicFunction.universalIdentifier),
- },
- },
- });
- };
-
- beforeEach(async () => {
- jest.clearAllMocks();
- driver.getInstalledBundleChecksum.mockResolvedValue(null);
- driver.installPrebuiltBundle.mockResolvedValue(undefined);
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- LogicFunctionPrebuiltWarmUpService,
- { provide: WorkspaceCacheService, useValue: workspaceCacheService },
- {
- provide: LOGIC_FUNCTION_DRIVER_FACTORY_TOKEN,
- useValue: logicFunctionDriverFactory,
- },
- ],
- }).compile();
-
- service = module.get(LogicFunctionPrebuiltWarmUpService);
- });
-
- it('installs the prebuilt bundle of the listed ready functions of the application', async () => {
- setFlatLogicFunctions([
- buildFlatLogicFunction({ id: 'ready-1' }),
- buildFlatLogicFunction({ id: 'ready-2' }),
- buildFlatLogicFunction({
- id: 'live',
- executionMode: LogicFunctionExecutionMode.LIVE,
- }),
- buildFlatLogicFunction({ id: 'not-built', isBuildUpToDate: false }),
- buildFlatLogicFunction({
- id: 'other-app',
- applicationId: OTHER_APPLICATION_ID,
- }),
- ]);
-
- await service.warmUpApplicationLogicFunctions({
- workspaceId: WORKSPACE_ID,
- applicationId: APPLICATION_ID,
- logicFunctionUniversalIdentifiers: ALL_UNIVERSAL_IDENTIFIERS,
- });
-
- expect(driver.installPrebuiltBundle).toHaveBeenCalledTimes(2);
- expect(
- driver.installPrebuiltBundle.mock.calls.map(
- ([params]) => params.flatLogicFunction.id,
- ),
- ).toEqual(['ready-1', 'ready-2']);
- expect(driver.installPrebuiltBundle).toHaveBeenCalledWith(
- expect.objectContaining({
- flatApplication,
- applicationUniversalIdentifier: 'test-app',
- }),
- );
- });
-
- it('skips functions whose installed bundle already matches the checksum', async () => {
- setFlatLogicFunctions([
- buildFlatLogicFunction({ id: 'installed', checksum: 'checksum-same' }),
- buildFlatLogicFunction({ id: 'outdated', checksum: 'checksum-new' }),
- ]);
- driver.getInstalledBundleChecksum.mockImplementation(
- async (flatLogicFunction: { id: string }) =>
- flatLogicFunction.id === 'installed' ? 'checksum-same' : 'old',
- );
-
- await service.warmUpApplicationLogicFunctions({
- workspaceId: WORKSPACE_ID,
- applicationId: APPLICATION_ID,
- logicFunctionUniversalIdentifiers: ALL_UNIVERSAL_IDENTIFIERS,
- });
-
- expect(driver.installPrebuiltBundle).toHaveBeenCalledTimes(1);
- expect(driver.installPrebuiltBundle).toHaveBeenCalledWith(
- expect.objectContaining({
- flatLogicFunction: expect.objectContaining({ id: 'outdated' }),
- }),
- );
- });
-
- it('only touches the listed functions', async () => {
- setFlatLogicFunctions([
- buildFlatLogicFunction({ id: 'ready-1' }),
- buildFlatLogicFunction({ id: 'ready-2' }),
- ]);
-
- await service.warmUpApplicationLogicFunctions({
- workspaceId: WORKSPACE_ID,
- applicationId: APPLICATION_ID,
- logicFunctionUniversalIdentifiers: ['universal-ready-2'],
- });
-
- expect(driver.installPrebuiltBundle).toHaveBeenCalledTimes(1);
- expect(driver.installPrebuiltBundle).toHaveBeenCalledWith(
- expect.objectContaining({
- flatLogicFunction: expect.objectContaining({ id: 'ready-2' }),
- }),
- );
- });
-
- it('builds the functions in chunks of ten', async () => {
- const flatLogicFunctions = Array.from({ length: 15 }, (_, index) =>
- buildFlatLogicFunction({ id: `function-${index}` }),
- );
-
- setFlatLogicFunctions(flatLogicFunctions);
-
- let inFlight = 0;
- let maxInFlight = 0;
-
- driver.installPrebuiltBundle.mockImplementation(async () => {
- inFlight += 1;
- maxInFlight = Math.max(maxInFlight, inFlight);
- await Promise.resolve();
- inFlight -= 1;
- });
-
- await service.warmUpApplicationLogicFunctions({
- workspaceId: WORKSPACE_ID,
- applicationId: APPLICATION_ID,
- logicFunctionUniversalIdentifiers: flatLogicFunctions.map(
- (flatLogicFunction) => flatLogicFunction.universalIdentifier,
- ),
- });
-
- expect(driver.installPrebuiltBundle).toHaveBeenCalledTimes(15);
- expect(maxInFlight).toBe(10);
- });
-
- it('does nothing when the application is no longer installed', async () => {
- setFlatLogicFunctions([buildFlatLogicFunction({ id: 'ready-1' })], {
- withApplication: false,
- });
-
- await service.warmUpApplicationLogicFunctions({
- workspaceId: WORKSPACE_ID,
- applicationId: APPLICATION_ID,
- logicFunctionUniversalIdentifiers: ALL_UNIVERSAL_IDENTIFIERS,
- });
-
- expect(driver.installPrebuiltBundle).not.toHaveBeenCalled();
- });
-
- it('keeps installing the other functions and throws when one install fails', async () => {
- setFlatLogicFunctions([
- buildFlatLogicFunction({ id: 'ready-1' }),
- buildFlatLogicFunction({ id: 'failing' }),
- buildFlatLogicFunction({ id: 'ready-2' }),
- ]);
- driver.installPrebuiltBundle.mockImplementation(
- async ({ flatLogicFunction }: { flatLogicFunction: { id: string } }) => {
- if (flatLogicFunction.id === 'failing') {
- throw new Error('lambda unavailable');
- }
- },
- );
-
- await expect(
- service.warmUpApplicationLogicFunctions({
- workspaceId: WORKSPACE_ID,
- applicationId: APPLICATION_ID,
- logicFunctionUniversalIdentifiers: ALL_UNIVERSAL_IDENTIFIERS,
- }),
- ).rejects.toThrow(
- /Failed to warm up 1 of 3 prebuilt logic functions .*: failing: Failed to install the prebuilt bundle for function 'failing'/,
- );
-
- expect(driver.installPrebuiltBundle).toHaveBeenCalledTimes(3);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/__tests__/logic-function-job-runner.service.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/__tests__/logic-function-job-runner.service.spec.ts
deleted file mode 100644
index 30743f07a8d..00000000000
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-trigger/__tests__/logic-function-job-runner.service.spec.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import {
- RETRYABLE_LOGIC_FUNCTION_ERROR_NAME,
- RetryableLogicFunctionError,
-} from 'twenty-shared/logic-function';
-
-import { type LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
-import { LogicFunctionJobRunnerService } from 'src/engine/core-modules/logic-function/logic-function-trigger/logic-function-job-runner.service';
-import {
- UsageLimitException,
- UsageLimitExceptionCode,
-} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
-import {
- LogicFunctionException,
- LogicFunctionExceptionCode,
-} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
-
-describe('LogicFunctionJobRunnerService', () => {
- const logicFunctionPayload = {
- logicFunctionId: 'logic-function-id',
- workspaceId: 'workspace-id',
- payload: { newVersion: '1.4.1' },
- };
-
- const buildService = (
- execute: jest.Mock,
- ): {
- service: LogicFunctionJobRunnerService;
- persistRetryCount: jest.Mock;
- } => ({
- service: new LogicFunctionJobRunnerService({
- execute,
- } as unknown as LogicFunctionExecutorService),
- persistRetryCount: jest.fn(),
- });
-
- it('does not retry a successful execution', async () => {
- const execute = jest.fn().mockResolvedValue({});
- const { service, persistRetryCount } = buildService(execute);
-
- await service.run({
- logicFunctionPayload,
- retryLimit: 3,
- persistRetryCount,
- });
-
- expect(execute).toHaveBeenCalledWith(
- expect.objectContaining({
- logicFunctionId: 'logic-function-id',
- workspaceId: 'workspace-id',
- retry: { retryCount: 0, maxRetries: 3 },
- }),
- );
- expect(persistRetryCount).not.toHaveBeenCalled();
- });
-
- it('persists the next retry count and fails the job on a retryable error', async () => {
- const execute = jest.fn().mockResolvedValue({
- error: {
- errorType: RETRYABLE_LOGIC_FUNCTION_ERROR_NAME,
- errorMessage: 'sandbox unavailable',
- },
- });
- const { service, persistRetryCount } = buildService(execute);
-
- await expect(
- service.run({
- logicFunctionPayload: {
- ...logicFunctionPayload,
- applicationRetryCount: 1,
- },
- retryLimit: 3,
- persistRetryCount,
- }),
- ).rejects.toThrow(RetryableLogicFunctionError);
-
- expect(persistRetryCount).toHaveBeenCalledWith(2);
- });
-
- it('stops retrying once the retry limit is reached', async () => {
- const execute = jest.fn().mockResolvedValue({
- error: {
- errorType: RETRYABLE_LOGIC_FUNCTION_ERROR_NAME,
- errorMessage: 'sandbox unavailable',
- },
- });
- const { service, persistRetryCount } = buildService(execute);
-
- await service.run({
- logicFunctionPayload: {
- ...logicFunctionPayload,
- applicationRetryCount: 3,
- },
- retryLimit: 3,
- persistRetryCount,
- });
-
- expect(persistRetryCount).not.toHaveBeenCalled();
- });
-
- it('does not fail the job when usage was refused', async () => {
- const execute = jest
- .fn()
- .mockRejectedValue(
- new UsageLimitException(
- 'Usage limit reached for workspace',
- UsageLimitExceptionCode.QUOTA_EXHAUSTED,
- ),
- );
- const { service, persistRetryCount } = buildService(execute);
-
- await service.run({
- logicFunctionPayload,
- retryLimit: 3,
- persistRetryCount,
- });
-
- expect(persistRetryCount).not.toHaveBeenCalled();
- });
-
- it('does not fail the job when the application is stopped', async () => {
- const execute = jest
- .fn()
- .mockRejectedValue(
- new LogicFunctionException(
- 'Application is stopped',
- LogicFunctionExceptionCode.LOGIC_FUNCTION_DISABLED,
- ),
- );
- const { service, persistRetryCount } = buildService(execute);
-
- await service.run({
- logicFunctionPayload,
- retryLimit: 3,
- persistRetryCount,
- });
-
- expect(persistRetryCount).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/__tests__/onboarding.service.spec.ts b/packages/twenty-server/src/engine/core-modules/onboarding/__tests__/onboarding.service.spec.ts
deleted file mode 100644
index dcff585aef7..00000000000
--- a/packages/twenty-server/src/engine/core-modules/onboarding/__tests__/onboarding.service.spec.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-import { getDataSourceToken, getRepositoryToken } from '@nestjs/typeorm';
-
-import { type DataSource } from 'typeorm';
-
-import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
-import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
-import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';
-import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
-import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
-import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
-import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
-import { getQueueToken } from 'src/engine/core-modules/message-queue/utils/get-queue-token.util';
-import { OnboardingService } from 'src/engine/core-modules/onboarding/onboarding.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { UserVarsService } from 'src/engine/core-modules/user/user-vars/services/user-vars.service';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
-import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
-
-describe('OnboardingService', () => {
- let service: OnboardingService;
-
- const userId = 'user-id';
- const workspaceId = 'workspace-id';
- const creditTiers = {
- midMarket: { minEmployeeCount: 20, amountMicro: 5_000_000 },
- };
-
- // The book-call step deliberately asks for a far bigger company than the
- // credit reward, so the two bars cannot be confused for one another.
- const bookCallMinEmployeeCount = 200;
-
- const configValues: Record<string, unknown> = {
- CALENDAR_BOOKING_PAGE_ID: 'team/twenty/talk-to-us',
- ONBOARDING_BOOK_CALL_MIN_EMPLOYEE_COUNT: bookCallMinEmployeeCount,
- ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS: creditTiers,
- };
-
- const grantCredits = jest.fn();
- const captureExceptions = jest.fn();
- const setIfNotExists = jest.fn();
- const getConfig = jest.fn();
-
- beforeEach(async () => {
- grantCredits.mockResolvedValue(null);
- setIfNotExists.mockResolvedValue(true);
- getConfig.mockImplementation((key: string) => configValues[key]);
-
- const dataSource = {
- transaction: jest.fn((runInTransaction) =>
- runInTransaction({ queryRunner: {} }),
- ),
- } as unknown as DataSource;
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- OnboardingService,
- { provide: BillingService, useValue: { isBillingEnabled: jest.fn() } },
- { provide: BillingCreditService, useValue: { grantCredits } },
- { provide: BillingCreditGrantService, useValue: {} },
- { provide: CacheLockService, useValue: {} },
- {
- provide: ExceptionHandlerService,
- useValue: { captureExceptions },
- },
- {
- provide: UserVarsService,
- useValue: {
- get: jest.fn(),
- set: jest.fn(),
- delete: jest.fn(),
- setIfNotExists,
- },
- },
- { provide: TwentyConfigService, useValue: { get: getConfig } },
- { provide: getRepositoryToken(WorkspaceEntity), useValue: {} },
- { provide: getRepositoryToken(UserWorkspaceEntity), useValue: {} },
- {
- provide: getQueueToken(MessageQueue.workspaceQueue),
- useValue: { add: jest.fn() },
- },
- { provide: getDataSourceToken(), useValue: dataSource },
- ],
- }).compile();
-
- service = module.get<OnboardingService>(OnboardingService);
- });
-
- afterEach(() => {
- jest.resetAllMocks();
- });
-
- describe('creditEnrichmentQualificationReward', () => {
- it('grants the amount of the tier the enriched company lands in', async () => {
- await service.creditEnrichmentQualificationReward({
- workspaceId,
- employeeCount: 20,
- });
-
- expect(grantCredits).toHaveBeenCalledTimes(1);
- expect(grantCredits).toHaveBeenCalledWith(
- expect.objectContaining({
- workspaceId,
- amountMicro: 5_000_000,
- type: BillingCreditGrantType.ONBOARDING_REWARD,
- idempotencyKey: `onboarding-enrichment-qualified:${workspaceId}`,
- }),
- );
- });
-
- it('grants nothing to a company below every tier', async () => {
- await service.creditEnrichmentQualificationReward({
- workspaceId,
- employeeCount: 19,
- });
-
- expect(grantCredits).not.toHaveBeenCalled();
- });
-
- it('grants nothing to a workspace enrichment could not match', async () => {
- await service.creditEnrichmentQualificationReward({
- workspaceId,
- employeeCount: null,
- });
-
- expect(grantCredits).not.toHaveBeenCalled();
- });
-
- it('grants nothing while no tier is configured', async () => {
- getConfig.mockImplementation((key: string) =>
- key === 'ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS'
- ? {}
- : configValues[key],
- );
-
- await service.creditEnrichmentQualificationReward({
- workspaceId,
- employeeCount: 5000,
- });
-
- expect(grantCredits).not.toHaveBeenCalled();
- });
-
- it('swallows a billing failure so enrichment still completes', async () => {
- grantCredits.mockRejectedValue(new Error('billing is down'));
-
- await expect(
- service.creditEnrichmentQualificationReward({
- workspaceId,
- employeeCount: 5000,
- }),
- ).resolves.toBeUndefined();
- });
-
- it('reports malformed tiers to Sentry and pays the well-formed ones', async () => {
- getConfig.mockImplementation((key: string) =>
- key === 'ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS'
- ? { broken: { minEmployeeCount: 'twenty' }, ...creditTiers }
- : configValues[key],
- );
-
- await service.creditEnrichmentQualificationReward({
- workspaceId,
- employeeCount: 20,
- });
-
- expect(captureExceptions).toHaveBeenCalledTimes(1);
- expect(captureExceptions.mock.calls[0][0][0].message).toContain('broken');
- expect(grantCredits).toHaveBeenCalledWith(
- expect.objectContaining({ amountMicro: 5_000_000 }),
- );
- });
-
- it('survives a tier config too malformed to even read, and reports it', async () => {
- // The JSON config transformer throws rather than returning a value when
- // the configured tiers are not a parseable object.
- getConfig.mockImplementation((key: string) => {
- if (key === 'ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS') {
- throw new Error('Failed to parse JSON string');
- }
-
- return configValues[key];
- });
-
- await expect(
- service.creditEnrichmentQualificationReward({
- workspaceId,
- employeeCount: 20,
- }),
- ).resolves.toBeUndefined();
-
- expect(grantCredits).not.toHaveBeenCalled();
- expect(captureExceptions).toHaveBeenCalledTimes(1);
- });
-
- it('grants credits even when the book-a-call step is switched off', async () => {
- getConfig.mockImplementation((key: string) =>
- key === 'CALENDAR_BOOKING_PAGE_ID' ||
- key === 'ONBOARDING_BOOK_CALL_MIN_EMPLOYEE_COUNT'
- ? undefined
- : configValues[key],
- );
-
- await service.creditEnrichmentQualificationReward({
- workspaceId,
- employeeCount: 20,
- });
-
- expect(grantCredits).toHaveBeenCalledWith(
- expect.objectContaining({ amountMicro: 5_000_000 }),
- );
- });
- });
-
- describe('setOnboardingBookCallPendingIfQualified', () => {
- it('offers the call without granting credits', async () => {
- const hasQualified =
- await service.setOnboardingBookCallPendingIfQualified({
- userId,
- workspaceId,
- employeeCount: bookCallMinEmployeeCount,
- });
-
- expect(hasQualified).toBe(true);
- expect(grantCredits).not.toHaveBeenCalled();
- });
-
- it('withholds the call from a company that only clears the credit tier', async () => {
- const hasQualified =
- await service.setOnboardingBookCallPendingIfQualified({
- userId,
- workspaceId,
- employeeCount: 20,
- });
-
- expect(hasQualified).toBe(false);
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/record-export/services/__tests__/record-export.workspace-service.spec.ts b/packages/twenty-server/src/engine/core-modules/record-export/services/__tests__/record-export.workspace-service.spec.ts
deleted file mode 100644
index d7cf130b594..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-export/services/__tests__/record-export.workspace-service.spec.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { Test } from '@nestjs/testing';
-
-import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
-import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
-import { RECORD_EXPORT_DOWNLOAD_TOKEN_TTL_SECONDS } from 'src/engine/core-modules/record-export/constants/record-export.constants';
-import { RecordExportWorkspaceService } from 'src/engine/core-modules/record-export/services/record-export.workspace-service';
-
-describe('RecordExportWorkspaceService', () => {
- it('returns an API-relative download path with a token bound to the requester', async () => {
- const jwtWrapperService = {
- signAsyncOrThrow: jest.fn().mockResolvedValue('signed-token'),
- };
- const module = await Test.createTestingModule({
- providers: [
- RecordExportWorkspaceService,
- { provide: JwtWrapperService, useValue: jwtWrapperService },
- ],
- })
- .useMocker(() => ({}))
- .compile();
- const service = module.get(RecordExportWorkspaceService);
- jest.spyOn(service, 'resolveRequester').mockResolvedValue({} as never);
- jest.spyOn(service, 'assertPermissionsUnchanged').mockResolvedValue();
- jest.spyOn(service, 'findOrThrow').mockResolvedValue({} as never);
-
- const recordExport = {
- id: 'export-id',
- workspaceId: 'workspace-id',
- userWorkspaceId: 'user-workspace-id',
- workspaceMemberId: 'workspace-member-id',
- requestTokenHash: 'request-token-hash',
- permissionsHash: 'permissions-hash',
- filename: 'company.csv',
- };
-
- await expect(service.getDownloadPath(recordExport)).resolves.toBe(
- '/file/record-export/export-id?token=signed-token',
- );
- expect(jwtWrapperService.signAsyncOrThrow).toHaveBeenCalledWith(
- {
- type: JwtTokenTypeEnum.FILE,
- purpose: 'record-export',
- sub: recordExport.workspaceId,
- workspaceId: recordExport.workspaceId,
- fileId: recordExport.id,
- userWorkspaceId: recordExport.userWorkspaceId,
- workspaceMemberId: recordExport.workspaceMemberId,
- requestTokenHash: recordExport.requestTokenHash,
- permissionsHash: recordExport.permissionsHash,
- filename: recordExport.filename,
- },
- { expiresIn: RECORD_EXPORT_DOWNLOAD_TOKEN_TTL_SECONDS },
- );
- await module.close();
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/services/__tests__/record-access-policy.service.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/services/__tests__/record-access-policy.service.spec.ts
deleted file mode 100644
index 383d052660e..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/services/__tests__/record-access-policy.service.spec.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { Test } from '@nestjs/testing';
-import {
- MetadataReadability,
- RecordShareRowCause,
- RecordShareAccessLevel,
-} from 'twenty-shared/types';
-import { RecordAccessPolicyService } from 'src/engine/core-modules/record-share/services/record-access-policy.service';
-import { RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';
-import { COMPANY_FLAT_OBJECT_MOCK } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/company-flat-object.mock';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-
-const setup = async ({ rowCause }: { rowCause?: RecordShareRowCause } = {}) => {
- const module = await Test.createTestingModule({
- providers: [
- RecordAccessPolicyService,
- { provide: WorkspaceOrmManager, useValue: {} },
- { provide: WorkspaceCacheService, useValue: {} },
- {
- provide: RecordShareStorageService,
- useValue: {
- findByRecordIds: jest.fn().mockResolvedValue(
- rowCause
- ? [
- {
- recordId: 'record',
- principalId: 'member',
- rowCause,
- accessLevel: RecordShareAccessLevel.FULL,
- },
- ]
- : [],
- ),
- },
- },
- ],
- }).compile();
- const gate = (readability: MetadataReadability) =>
- module.get(RecordAccessPolicyService).buildEventRecordAccessGate({
- name: 'company.created',
- workspaceId: COMPANY_FLAT_OBJECT_MOCK.workspaceId,
- objectMetadata: { ...COMPANY_FLAT_OBJECT_MOCK, readability },
- events: [{ recordId: 'record', properties: { after: { id: 'record' } } }],
- });
- return { module, gate };
-};
-
-const subject = {
- isSystemContext: false,
- objectsPermissions: undefined,
- principalIds: ['member'],
- isOwningApplication: () => false,
- resolveRowLevelPermissionRecordFilter: () => null,
-};
-
-describe('mandatory event visibility', () => {
- it('loads record grants once per batch across concurrent subscribers', async () => {
- const { module, gate } = await setup({
- rowCause: RecordShareRowCause.OWNER,
- });
- const eventGate = gate(MetadataReadability.PRIVATE);
- const admitted = await Promise.all([
- eventGate.resolveAdmittedRecordIds(subject),
- eventGate.resolveAdmittedRecordIds({
- ...subject,
- principalIds: ['other-member'],
- }),
- ]);
- expect(admitted).toEqual([new Set(['record']), new Set()]);
- expect(
- module.get(RecordShareStorageService).findByRecordIds,
- ).toHaveBeenCalledTimes(1);
- await gate(MetadataReadability.PRIVATE).resolveAdmittedRecordIds(subject);
- expect(
- module.get(RecordShareStorageService).findByRecordIds,
- ).toHaveBeenCalledTimes(2);
- await module.close();
- });
-
- it.each([true, false])(
- 'denies SYSTEM records with owning application=%s',
- async (isOwningApplication) => {
- const { module, gate } = await setup();
- expect(
- await gate(MetadataReadability.SYSTEM).resolveAdmittedRecordIds({
- ...subject,
- isOwningApplication: () => isOwningApplication,
- }),
- ).toEqual(new Set());
- await module.close();
- },
- );
-
- it.each([
- RecordShareRowCause.OWNER,
- RecordShareRowCause.APPLICATION,
- RecordShareRowCause.MANUAL,
- ])('honors %s grants after metadata activation', async (rowCause) => {
- const { module, gate } = await setup({ rowCause });
- expect(
- await gate(MetadataReadability.PRIVATE).resolveAdmittedRecordIds(subject),
- ).toEqual(new Set(['record']));
- await module.close();
- });
-
- it('denies unshared private events', async () => {
- const { module, gate } = await setup();
- expect(
- await gate(MetadataReadability.PRIVATE).resolveAdmittedRecordIds(subject),
- ).toEqual(new Set());
- await module.close();
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/services/__tests__/record-share-storage.service.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/services/__tests__/record-share-storage.service.spec.ts
deleted file mode 100644
index 80c88bdc333..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/services/__tests__/record-share-storage.service.spec.ts
+++ /dev/null
@@ -1,146 +0,0 @@
-import {
- RecordShareAccessLevel,
- RecordSharePrincipalType,
- RecordShareRowCause,
-} from 'twenty-shared/types';
-
-import { RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';
-import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/types/workspace-transaction-scope.type';
-import { type RecordShareInput } from 'src/engine/core-modules/record-share/types/record-share-input.type';
-
-const share = {
- objectMetadataId: 'object',
- recordId: 'record',
- principalId: 'member',
- principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
- accessLevel: RecordShareAccessLevel.READ,
- sourceId: 'record',
-};
-
-const buildService = () => {
- let rows: RecordShareInput[] = [
- { ...share, rowCause: RecordShareRowCause.OWNER },
- {
- ...share,
- sourceId: 'application',
- rowCause: RecordShareRowCause.APPLICATION,
- },
- ];
- const repository = {
- delete: jest
- .fn()
- .mockImplementation(async (where: Partial<RecordShareInput>) => {
- rows = rows.filter(
- (row) =>
- !Object.entries(where).every(
- ([key, value]) => row[key as keyof RecordShareInput] === value,
- ),
- );
- }),
- insert: jest.fn().mockImplementation(async (row: RecordShareInput) => {
- rows.push(row);
- }),
- };
- const scope = {
- workspaceId: 'workspace',
- getRepository: () => repository,
- executeRawQuery: jest.fn(),
- };
- const manager = {
- executeInWorkspaceContext: jest
- .fn()
- .mockImplementation((work: () => Promise<void>) => work()),
- runInWorkspaceTransaction: jest
- .fn()
- .mockImplementation(async (work: (scope: unknown) => Promise<void>) => {
- const before = [...rows];
- try {
- await work(scope);
- } catch (error) {
- rows = before;
- throw error;
- }
- }),
- };
- const service = new RecordShareStorageService(manager as never);
- const setManualShare = (
- args: Omit<
- Parameters<RecordShareStorageService['setManualShare']>[0],
- 'transactionScope'
- >,
- ) =>
- manager.runInWorkspaceTransaction(
- (transactionScope: WorkspaceTransactionScope) =>
- service.setManualShare({ ...args, transactionScope }),
- );
- return {
- setManualShare,
- repository,
- rows: () => rows,
- scope,
- };
-};
-
-describe('Manual record share management', () => {
- it('is idempotent and preserves owner and application grants', async () => {
- const { setManualShare, rows } = buildService();
- await setManualShare({
- workspaceId: 'workspace',
- share,
- enabled: true,
- });
- await setManualShare({
- workspaceId: 'workspace',
- share,
- enabled: true,
- });
- expect(rows()).toHaveLength(3);
- await setManualShare({
- workspaceId: 'workspace',
- share,
- enabled: false,
- });
- expect(rows().map((row) => row.rowCause)).toEqual([
- RecordShareRowCause.OWNER,
- RecordShareRowCause.APPLICATION,
- ]);
- });
-
- it('revokes manual grants regardless of their author without touching another record', async () => {
- const { setManualShare, rows } = buildService();
- await setManualShare({
- workspaceId: 'workspace',
- share,
- enabled: true,
- });
- await setManualShare({
- workspaceId: 'workspace',
- share: { ...share, recordId: 'another-record' },
- enabled: true,
- });
- await setManualShare({
- workspaceId: 'workspace',
- share: { ...share, sourceId: 'another-source' },
- enabled: false,
- });
- expect(rows()).toHaveLength(3);
- });
-
- it('rolls back replacement if the insert fails', async () => {
- const { setManualShare, rows, repository } = buildService();
- await setManualShare({
- workspaceId: 'workspace',
- share,
- enabled: true,
- });
- repository.insert.mockRejectedValueOnce(new Error('write failed'));
- await expect(
- setManualShare({
- workspaceId: 'workspace',
- share,
- enabled: true,
- }),
- ).rejects.toThrow('write failed');
- expect(rows()).toHaveLength(3);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/services/__tests__/record-sharing.service.spec.ts b/packages/twenty-server/src/engine/core-modules/record-share/services/__tests__/record-sharing.service.spec.ts
deleted file mode 100644
index f4cd3c850e1..00000000000
--- a/packages/twenty-server/src/engine/core-modules/record-share/services/__tests__/record-sharing.service.spec.ts
+++ /dev/null
@@ -1,368 +0,0 @@
-import { EVERYONE_PRINCIPAL_ID } from 'twenty-shared/constants';
-import {
- MetadataReadability,
- RecordShareAccessLevel,
-} from 'twenty-shared/types';
-
-import { RecordSharingService } from 'src/engine/core-modules/record-share/services/record-sharing.service';
-
-const MEMBER_ID = '20202020-0000-4000-8000-000000000003';
-const ROLE_ID = '20202020-0000-4000-8000-000000000004';
-const args = {
- objectMetadataId: 'object',
- recordId: 'record',
- authContext: {
- type: 'user',
- workspaceMemberId: MEMBER_ID,
- workspace: { id: '20202020-0000-4000-8000-000000000001' },
- userWorkspaceId: 'writer',
- } as never,
-};
-const change = {
- ...args,
- principal: { everyone: true },
- accessLevel: RecordShareAccessLevel.READ,
- enabled: true,
-};
-
-const buildService = () => {
- const objectMetadata = {
- id: 'object',
- nameSingular: 'note',
- readability: MetadataReadability.PRIVATE,
- };
- const maps = {
- userWorkspaceRoleMap: { writer: ROLE_ID },
- apiKeyRoleMap: {},
- flatObjectMetadataMaps: {
- universalIdentifierById: { object: 'object' },
- byUniversalIdentifier: { object: objectMetadata },
- },
- flatWorkspaceMemberMaps: {
- byId: { [MEMBER_ID]: { id: MEMBER_ID, deletedAt: null } },
- },
- flatRoleMaps: {
- universalIdentifierById: { [ROLE_ID]: 'role' },
- byUniversalIdentifier: {
- role: { id: ROLE_ID, label: 'Sales', canBeAssignedToUsers: true },
- },
- },
- };
- const cache = { getOrRecompute: jest.fn().mockResolvedValue(maps) };
- const allowed = new Set(['select', 'update']);
- const repository = {
- findRecordIdsAllowedForOperation: jest
- .fn()
- .mockImplementation(async ({ operationType, recordIds }) =>
- allowed.has(operationType) ? recordIds : [],
- ),
- };
- const scope = {
- workspaceId: '20202020-0000-4000-8000-000000000001',
- getRepository: () => repository,
- executeRawQuery: jest.fn().mockResolvedValue([{ id: 'record' }]),
- };
- const manager = {
- getRepositoryWithContextPermissions: () => repository,
- executeInWorkspaceContext: jest
- .fn()
- .mockImplementation(async (work: () => Promise<unknown>) => work()),
- runInWorkspaceTransaction: jest
- .fn()
- .mockImplementation(async (work: (scope: unknown) => Promise<unknown>) =>
- work(scope),
- ),
- };
- const grant = {
- principalId: MEMBER_ID,
- principalType: 'WORKSPACE_MEMBER',
- accessLevel: RecordShareAccessLevel.FULL,
- rowCause: 'MANUAL',
- };
- const shares = {
- findByRecordIds: jest.fn().mockResolvedValue([grant]),
- setManualShare: jest.fn(),
- };
- const service = new RecordSharingService(
- manager as never,
- cache as never,
- shares as never,
- );
- return {
- service,
- grant,
- objectMetadata,
- maps,
- repository,
- allowed,
- shares,
- scope,
- };
-};
-
-describe('Generic record sharing', () => {
- it('returns distinct operation capabilities from ordinary record policy', async () => {
- const { service } = buildService();
- await expect(service.getPermissions(args)).resolves.toEqual({
- canRead: true,
- canUpdate: true,
- canDelete: false,
- canSoftDelete: false,
- });
- });
-
- it('evaluates response permissions once after changing a grant', async () => {
- const { service, repository } = buildService();
- await service.setShare(change);
- expect(repository.findRecordIdsAllowedForOperation).toHaveBeenCalledTimes(
- 5,
- );
- });
-
- it('includes authorized deleted records in generic sharing and permission queries', async () => {
- const { service, repository } = buildService();
- await service.getSharing(args);
- expect(repository.findRecordIdsAllowedForOperation).toHaveBeenCalledWith(
- expect.objectContaining({ operationType: 'select', withDeleted: true }),
- );
- repository.findRecordIdsAllowedForOperation.mockClear();
- await service.setShare(change);
- expect(repository.findRecordIdsAllowedForOperation).toHaveBeenCalledWith(
- expect.objectContaining({ operationType: 'update', withDeleted: true }),
- );
- });
-
- it('does not expose the audience to read-only recipients', async () => {
- const { service, allowed, shares } = buildService();
- allowed.delete('update');
- await expect(service.getSharing(args)).resolves.toMatchObject({
- isEnabled: true,
- shares: [],
- roles: [],
- permissions: { canUpdate: false },
- });
- await expect(service.setShare(change)).rejects.toThrow('Record not found');
- expect(shares.setManualShare).not.toHaveBeenCalled();
- });
-
- it('keeps labels for existing application roles without offering unrelated application roles', async () => {
- const { service, maps, shares, grant } = buildService();
- maps.flatRoleMaps.byUniversalIdentifier.role.canBeAssignedToUsers = false;
- expect((await service.getSharing(args)).roles).toEqual([]);
- shares.findByRecordIds.mockResolvedValue([
- grant,
- { principalType: 'ROLE', principalId: ROLE_ID, rowCause: 'APPLICATION' },
- ]);
- expect((await service.getSharing(args)).roles).toEqual([
- { id: ROLE_ID, label: 'Sales' },
- ]);
- });
-
- it('does not reveal records outside the authenticated workspace', async () => {
- const { service } = buildService();
- await expect(
- service.getSharing({ ...args, objectMetadataId: 'foreign-object' }),
- ).rejects.toThrow('Record not found');
- await expect(
- service.setShare({ ...change, objectMetadataId: 'foreign-object' }),
- ).rejects.toThrow('Record not found');
- });
-
- it.each([
- { everyone: true },
- { workspaceMemberId: MEMBER_ID },
- { roleId: ROLE_ID },
- ])(
- 'lets a FULL holder manage %j without a separate ownership check',
- async (principal) => {
- const { service, shares, scope } = buildService();
- await service.setShare({ ...change, principal });
- expect(shares.setManualShare).toHaveBeenCalledWith(
- expect.objectContaining({
- transactionScope: scope,
- workspaceId: '20202020-0000-4000-8000-000000000001',
- enabled: true,
- share: expect.objectContaining({
- objectMetadataId: 'object',
- recordId: 'record',
- accessLevel: 'READ',
- }),
- }),
- );
- expect(scope.executeRawQuery).toHaveBeenCalledWith(
- expect.stringContaining('FOR UPDATE'),
- ['record'],
- );
- },
- );
-
- it.each(Object.values(RecordShareAccessLevel))(
- 'allows a FULL holder to grant %s within the authorization transaction',
- async (accessLevel) => {
- const { service, shares, scope } = buildService();
- await service.setShare({ ...change, accessLevel });
- expect(shares.setManualShare).toHaveBeenCalledWith(
- expect.objectContaining({
- share: expect.objectContaining({ accessLevel }),
- }),
- );
- expect(shares.findByRecordIds).toHaveBeenCalledWith(
- expect.objectContaining({ transactionScope: scope }),
- );
- },
- );
-
- it.each([RecordShareAccessLevel.READ, RecordShareAccessLevel.READ_WRITE])(
- 'hides the audience and denies all grant mutations for %s even with update permission',
- async (accessLevel) => {
- const { service, shares, grant } = buildService();
- grant.accessLevel = accessLevel;
- await expect(service.getSharing(args)).resolves.toMatchObject({
- viewerAccessLevel: accessLevel,
- permissions: { canUpdate: true },
- shares: [],
- roles: [],
- });
- for (const enabled of [true, false]) {
- for (const requestedLevel of Object.values(RecordShareAccessLevel)) {
- await expect(
- service.setShare({
- ...change,
- enabled,
- accessLevel: requestedLevel,
- }),
- ).rejects.toThrow('Record not found');
- }
- }
- expect(shares.setManualShare).not.toHaveBeenCalled();
- },
- );
-
- it.each([MEMBER_ID, ROLE_ID, EVERYONE_PRINCIPAL_ID])(
- 'resolves FULL from the existing member, role or everyone principal %s',
- async (principalId) => {
- const { service, grant } = buildService();
- grant.principalId = principalId;
- await expect(service.setShare(change)).resolves.toMatchObject({
- viewerAccessLevel: RecordShareAccessLevel.FULL,
- });
- },
- );
-
- it('does not use another principal’s FULL grant to authorize an editor', async () => {
- const { service, shares, grant } = buildService();
- grant.accessLevel = RecordShareAccessLevel.READ_WRITE;
- shares.findByRecordIds.mockResolvedValue([
- grant,
- {
- ...grant,
- principalId: 'another-member',
- accessLevel: RecordShareAccessLevel.FULL,
- },
- ]);
- await expect(service.setShare(change)).rejects.toThrow('Record not found');
- expect(shares.setManualShare).not.toHaveBeenCalled();
- });
-
- it.each([
- MetadataReadability.SYSTEM,
- MetadataReadability.APPLICATION,
- MetadataReadability.OPEN,
- ])('does not manage grants on %s objects', async (readability) => {
- const { service, objectMetadata, shares } = buildService();
- objectMetadata.readability = readability;
- await expect(service.getSharing(args)).resolves.toMatchObject({
- isEnabled: false,
- });
- await expect(service.setShare(change)).rejects.toThrow('Record not found');
- expect(shares.setManualShare).not.toHaveBeenCalled();
- });
-
- it('explains inherited access for objects with parent permissions', async () => {
- const { service, objectMetadata } = buildService();
- objectMetadata.readability = MetadataReadability.INHERITED;
- await expect(service.getSharing(args)).resolves.toMatchObject({
- isEnabled: true,
- hasInheritedAccess: true,
- });
- });
-
- it('does not turn inherited edit access into permission to manage direct grants', async () => {
- const { service, objectMetadata, shares } = buildService();
- objectMetadata.readability = MetadataReadability.INHERITED;
- shares.findByRecordIds.mockResolvedValue([]);
- await expect(service.getSharing(args)).resolves.toMatchObject({
- viewerAccessLevel: null,
- permissions: { canUpdate: true },
- hasInheritedAccess: true,
- shares: [],
- roles: [],
- });
- await expect(service.setShare(change)).rejects.toThrow('Record not found');
- expect(shares.setManualShare).not.toHaveBeenCalled();
- });
-
- it('denies nonexistent or unreadable records without exposing audience data', async () => {
- const { service, allowed, shares } = buildService();
- allowed.clear();
- await expect(service.getSharing(args)).rejects.toThrow('Record not found');
- await expect(service.setShare(change)).rejects.toThrow('Record not found');
- expect(shares.findByRecordIds).not.toHaveBeenCalled();
- expect(shares.setManualShare).not.toHaveBeenCalled();
- });
-
- it('allows revocation for a removed recipient', async () => {
- const { service, shares } = buildService();
- await service.setShare({
- ...change,
- principal: { workspaceMemberId: ROLE_ID },
- enabled: false,
- });
- expect(shares.setManualShare).toHaveBeenCalledTimes(1);
- });
-
- it('rejects ambiguous and cross-workspace recipients', async () => {
- const { service, shares } = buildService();
- for (const principal of [
- { everyone: true, roleId: ROLE_ID },
- { workspaceMemberId: ROLE_ID },
- ]) {
- await expect(
- service.setShare({ ...change, principal }),
- ).rejects.toMatchObject({ code: 'INVALID_SHARE_WITH' });
- }
- expect(shares.setManualShare).not.toHaveBeenCalled();
- });
-
- it('successfully redacts the response after a writer revokes their own access', async () => {
- const { service, shares, allowed } = buildService();
- shares.setManualShare.mockImplementation(async () => allowed.clear());
- await expect(
- service.setShare({
- ...change,
- principal: { workspaceMemberId: MEMBER_ID },
- enabled: false,
- }),
- ).resolves.toEqual({
- viewerAccessLevel: null,
- permissions: {
- canRead: false,
- canUpdate: false,
- canDelete: false,
- canSoftDelete: false,
- },
- isEnabled: false,
- hasInheritedAccess: false,
- roles: [],
- shares: [],
- });
- });
-
- it('propagates storage failures without returning a successful save', async () => {
- const { service, shares } = buildService();
- shares.setManualShare.mockRejectedValue(new Error('Transaction failed'));
- await expect(service.setShare(change)).rejects.toThrow(
- 'Transaction failed',
- );
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/__tests__/secure-http-client.service.spec.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/__tests__/secure-http-client.service.spec.ts
deleted file mode 100644
index b8035a76d9d..00000000000
--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/__tests__/secure-http-client.service.spec.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { EventEmitter } from 'events';
-import * as http from 'http';
-import * as https from 'https';
-import { type Duplex } from 'stream';
-
-import { Logger } from '@nestjs/common';
-
-import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';
-import { type TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-
-describe('SecureHttpClientService', () => {
- const buildService = (config: {
- OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: string[];
- OUTBOUND_HTTP_SAFE_MODE_ENABLED?: boolean;
- }) =>
- new SecureHttpClientService({
- get: (key: keyof typeof config) => config[key],
- } as unknown as TwentyConfigService);
-
- describe('getSsrfSafeAgent', () => {
- it('returns an agent matching the URL protocol', () => {
- const service = buildService({
- OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: [],
- });
-
- expect(
- service.getSsrfSafeAgent(new URL('https://idp.example.com')),
- ).toBeInstanceOf(https.Agent);
- expect(
- service.getSsrfSafeAgent(new URL('http://idp.example.com')),
- ).toBeInstanceOf(http.Agent);
- });
-
- it('returns an agent that blocks a private address', () => {
- const service = buildService({
- OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: [],
- });
-
- const agent = service.getSsrfSafeAgent(
- new URL('http://169.254.169.254/latest/meta-data/'),
- ) as http.Agent;
-
- expect(() =>
- agent.createConnection(
- { host: '169.254.169.254' } as http.ClientRequestArgs,
- jest.fn(),
- ),
- ).toThrow(
- 'Request to internal IP address 169.254.169.254 is not allowed.',
- );
- });
-
- it('returns undefined when all internal hosts are allowed', () => {
- const service = buildService({
- OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: ['*'],
- });
-
- expect(
- service.getSsrfSafeAgent(new URL('http://keycloak:8080')),
- ).toBeUndefined();
- });
-
- it('honours the deprecated OUTBOUND_HTTP_SAFE_MODE_ENABLED=false and warns once', () => {
- const warnSpy = jest
- .spyOn(Logger.prototype, 'warn')
- .mockImplementation(() => undefined);
- const service = buildService({
- OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: ['keycloak'],
- OUTBOUND_HTTP_SAFE_MODE_ENABLED: false,
- });
-
- expect(
- service.getSsrfSafeAgent(new URL('http://keycloak:8080')),
- ).toBeUndefined();
- expect(
- service.getSsrfSafeAgent(new URL('http://10.0.0.1')),
- ).toBeUndefined();
- expect(warnSpy).toHaveBeenCalledTimes(1);
-
- warnSpy.mockRestore();
- });
-
- it('accepts a full URL or host:port entry and matches on the hostname', () => {
- const socket = new EventEmitter();
- const createConnectionSpy = jest
- .spyOn(http.Agent.prototype, 'createConnection')
- .mockReturnValue(socket as unknown as Duplex);
- const service = buildService({
- OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: [
- 'http://Keycloak:8080/realms/twenty',
- '[::1]:993',
- ],
- });
-
- const agent = service.getSsrfSafeAgent(
- new URL('http://keycloak:8080'),
- ) as http.Agent;
-
- agent.createConnection(
- { host: '::1' } as http.ClientRequestArgs,
- jest.fn(),
- );
- agent.createConnection(
- { host: 'keycloak' } as http.ClientRequestArgs,
- jest.fn(),
- );
- socket.emit('lookup', null, '172.18.0.5', 4, 'keycloak');
-
- expect(createConnectionSpy).toHaveBeenCalledTimes(2);
-
- createConnectionSpy.mockRestore();
- });
- });
-
- describe('getValidatedHost', () => {
- it('lets an allowed private IP through, ignoring surrounding whitespace', async () => {
- const service = buildService({
- OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: [' 192.168.1.10 '],
- });
-
- await expect(service.getValidatedHost('192.168.1.10')).resolves.toBe(
- '192.168.1.10',
- );
- });
-
- it('still blocks a private IP that is not allowed', async () => {
- const service = buildService({
- OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: ['192.168.1.10'],
- });
-
- await expect(service.getValidatedHost('10.0.0.1')).rejects.toThrow(
- 'Connection to internal IP address 10.0.0.1 is not allowed.',
- );
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/sso/services/__tests__/sso.service.spec.ts b/packages/twenty-server/src/engine/core-modules/sso/services/__tests__/sso.service.spec.ts
deleted file mode 100644
index ae8abd69d66..00000000000
--- a/packages/twenty-server/src/engine/core-modules/sso/services/__tests__/sso.service.spec.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-/* @license Enterprise */
-
-import * as http from 'http';
-
-import { custom, Issuer } from 'openid-client';
-
-import { type BillingService } from 'src/engine/core-modules/billing/services/billing.service';
-import { type ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
-import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';
-import { SsoService } from 'src/engine/core-modules/sso/services/sso.service';
-import { type TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import {
- IdentityProviderType,
- type WorkspaceSsoIdentityProviderEntity,
-} from 'src/engine/core-modules/sso/workspace-sso-identity-provider.entity';
-
-const METADATA_SERVICE_URL = new URL(
- 'http://169.254.169.254/latest/meta-data/',
-);
-
-const expectAgentToBlockMetadataService = (options: {
- agent?: http.Agent | boolean;
-}) => {
- expect(options.agent).toBeInstanceOf(http.Agent);
- expect(() =>
- (options.agent as http.Agent).createConnection(
- { host: METADATA_SERVICE_URL.hostname } as http.ClientRequestArgs,
- jest.fn(),
- ),
- ).toThrow('Request to internal IP address 169.254.169.254 is not allowed.');
-};
-
-describe('SsoService', () => {
- const originalIssuerHttpOptions = Issuer[custom.http_options];
-
- const buildSsoService = (allowedInternalHosts: string[] = []) => {
- const twentyConfigService = {
- get: (key: string) =>
- key === 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS'
- ? allowedInternalHosts
- : 'https://app.example.com',
- } as unknown as TwentyConfigService;
-
- return new SsoService(
- {} as never,
- twentyConfigService,
- {} as BillingService,
- {} as ExceptionHandlerService,
- new SecureHttpClientService(twentyConfigService),
- );
- };
-
- const oidcIdentityProvider = {
- type: IdentityProviderType.OIDC,
- id: 'idp-id',
- clientID: 'client-id',
- clientSecret: 'client-secret',
- } as WorkspaceSsoIdentityProviderEntity;
-
- afterEach(() => {
- Issuer[custom.http_options] = originalIssuerHttpOptions;
- });
-
- it('blocks issuer discovery against the metadata service', () => {
- buildSsoService();
-
- expectAgentToBlockMetadataService(
- Issuer[custom.http_options](METADATA_SERVICE_URL, {}),
- );
- });
-
- it('blocks JWKS, token and userinfo endpoints that a discovery document points at the metadata service', () => {
- const ssoService = buildSsoService();
- const issuer = new Issuer({ issuer: 'https://idp.example.com' });
-
- const client = ssoService.getOidcClient(oidcIdentityProvider, issuer);
-
- expectAgentToBlockMetadataService(
- issuer[custom.http_options](METADATA_SERVICE_URL, {}),
- );
- expectAgentToBlockMetadataService(
- client[custom.http_options](METADATA_SERVICE_URL, {}),
- );
- });
-
- it('does not restrict requests when every internal host is allowed', () => {
- buildSsoService(['*']);
-
- expect(Issuer[custom.http_options](METADATA_SERVICE_URL, {})).toEqual({
- agent: undefined,
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/target/services/__tests__/message-calendar-target-readiness.service.spec.ts b/packages/twenty-server/src/engine/core-modules/target/services/__tests__/message-calendar-target-readiness.service.spec.ts
deleted file mode 100644
index 26ebcc4e5ad..00000000000
--- a/packages/twenty-server/src/engine/core-modules/target/services/__tests__/message-calendar-target-readiness.service.spec.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { Test } from '@nestjs/testing';
-
-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
-
-import { MessageCalendarTargetReadinessService } from 'src/engine/core-modules/target/services/message-calendar-target-readiness.service';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-
-const WORKSPACE_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
-const RECORD_ID = '20202020-9b8b-4d9b-a555-9ca96a4fccb1';
-const TARGET_OBJECT_IDENTIFIERS = [
- STANDARD_OBJECTS.messageThreadTarget.universalIdentifier,
- STANDARD_OBJECTS.calendarEventTarget.universalIdentifier,
-];
-
-describe('MessageCalendarTargetReadinessService', () => {
- let service: MessageCalendarTargetReadinessService;
- const getOrRecompute = jest.fn();
-
- const setAvailableTargetObjects = (universalIdentifiers: string[]) => {
- getOrRecompute.mockResolvedValue({
- flatObjectMetadataMaps: {
- byUniversalIdentifier: Object.fromEntries(
- universalIdentifiers.map((universalIdentifier) => [
- universalIdentifier,
- { universalIdentifier },
- ]),
- ),
- },
- });
- };
-
- beforeEach(async () => {
- const module = await Test.createTestingModule({
- providers: [
- MessageCalendarTargetReadinessService,
- { provide: WorkspaceCacheService, useValue: { getOrRecompute } },
- ],
- }).compile();
-
- service = module.get(MessageCalendarTargetReadinessService);
- setAvailableTargetObjects(TARGET_OBJECT_IDENTIFIERS);
- });
-
- it.each([
- ['person', 'targetPersonId'],
- ['company', 'targetCompanyId'],
- ['opportunity', 'targetOpportunityId'],
- ])(
- 'uses target reads for %s without a feature flag',
- async (objectNameSingular, fieldName) => {
- await expect(
- service.resolveTargetFilter({
- objectNameSingular,
- recordId: RECORD_ID,
- workspaceId: WORKSPACE_ID,
- }),
- ).resolves.toEqual({ fieldName, recordId: RECORD_ID });
- },
- );
-
- it.each([
- { name: 'both objects are missing', universalIdentifiers: [] },
- {
- name: 'calendar targets are missing',
- universalIdentifiers: [TARGET_OBJECT_IDENTIFIERS[0]],
- },
- {
- name: 'message targets are missing',
- universalIdentifiers: [TARGET_OBJECT_IDENTIFIERS[1]],
- },
- ])('retains legacy reads when $name', async ({ universalIdentifiers }) => {
- setAvailableTargetObjects(universalIdentifiers);
-
- await expect(service.isReady(WORKSPACE_ID)).resolves.toBe(false);
- });
-
- it('retains the related-person fallback for custom objects', async () => {
- await expect(
- service.resolveTargetFilter({
- objectNameSingular: 'pet',
- recordId: RECORD_ID,
- workspaceId: WORKSPACE_ID,
- }),
- ).resolves.toBeUndefined();
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts
deleted file mode 100644
index 085f3f86a96..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts
+++ /dev/null
@@ -1,1058 +0,0 @@
-import { DiscoveryService } from '@nestjs/core';
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
-import {
- CacheLockException,
- CacheLockExceptionCode,
-} from 'src/engine/core-modules/cache-lock/exceptions/cache-lock.exception';
-import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
-import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
-import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';
-import { UsageLimitEntitlementProvider } from 'src/engine/core-modules/usage-limit/interfaces/usage-limit-entitlement-provider.service';
-import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
-import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
-import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
-import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
-import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
-import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
-import { type UsageLimitCounterScope } from 'src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type';
-import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';
-import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util';
-import { buildQuotaDefaultCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-default-counter-key.util';
-import { buildQuotaWarmLockKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-warm-lock-key.util';
-import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
-import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
-import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
-import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-
-const MONTH_PERIOD = {
- periodStart: new Date('2026-08-01T00:00:00.000Z'),
- periodEnd: new Date('2100-09-01T00:00:00.000Z'),
-};
-
-const WEEK_PERIOD = {
- periodStart: new Date('2026-08-24T00:00:00.000Z'),
- periodEnd: new Date('2100-08-31T00:00:00.000Z'),
-};
-
-const DAY_PERIOD = {
- periodStart: new Date('2026-08-20T00:00:00.000Z'),
- periodEnd: new Date('2100-08-21T00:00:00.000Z'),
-};
-
-const ALLOWANCE_PERIOD = {
- periodStart: new Date('2026-08-15T09:00:00.000Z'),
- periodEnd: new Date('2100-09-15T09:00:00.000Z'),
-};
-
-class TestCreditAllowanceProvider extends CreditAllowanceProvider {
- isCreditAllowanceEnabled = jest.fn().mockResolvedValue(true);
- getCreditAllowancePeriod = jest.fn().mockResolvedValue(null);
- getCreditAllowance = jest.fn().mockResolvedValue(null);
-}
-
-class TestUsageLimitEntitlementProvider extends UsageLimitEntitlementProvider {
- hasIntraWorkspaceLimitEntitlement = jest.fn();
-}
-
-const buildLimitCounterScope = (
- overrides: Partial<UsageLimitCounterScope> = {},
-): UsageLimitCounterScope => ({
- workspaceId: 'workspace-1',
- resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- spenderType: 'workspace',
- spenderId: '',
- limitKind: 'quota',
- periodUnit: 'month',
- meter: 'creditsUsedMicro',
- limitValue: 1_000,
- ...overrides,
-});
-
-const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
- id: 'limit-1',
- resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- spenderType: 'workspace',
- spenderId: '',
- limitKind: 'quota',
- periodCount: 1,
- periodUnit: 'month',
- meter: 'creditsUsedMicro',
- limitValue: 1_000,
- burstValue: null,
- isInstanceOverride: false,
- ...overrides,
-});
-
-describe('UsageLimitQuotaService', () => {
- let service: UsageLimitQuotaService;
- let creditAllowanceProvider: TestCreditAllowanceProvider;
- let entitlementProvider: TestUsageLimitEntitlementProvider;
-
- const cacheStorage = {
- mget: jest.fn().mockResolvedValue([]),
- mset: jest.fn().mockResolvedValue(undefined),
- runScript: jest.fn().mockResolvedValue([]),
- mdel: jest.fn().mockResolvedValue(undefined),
- };
-
- const workspaceCacheService = {
- getOrRecompute: jest
- .fn()
- .mockResolvedValue({ usageLimits: { byResourceType: {} } }),
- };
-
- const cacheLockService = {
- withLock: jest.fn((fn: () => Promise<unknown>) => fn()),
- };
-
- const usageAnalyticsService = {
- getConsumptionRowsForAllScopes: jest.fn().mockResolvedValue([]),
- getCreditsUsedMicroForBillingPeriod: jest.fn().mockResolvedValue(0),
- };
-
- const usagePeriodService = {
- findCurrentPeriod: jest.fn(),
- findCurrentPeriodsByUnit: jest.fn(),
- };
-
- const metricsService = {
- incrementCounterBy: jest.fn(),
- };
-
- const twentyConfigService = {
- get: jest.fn(),
- };
-
- let periodByUnit: Partial<Record<PeriodUnit, UsagePeriod>>;
-
- const setLimits = (
- limits: FlatUsageLimit[],
- resourceType: UsageResourceType = UsageResourceType.AI,
- ) => {
- workspaceCacheService.getOrRecompute.mockResolvedValue({
- usageLimits: {
- byResourceType: { [resourceType]: limits },
- },
- });
- };
-
- const setAllowance = (allowanceMicro: number | null) => {
- periodByUnit.allowancePeriod = ALLOWANCE_PERIOD;
- creditAllowanceProvider.getCreditAllowancePeriod.mockResolvedValue(
- ALLOWANCE_PERIOD,
- );
- creditAllowanceProvider.getCreditAllowance.mockResolvedValue(
- allowanceMicro === null
- ? null
- : {
- ...ALLOWANCE_PERIOD,
- allowanceMicro,
- validUntil: ALLOWANCE_PERIOD.periodEnd,
- },
- );
- };
-
- const findExhaustedScope = () =>
- service.findExhaustedScope({
- workspaceId: 'workspace-1',
- resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- spenders: { userWorkspaceId: 'user-1' },
- });
-
- const consumeQuota = (creditsUsedMicro: number, quantity = 0) =>
- service.consumeQuota({
- workspaceId: 'workspace-1',
- resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- spenders: { userWorkspaceId: 'user-1' },
- cost: { creditsUsedMicro, quantity },
- });
-
- beforeEach(async () => {
- jest.clearAllMocks();
- creditAllowanceProvider = new TestCreditAllowanceProvider();
- entitlementProvider = new TestUsageLimitEntitlementProvider();
- entitlementProvider.hasIntraWorkspaceLimitEntitlement.mockResolvedValue(
- true,
- );
- cacheStorage.mget.mockResolvedValue([]);
- cacheStorage.runScript.mockResolvedValue([]);
- twentyConfigService.get.mockReturnValue(1_000);
- usageAnalyticsService.getConsumptionRowsForAllScopes.mockResolvedValue([]);
- usageAnalyticsService.getCreditsUsedMicroForBillingPeriod.mockResolvedValue(
- 0,
- );
- periodByUnit = { month: MONTH_PERIOD, week: WEEK_PERIOD };
- usagePeriodService.findCurrentPeriod.mockImplementation(
- async ({ periodUnit }: { periodUnit: PeriodUnit }) =>
- periodByUnit[periodUnit] ?? null,
- );
- usagePeriodService.findCurrentPeriodsByUnit.mockImplementation(
- async () => periodByUnit,
- );
- workspaceCacheService.getOrRecompute.mockResolvedValue({
- usageLimits: { byResourceType: {} },
- });
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- UsageLimitQuotaService,
- UsageLimitEntitlementService,
- {
- provide: CacheStorageNamespace.EngineUsageLimit,
- useValue: cacheStorage,
- },
- { provide: WorkspaceCacheService, useValue: workspaceCacheService },
- { provide: CacheLockService, useValue: cacheLockService },
- { provide: UsageAnalyticsService, useValue: usageAnalyticsService },
- { provide: UsagePeriodService, useValue: usagePeriodService },
- { provide: MetricsService, useValue: metricsService },
- { provide: TwentyConfigService, useValue: twentyConfigService },
- {
- provide: DiscoveryService,
- useValue: {
- getProviders: () => [
- { instance: creditAllowanceProvider },
- { instance: entitlementProvider },
- ],
- },
- },
- ],
- }).compile();
-
- service = module.get<UsageLimitQuotaService>(UsageLimitQuotaService);
- service.onModuleInit();
- module.get(UsageLimitEntitlementService).onModuleInit();
- });
-
- it('admits on a warm counter with budget left', async () => {
- setLimits([buildLimit({})]);
- cacheStorage.mget.mockResolvedValue([250]);
-
- await expect(findExhaustedScope()).resolves.toBeNull();
- expect(
- usageAnalyticsService.getConsumptionRowsForAllScopes,
- ).not.toHaveBeenCalled();
- });
-
- it('denies on an exhausted warm counter', async () => {
- setLimits([buildLimit({})]);
- cacheStorage.mget.mockResolvedValue([0]);
-
- await expect(findExhaustedScope()).resolves.toMatchObject({
- spenderType: 'workspace',
- limitKind: 'quota',
- exhaustedKind: 'limit',
- });
- });
-
- it('warms limit counters over UTC day buckets', async () => {
- setLimits([buildLimit({})]);
- cacheStorage.mget.mockResolvedValue([undefined]);
-
- await expect(findExhaustedScope()).resolves.toBeNull();
- expect(
- usageAnalyticsService.getConsumptionRowsForAllScopes,
- ).toHaveBeenCalledWith(
- expect.objectContaining({
- periodAnchor: 'calendar',
- periodStart: MONTH_PERIOD.periodStart,
- }),
- );
- });
-
- it('runs one warm query per distinct period', async () => {
- setLimits([
- buildLimit({ id: 'monthly' }),
- buildLimit({ id: 'weekly', periodUnit: 'week' }),
- ]);
- cacheStorage.mget.mockResolvedValue([undefined, undefined]);
-
- await findExhaustedScope();
-
- expect(
- usageAnalyticsService.getConsumptionRowsForAllScopes,
- ).toHaveBeenCalledTimes(2);
- });
-
- it('warms a cold allowance counter from the live allowance minus the stamped consumption', async () => {
- setAllowance(100);
- cacheStorage.mget.mockResolvedValue([undefined]);
- usageAnalyticsService.getCreditsUsedMicroForBillingPeriod.mockResolvedValue(
- 150,
- );
-
- await expect(findExhaustedScope()).resolves.not.toBeNull();
- expect(
- usageAnalyticsService.getCreditsUsedMicroForBillingPeriod,
- ).toHaveBeenCalledWith({
- workspaceId: 'workspace-1',
- periodStart: ALLOWANCE_PERIOD.periodStart,
- });
- expect(cacheStorage.mset).toHaveBeenCalledWith([
- expect.objectContaining({ value: -50 }),
- ]);
- });
-
- it('expires a warm allowance counter with the earliest lapsing grant', async () => {
- const validUntil = new Date(Date.now() + 60_000);
-
- setAllowance(100);
- creditAllowanceProvider.getCreditAllowance.mockResolvedValue({
- ...ALLOWANCE_PERIOD,
- allowanceMicro: 100,
- validUntil,
- });
- cacheStorage.mget.mockResolvedValue([undefined]);
-
- await findExhaustedScope();
-
- const [[entries]] = cacheStorage.mset.mock.calls;
-
- expect(entries[0].ttl).toBeLessThanOrEqual(60_000);
- expect(entries[0].ttl).toBeGreaterThan(0);
- });
-
- it('scopes a spent allowance counter over the live allowance', async () => {
- setAllowance(2_000_000);
- cacheStorage.mget.mockResolvedValue([0]);
-
- await expect(findExhaustedScope()).resolves.toMatchObject({
- exhaustedKind: 'allowance',
- limitValue: 2_000_000,
- });
- });
-
- it('reports the exhausted allowance over an exhausted limit', async () => {
- setLimits([buildLimit({})]);
- setAllowance(2_000_000);
- cacheStorage.mget.mockResolvedValue([0, 0]);
-
- await expect(findExhaustedScope()).resolves.toMatchObject({
- exhaustedKind: 'allowance',
- });
- });
-
- it('builds no allowance counter when the provider reports it disabled', async () => {
- setLimits([buildLimit({})]);
- setAllowance(2_000_000);
- creditAllowanceProvider.isCreditAllowanceEnabled.mockResolvedValue(false);
- cacheStorage.mget.mockResolvedValue([0]);
-
- await expect(findExhaustedScope()).resolves.toMatchObject({
- exhaustedKind: 'limit',
- });
- expect(cacheStorage.mget).toHaveBeenCalledWith([
- expect.not.stringContaining(':allowance:'),
- ]);
- expect(
- creditAllowanceProvider.getCreditAllowancePeriod,
- ).not.toHaveBeenCalled();
- });
-
- it('skips warming an allowance whose period rolled over since the read', async () => {
- periodByUnit.allowancePeriod = ALLOWANCE_PERIOD;
- creditAllowanceProvider.getCreditAllowance.mockResolvedValue({
- allowanceMicro: 100,
- periodStart: new Date('2026-09-15T09:00:00.000Z'),
- periodEnd: new Date('2100-10-15T09:00:00.000Z'),
- validUntil: new Date('2100-10-15T09:00:00.000Z'),
- });
- cacheStorage.mget.mockResolvedValue([undefined]);
-
- await expect(findExhaustedScope()).resolves.toBeNull();
- expect(cacheStorage.mset).toHaveBeenCalledWith([]);
- });
-
- describe('allowance-period limits', () => {
- const allowancePeriodLimit = buildLimit({
- id: 'allowance-period',
- periodUnit: 'allowancePeriod',
- limitValue: 800,
- });
-
- it('warms the counter from the consumption of the allowance period', async () => {
- setLimits([allowancePeriodLimit]);
- setAllowance(2_000);
- creditAllowanceProvider.isCreditAllowanceEnabled.mockResolvedValue(false);
- cacheStorage.mget.mockResolvedValue([undefined]);
- usageAnalyticsService.getConsumptionRowsForAllScopes.mockResolvedValue([
- {
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- userWorkspaceId: 'user-1',
- apiKeyId: '',
- applicationId: '',
- agentId: '',
- workflowId: '',
- logicFunctionId: '',
- creditsUsedMicro: '150',
- quantity: '0',
- },
- ]);
-
- await expect(findExhaustedScope()).resolves.toBeNull();
-
- expect(
- usageAnalyticsService.getConsumptionRowsForAllScopes,
- ).toHaveBeenCalledWith(
- expect.objectContaining({
- periodAnchor: 'billing',
- periodStart: ALLOWANCE_PERIOD.periodStart,
- periodEnd: ALLOWANCE_PERIOD.periodEnd,
- }),
- );
- expect(cacheStorage.mset).toHaveBeenCalledWith([
- expect.objectContaining({ value: 650 }),
- ]);
- });
- });
-
- it('admits when the counters cannot be read', async () => {
- setLimits([buildLimit({})]);
- cacheStorage.mget.mockRejectedValue(new Error('Socket closed'));
-
- await expect(findExhaustedScope()).resolves.toBeNull();
- expect(metricsService.incrementCounterBy).toHaveBeenCalledTimes(1);
- expect(metricsService.incrementCounterBy).toHaveBeenCalledWith({
- key: MetricsKeys.UsageLimitQuotaAdmittedOnFailure,
- amount: 1,
- attributes: { operation: 'assert', resourceType: UsageResourceType.AI },
- });
- });
-
- it('counts the credits admitted when a consume fails', async () => {
- setLimits([buildLimit({})]);
- cacheStorage.mget.mockRejectedValue(new Error('Socket closed'));
-
- await expect(consumeQuota(50, 7)).resolves.toEqual({ exhausted: [] });
- expect(metricsService.incrementCounterBy).toHaveBeenCalledWith({
- key: MetricsKeys.UsageLimitQuotaAdmittedOnFailure,
- amount: 1,
- attributes: { operation: 'consume', resourceType: UsageResourceType.AI },
- });
- expect(metricsService.incrementCounterBy).toHaveBeenCalledWith({
- key: MetricsKeys.UsageLimitQuotaAdmittedOnFailureCreditsMicro,
- amount: 50,
- attributes: { operation: 'consume', resourceType: UsageResourceType.AI },
- });
- });
-
- it('does not count an admit on a successful consume', async () => {
- setLimits([buildLimit({})]);
- cacheStorage.runScript.mockResolvedValue([1, 500]);
-
- await expect(consumeQuota(50)).resolves.toEqual({ exhausted: [] });
- expect(metricsService.incrementCounterBy).not.toHaveBeenCalled();
- });
-
- it('admits when the warm query fails instead of granting a fresh budget', async () => {
- setLimits([buildLimit({})]);
- cacheStorage.mget.mockResolvedValue([undefined]);
- usageAnalyticsService.getConsumptionRowsForAllScopes.mockRejectedValue(
- new Error('clickhouse unreachable'),
- );
-
- await expect(findExhaustedScope()).resolves.toBeNull();
- expect(cacheStorage.mset).not.toHaveBeenCalled();
- });
-
- it('debits each counter in its own meter on consume', async () => {
- setLimits([
- buildLimit({ id: 'credits' }),
- buildLimit({ id: 'tokens', meter: 'quantity' }),
- ]);
- cacheStorage.runScript.mockResolvedValue([1, 500, 1, 900]);
-
- const { exhausted } = await consumeQuota(50, 7);
-
- expect(cacheStorage.runScript).toHaveBeenCalledWith(
- expect.objectContaining({ args: ['[50,7]'] }),
- );
- expect(exhausted).toEqual([]);
- });
-
- it('consumes an invalid cost as zero instead of crediting the counter', async () => {
- setLimits([buildLimit({})]);
- cacheStorage.runScript.mockResolvedValue([1, 950]);
-
- await consumeQuota(-50, Number.NaN);
-
- expect(cacheStorage.runScript).toHaveBeenCalledWith(
- expect.objectContaining({ args: ['[0]'] }),
- );
- });
-
- it('debits the allowance counter with the credit cost on consume', async () => {
- setLimits([buildLimit({ meter: 'quantity' })]);
- setAllowance(2_000_000);
- cacheStorage.runScript.mockResolvedValue([1, 500, 1, -5]);
-
- const { exhausted } = await consumeQuota(50, 7);
-
- expect(cacheStorage.runScript).toHaveBeenCalledWith(
- expect.objectContaining({ args: ['[7,50]'] }),
- );
- expect(exhausted).toMatchObject([{ exhaustedKind: 'allowance' }]);
- });
-
- it('reports every exhausted counter on consume', async () => {
- setLimits([buildLimit({})]);
- setAllowance(2_000_000);
- cacheStorage.runScript.mockResolvedValue([1, 0, 1, -5]);
-
- const { exhausted } = await consumeQuota(50);
-
- expect(exhausted).toMatchObject([
- { exhaustedKind: 'limit' },
- { exhaustedKind: 'allowance' },
- ]);
- });
-
- it('warms a cold counter before consuming it', async () => {
- setLimits([buildLimit({})]);
- cacheStorage.mget.mockResolvedValue([undefined]);
- cacheStorage.runScript.mockResolvedValue([1, 950]);
-
- const { exhausted } = await consumeQuota(50);
-
- expect(cacheStorage.mset).toHaveBeenCalledWith([
- expect.objectContaining({ value: 1_000 }),
- ]);
- expect(cacheStorage.runScript).toHaveBeenCalledWith(
- expect.objectContaining({ args: ['[50]'] }),
- );
- expect(exhausted).toEqual([]);
- });
-
- describe('intra-workspace limit entitlement', () => {
- it('does not check entitlement when only workspace-scope quota rows exist', async () => {
- setLimits([buildLimit({})]);
- cacheStorage.mget.mockResolvedValue([250]);
-
- await findExhaustedScope();
-
- expect(
- entitlementProvider.hasIntraWorkspaceLimitEntitlement,
- ).not.toHaveBeenCalled();
- });
-
- it('enforces only workspace-scope quota rows when not entitled', async () => {
- entitlementProvider.hasIntraWorkspaceLimitEntitlement.mockResolvedValue(
- false,
- );
- setLimits([
- buildLimit({ id: 'ws' }),
- buildLimit({ id: 'uw', spenderType: 'userWorkspace' }),
- ]);
- cacheStorage.mget.mockResolvedValue([250]);
-
- await findExhaustedScope();
-
- expect(cacheStorage.mget.mock.calls[0][0]).toHaveLength(1);
- });
-
- it('enforces intra-workspace quota rows when entitled', async () => {
- setLimits([
- buildLimit({ id: 'ws' }),
- buildLimit({ id: 'uw', spenderType: 'userWorkspace' }),
- ]);
- cacheStorage.mget.mockResolvedValue([250, 250]);
-
- await findExhaustedScope();
-
- expect(cacheStorage.mget.mock.calls[0][0]).toHaveLength(2);
- });
- });
-
- describe('dropAllowanceCounter', () => {
- it('drops the counter keyed by the current period', async () => {
- setAllowance(2_000_000);
-
- await service.dropAllowanceCounter('workspace-1');
-
- expect(cacheStorage.mdel).toHaveBeenCalledWith([
- buildAllowanceCounterKey({
- workspaceId: 'workspace-1',
- periodStart: ALLOWANCE_PERIOD.periodStart,
- }),
- ]);
- });
-
- it('does nothing when no allowance exists', async () => {
- await service.dropAllowanceCounter('workspace-1');
-
- expect(cacheStorage.mdel).not.toHaveBeenCalled();
- });
- });
-
- describe('dropIntraWorkspaceLimitCounters', () => {
- it('drops every intra-workspace quota counter under the warm lock', async () => {
- setLimits([
- buildLimit({ id: 'workspace-month' }),
- buildLimit({
- id: 'member-month',
- spenderType: 'userWorkspace',
- spenderId: 'user-1',
- }),
- buildLimit({
- id: 'agent-week',
- spenderType: 'agent',
- periodUnit: 'week',
- }),
- buildLimit({
- id: 'member-speed',
- spenderType: 'userWorkspace',
- limitKind: 'speed',
- periodUnit: 'second',
- meter: 'quantity',
- }),
- ]);
-
- await service.dropIntraWorkspaceLimitCounters('workspace-1');
-
- expect(cacheLockService.withLock).toHaveBeenCalledWith(
- expect.any(Function),
- buildQuotaWarmLockKey('workspace-1'),
- expect.anything(),
- );
- expect(cacheStorage.mdel).toHaveBeenCalledWith([
- buildQuotaCounterKey({
- workspaceId: 'workspace-1',
- resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- spenderType: 'userWorkspace',
- spenderId: 'user-1',
- meter: 'creditsUsedMicro',
- periodUnit: 'month',
- periodStart: MONTH_PERIOD.periodStart,
- limitValue: 1_000,
- }),
- buildQuotaCounterKey({
- workspaceId: 'workspace-1',
- resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- spenderType: 'agent',
- spenderId: '',
- meter: 'creditsUsedMicro',
- periodUnit: 'week',
- periodStart: WEEK_PERIOD.periodStart,
- limitValue: 1_000,
- }),
- ]);
- });
-
- it('does nothing when the workspace only has workspace-scoped limits', async () => {
- setLimits([buildLimit({})]);
-
- await service.dropIntraWorkspaceLimitCounters('workspace-1');
-
- expect(cacheStorage.mdel).not.toHaveBeenCalled();
- });
- });
-
- describe('dropLimitCounter', () => {
- it('drops the counter keyed by the current period under the warm lock', async () => {
- await service.dropLimitCounter(buildLimitCounterScope());
-
- expect(cacheLockService.withLock).toHaveBeenCalledWith(
- expect.any(Function),
- buildQuotaWarmLockKey('workspace-1'),
- expect.anything(),
- );
- expect(cacheStorage.mdel).toHaveBeenCalledWith([
- buildQuotaCounterKey({
- workspaceId: 'workspace-1',
- resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- spenderType: 'workspace',
- spenderId: '',
- meter: 'creditsUsedMicro',
- periodUnit: 'month',
- periodStart: MONTH_PERIOD.periodStart,
- limitValue: 1_000,
- }),
- ]);
- });
-
- it('also drops the default counter the limit overrides', async () => {
- periodByUnit.day = DAY_PERIOD;
-
- await service.dropLimitCounter(
- buildLimitCounterScope({
- resourceType: UsageResourceType.EMAIL,
- operationType: UsageOperationType.EMAIL_SEND,
- periodUnit: 'day',
- meter: 'quantity',
- }),
- );
-
- expect(cacheStorage.mdel).toHaveBeenCalledWith([
- buildQuotaCounterKey({
- workspaceId: 'workspace-1',
- resourceType: UsageResourceType.EMAIL,
- operationType: UsageOperationType.EMAIL_SEND,
- spenderType: 'workspace',
- spenderId: '',
- meter: 'quantity',
- periodUnit: 'day',
- periodStart: DAY_PERIOD.periodStart,
- limitValue: 1_000,
- }),
- buildQuotaDefaultCounterKey({
- workspaceId: 'workspace-1',
- resourceType: UsageResourceType.EMAIL,
- operationType: UsageOperationType.EMAIL_SEND,
- spenderType: 'workspace',
- meter: 'quantity',
- periodUnit: 'day',
- periodStart: DAY_PERIOD.periodStart,
- limitValue: 1_000,
- }),
- ]);
- });
-
- it('skips the drop when the period cannot be resolved', async () => {
- await service.dropLimitCounter(
- buildLimitCounterScope({ periodUnit: 'allowancePeriod' }),
- );
-
- expect(cacheStorage.mdel).not.toHaveBeenCalled();
- });
-
- it('ignores a speed limit', async () => {
- await service.dropLimitCounter(
- buildLimitCounterScope({ limitKind: 'speed', periodUnit: 'second' }),
- );
-
- expect(cacheStorage.mdel).not.toHaveBeenCalled();
- });
-
- it('dels without the lock when acquiring it times out', async () => {
- cacheLockService.withLock.mockRejectedValueOnce(
- new CacheLockException(
- 'timed out',
- CacheLockExceptionCode.LOCK_ACQUISITION_TIMEOUT,
- ),
- );
-
- await service.dropLimitCounter(buildLimitCounterScope());
-
- expect(cacheStorage.mdel).toHaveBeenCalledTimes(1);
- });
- });
-
- describe('getAllowanceUsage', () => {
- it('reports consumption and reset from the allowance counter', async () => {
- setAllowance(2000);
- cacheStorage.mget.mockResolvedValue([1500]);
- await expect(service.getAllowanceUsage('workspace-1')).resolves.toEqual({
- limitValue: 2000,
- consumedValue: 500,
- periodEnd: ALLOWANCE_PERIOD.periodEnd,
- });
- });
-
- it('preserves unavailable consumption instead of reporting zero usage', async () => {
- setAllowance(2000);
- cacheStorage.mget.mockRejectedValue(new Error('Socket closed'));
- await expect(service.getAllowanceUsage('workspace-1')).resolves.toEqual({
- limitValue: 2000,
- consumedValue: null,
- periodEnd: ALLOWANCE_PERIOD.periodEnd,
- });
- });
-
- it('reports unknown consumption when the allowance period changes', async () => {
- setAllowance(2000);
- creditAllowanceProvider.getCreditAllowance.mockResolvedValue({
- ...ALLOWANCE_PERIOD,
- periodStart: new Date('2026-09-15T09:00:00.000Z'),
- allowanceMicro: 2000,
- validUntil: ALLOWANCE_PERIOD.periodEnd,
- });
- await expect(service.getAllowanceUsage('workspace-1')).resolves.toEqual({
- limitValue: 2000,
- consumedValue: null,
- periodEnd: ALLOWANCE_PERIOD.periodEnd,
- });
- expect(cacheStorage.mget).not.toHaveBeenCalled();
- });
-
- it('returns no limit when the allowance is disabled', async () => {
- creditAllowanceProvider.isCreditAllowanceEnabled.mockResolvedValue(false);
- await expect(
- service.getAllowanceUsage('workspace-1'),
- ).resolves.toBeNull();
- });
- });
-
- describe('getAllowanceRemainingMicro', () => {
- it('reads the warm allowance counter', async () => {
- setAllowance(2_000_000);
- cacheStorage.mget.mockResolvedValue([1_500]);
-
- await expect(
- service.getAllowanceRemainingMicro('workspace-1'),
- ).resolves.toBe(1_500);
- });
-
- it('answers null when no allowance exists', async () => {
- await expect(
- service.getAllowanceRemainingMicro('workspace-1'),
- ).resolves.toBeNull();
- expect(cacheStorage.mget).not.toHaveBeenCalled();
- });
-
- it('does not count a failed read as an admit', async () => {
- setAllowance(2_000_000);
- cacheStorage.mget.mockRejectedValue(new Error('Socket closed'));
-
- await expect(
- service.getAllowanceRemainingMicro('workspace-1'),
- ).resolves.toBeNull();
- expect(metricsService.incrementCounterBy).not.toHaveBeenCalled();
- });
- });
-
- describe('readLimitConsumptions', () => {
- const readLimitConsumptions = (limits: FlatUsageLimit[]) =>
- service.readLimitConsumptions({ workspaceId: 'workspace-1', limits });
-
- const buildConsumptionRow = (
- overrides: Partial<UsageConsumptionRow> = {},
- ): UsageConsumptionRow => ({
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- userWorkspaceId: '',
- apiKeyId: '',
- applicationId: '',
- agentId: '',
- workflowId: '',
- logicFunctionId: '',
- creditsUsedMicro: '0',
- quantity: '0',
- ...overrides,
- });
-
- it('reads the consumption of each warm counter', async () => {
- cacheStorage.mget.mockResolvedValue([700]);
-
- await expect(
- readLimitConsumptions([buildLimit({ limitValue: 1_000 })]),
- ).resolves.toEqual(
- new Map([
- [
- 'limit-1',
- {
- consumedValue: 300,
- remainingValue: 700,
- periodStart: MONTH_PERIOD.periodStart,
- periodEnd: MONTH_PERIOD.periodEnd,
- },
- ],
- ]),
- );
- });
-
- it('answers a null consumption when the counters cannot be read', async () => {
- cacheStorage.mget.mockRejectedValue(new Error('Socket closed'));
-
- await expect(
- readLimitConsumptions([buildLimit({ limitValue: 1_000 })]),
- ).resolves.toEqual(
- new Map([
- [
- 'limit-1',
- {
- consumedValue: null,
- remainingValue: null,
- periodStart: MONTH_PERIOD.periodStart,
- periodEnd: MONTH_PERIOD.periodEnd,
- },
- ],
- ]),
- );
- expect(metricsService.incrementCounterBy).not.toHaveBeenCalled();
- });
-
- it('reads a cold counter from the consumption rows without warming it', async () => {
- cacheStorage.mget.mockResolvedValue([undefined]);
- usageAnalyticsService.getConsumptionRowsForAllScopes.mockResolvedValue([
- buildConsumptionRow({ creditsUsedMicro: '150' }),
- buildConsumptionRow({ creditsUsedMicro: '90' }),
- ]);
-
- await expect(
- readLimitConsumptions([buildLimit({ limitValue: 1_000 })]),
- ).resolves.toEqual(
- new Map([
- [
- 'limit-1',
- {
- consumedValue: 240,
- remainingValue: 760,
- periodStart: MONTH_PERIOD.periodStart,
- periodEnd: MONTH_PERIOD.periodEnd,
- },
- ],
- ]),
- );
- expect(cacheStorage.mset).not.toHaveBeenCalled();
- expect(cacheLockService.withLock).not.toHaveBeenCalled();
- });
-
- it('reads the warm counters from the cache and only the cold ones from ClickHouse', async () => {
- cacheStorage.mget.mockResolvedValue([700, undefined]);
- usageAnalyticsService.getConsumptionRowsForAllScopes.mockResolvedValue([
- buildConsumptionRow({ creditsUsedMicro: '120' }),
- ]);
-
- await expect(
- readLimitConsumptions([
- buildLimit({ id: 'monthly', limitValue: 1_000 }),
- buildLimit({ id: 'weekly', periodUnit: 'week', limitValue: 500 }),
- ]),
- ).resolves.toEqual(
- new Map([
- [
- 'monthly',
- {
- consumedValue: 300,
- remainingValue: 700,
- periodStart: MONTH_PERIOD.periodStart,
- periodEnd: MONTH_PERIOD.periodEnd,
- },
- ],
- [
- 'weekly',
- {
- consumedValue: 120,
- remainingValue: 380,
- periodStart: WEEK_PERIOD.periodStart,
- periodEnd: WEEK_PERIOD.periodEnd,
- },
- ],
- ]),
- );
- expect(
- usageAnalyticsService.getConsumptionRowsForAllScopes,
- ).toHaveBeenCalledTimes(1);
- expect(
- usageAnalyticsService.getConsumptionRowsForAllScopes,
- ).toHaveBeenCalledWith(
- expect.objectContaining({ periodStart: WEEK_PERIOD.periodStart }),
- );
- });
-
- it('answers a null consumption when ClickHouse cannot be read', async () => {
- cacheStorage.mget.mockResolvedValue([undefined]);
- usageAnalyticsService.getConsumptionRowsForAllScopes.mockRejectedValue(
- new Error('ClickHouse unreachable'),
- );
-
- await expect(
- readLimitConsumptions([buildLimit({ limitValue: 1_000 })]),
- ).resolves.toEqual(
- new Map([
- [
- 'limit-1',
- {
- consumedValue: null,
- remainingValue: null,
- periodStart: MONTH_PERIOD.periodStart,
- periodEnd: MONTH_PERIOD.periodEnd,
- },
- ],
- ]),
- );
- });
- });
-
- describe('default limits', () => {
- const findEmailExhaustedScope = () =>
- service.findExhaustedScope({
- workspaceId: 'workspace-1',
- resourceType: UsageResourceType.EMAIL,
- operationType: UsageOperationType.EMAIL_SEND,
- spenders: {},
- });
-
- const mockRemaining = (remaining: number | undefined) =>
- cacheStorage.mget.mockResolvedValue([remaining]);
-
- const buildEmailLimit = (overrides: Partial<FlatUsageLimit>) =>
- buildLimit({
- resourceType: UsageResourceType.EMAIL,
- operationType: UsageOperationType.EMAIL_SEND,
- periodUnit: 'day',
- meter: 'quantity',
- ...overrides,
- });
-
- beforeEach(() => {
- periodByUnit.day = DAY_PERIOD;
- });
-
- it('caps a workspace that stores no limit of its own', async () => {
- mockRemaining(0);
-
- await expect(findEmailExhaustedScope()).resolves.toMatchObject({
- exhaustedKind: 'limit',
- isDefault: true,
- limitValue: 1_000,
- periodUnit: 'day',
- spenderType: 'workspace',
- });
- });
-
- it('warms the default counter against the configured limit value', async () => {
- mockRemaining(undefined);
- usageAnalyticsService.getConsumptionRowsForAllScopes.mockResolvedValue([
- {
- operationType: UsageOperationType.EMAIL_SEND,
- userWorkspaceId: '',
- apiKeyId: '',
- applicationId: '',
- agentId: '',
- logicFunctionId: '',
- creditsUsedMicro: 0,
- quantity: 400,
- },
- ]);
-
- await expect(findEmailExhaustedScope()).resolves.toBeNull();
- expect(cacheStorage.mset).toHaveBeenCalledWith([
- expect.objectContaining({ value: 600 }),
- ]);
- });
-
- it('declares no default where ClickHouse is not configured', async () => {
- twentyConfigService.get.mockImplementation((key: string) =>
- key === 'CLICKHOUSE_URL' ? undefined : 1_000,
- );
- mockRemaining(undefined);
-
- await expect(findEmailExhaustedScope()).resolves.toBeNull();
- expect(
- usageAnalyticsService.getConsumptionRowsForAllScopes,
- ).not.toHaveBeenCalled();
- });
-
- it('gives way to a workspace limit that overrides it', async () => {
- setLimits([buildEmailLimit({ limitValue: 50 })], UsageResourceType.EMAIL);
- cacheStorage.mget.mockResolvedValue([0]);
-
- await expect(findEmailExhaustedScope()).resolves.toMatchObject({
- isDefault: false,
- limitValue: 50,
- });
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-speed.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-speed.service.spec.ts
deleted file mode 100644
index 74f2faaac07..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-speed.service.spec.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-import { DiscoveryService } from '@nestjs/core';
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import {
- CacheStorageException,
- CacheStorageExceptionCode,
-} from 'src/engine/core-modules/cache-storage/exceptions/cache-storage.exception';
-import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { UsageLimitEntitlementProvider } from 'src/engine/core-modules/usage-limit/interfaces/usage-limit-entitlement-provider.service';
-import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
-import { UsageLimitSpeedService } from 'src/engine/core-modules/usage-limit/services/usage-limit-speed.service';
-import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
-import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
-import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
-import {
- WorkspaceCacheException,
- WorkspaceCacheExceptionCode,
-} from 'src/engine/workspace-cache/exceptions/workspace-cache.exception';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-
-const apiKeyContext = {
- type: 'apiKey',
- workspace: { id: 'workspace-1' },
- apiKey: { id: 'key-1' },
-} as WorkspaceAuthContext;
-
-class TestUsageLimitEntitlementProvider extends UsageLimitEntitlementProvider {
- hasIntraWorkspaceLimitEntitlement = jest.fn();
-}
-
-const API_KEY_OVERRIDE_BUCKET_KEY =
- '{workspace-1}:speed:API:API_REQUEST:apiKey:key-1:60';
-
-const buildApiKeySpeedLimit = (): FlatUsageLimit => ({
- id: 'speed-1',
- resourceType: UsageResourceType.API,
- operationType: UsageOperationType.API_REQUEST,
- spenderType: 'apiKey',
- spenderId: 'key-1',
- limitKind: 'speed',
- periodCount: 60,
- periodUnit: 'second',
- meter: 'quantity',
- limitValue: 100,
- burstValue: null,
- isInstanceOverride: false,
-});
-
-describe('UsageLimitSpeedService', () => {
- let service: UsageLimitSpeedService;
- let entitlementProvider: TestUsageLimitEntitlementProvider;
-
- const cacheStorage = {
- runScript: jest.fn().mockResolvedValue([1, 0, 0]),
- };
-
- const workspaceCacheService = {
- getOrRecompute: jest
- .fn()
- .mockResolvedValue({ usageLimits: { byResourceType: {} } }),
- };
-
- const twentyConfigService = {
- get: jest.fn((key: string) => (key.endsWith('_IN_MS') ? 60_000 : 100)),
- };
-
- const consume = () =>
- service.consumeOrThrow({
- resourceType: UsageResourceType.API,
- authContext: apiKeyContext,
- operationType: UsageOperationType.API_REQUEST,
- });
-
- const consumeCost = (cost: number) =>
- service.tryConsume({
- resourceType: UsageResourceType.API,
- authContext: apiKeyContext,
- operationType: UsageOperationType.API_REQUEST,
- cost,
- });
-
- const consumeUpTo = (maxCost: number) =>
- service.tryConsumeUpTo({
- resourceType: UsageResourceType.API,
- authContext: apiKeyContext,
- operationType: UsageOperationType.API_REQUEST,
- maxCost,
- });
-
- beforeEach(async () => {
- jest.clearAllMocks();
- entitlementProvider = new TestUsageLimitEntitlementProvider();
- entitlementProvider.hasIntraWorkspaceLimitEntitlement.mockResolvedValue(
- true,
- );
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- UsageLimitSpeedService,
- UsageLimitEntitlementService,
- {
- provide: CacheStorageNamespace.EngineUsageLimit,
- useValue: cacheStorage,
- },
- { provide: WorkspaceCacheService, useValue: workspaceCacheService },
- { provide: TwentyConfigService, useValue: twentyConfigService },
- {
- provide: DiscoveryService,
- useValue: {
- getProviders: () => [{ instance: entitlementProvider }],
- },
- },
- ],
- }).compile();
-
- service = module.get<UsageLimitSpeedService>(UsageLimitSpeedService);
- module.get(UsageLimitEntitlementService).onModuleInit();
- });
-
- it('admits the request when the limits cannot be read from storage', async () => {
- workspaceCacheService.getOrRecompute.mockRejectedValueOnce(
- new Error('Socket closed unexpectedly'),
- );
-
- await expect(consume()).resolves.toBeUndefined();
- expect(cacheStorage.runScript).not.toHaveBeenCalled();
- });
-
- it('surfaces a misuse of the cache api instead of degrading', async () => {
- workspaceCacheService.getOrRecompute.mockRejectedValueOnce(
- new WorkspaceCacheException(
- 'Invalid parameters',
- WorkspaceCacheExceptionCode.INVALID_PARAMETERS,
- ),
- );
-
- await expect(consume()).rejects.toThrow(WorkspaceCacheException);
- });
-
- it('admits the request when the counters cannot be consumed', async () => {
- cacheStorage.runScript.mockRejectedValueOnce(
- new CacheStorageException(
- 'Script execution failed',
- CacheStorageExceptionCode.SCRIPT_EXECUTION_FAILED,
- ),
- );
-
- await expect(consume()).resolves.toBeUndefined();
- });
-
- it('denies the request when a bucket is exhausted', async () => {
- cacheStorage.runScript.mockResolvedValueOnce([0, 1, 1500]);
-
- await expect(consume()).rejects.toThrow(/Rate limit exceeded/);
- });
-
- it('admits a multi-cost request when the buckets cover all of it', async () => {
- cacheStorage.runScript.mockResolvedValueOnce([5, 0, 0]);
-
- await expect(consumeCost(5)).resolves.toEqual({
- admitted: true,
- admittedCount: 5,
- });
- });
-
- it('admits part of a batch when the buckets cannot cover all of it', async () => {
- cacheStorage.runScript.mockResolvedValueOnce([2, 1, 1500]);
-
- await expect(consumeUpTo(5)).resolves.toMatchObject({
- admitted: false,
- admittedCount: 2,
- retryAfterMs: 1500,
- });
- });
-
- it('enforces a stored apiKey speed override only when the workspace is entitled', async () => {
- workspaceCacheService.getOrRecompute.mockResolvedValue({
- usageLimits: {
- byResourceType: { [UsageResourceType.API]: [buildApiKeySpeedLimit()] },
- },
- });
-
- await consume();
- const entitledKeys: string[] = cacheStorage.runScript.mock.calls[0][0].keys;
-
- entitlementProvider.hasIntraWorkspaceLimitEntitlement.mockResolvedValue(
- false,
- );
- await consume();
- const notEntitledKeys: string[] =
- cacheStorage.runScript.mock.calls[1][0].keys;
-
- expect(entitledKeys).toContain(API_KEY_OVERRIDE_BUCKET_KEY);
- expect(notEntitledKeys).toEqual(
- entitledKeys.filter((key) => key !== API_KEY_OVERRIDE_BUCKET_KEY),
- );
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts
deleted file mode 100644
index ba3530219fe..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { Logger } from '@nestjs/common';
-import { DiscoveryService } from '@nestjs/core';
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';
-import {
- type UsageEventRow,
- type WorkspaceEventEnvelope,
-} from 'src/engine/core-modules/event-logs/types/workspace-event-envelope.type';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
-import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
-import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
-import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
-import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
-import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
-
-const API_REQUEST: RecordUsageInput = {
- resourceType: UsageResourceType.API,
- operationType: UsageOperationType.API_REQUEST,
- quantity: 1,
- unit: UsageUnit.REQUEST,
-};
-
-describe('UsageRecorderService', () => {
- let recorder: UsageRecorderService;
- let dispatch: jest.Mock;
-
- const dispatchedRows = (): UsageEventRow[] =>
- dispatch.mock.calls
- .flatMap((call) => call[0] as WorkspaceEventEnvelope[])
- .map((envelope) => envelope.row as UsageEventRow);
-
- beforeEach(async () => {
- jest.spyOn(Logger.prototype, 'warn').mockImplementation();
- jest.spyOn(Logger.prototype, 'error').mockImplementation();
-
- dispatch = jest.fn().mockResolvedValue(undefined);
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- UsageRecorderService,
- {
- provide: EventLogEmitterService,
- useValue: { dispatch, isEnabled: jest.fn().mockReturnValue(true) },
- },
- {
- provide: WorkspaceEventEmitter,
- useValue: { emitCustomBatchEvent: jest.fn() },
- },
- {
- provide: TwentyConfigService,
- useValue: {
- get: jest.fn((key: string) =>
- key === 'USAGE_ROLLUP_FLUSH_INTERVAL_MS' ? 60_000 : false,
- ),
- },
- },
- {
- provide: DiscoveryService,
- useValue: { getProviders: () => [] },
- },
- ],
- }).compile();
-
- recorder = module.get<UsageRecorderService>(UsageRecorderService);
- recorder.onModuleInit();
- });
-
- afterEach(async () => {
- await recorder.flushAndStop();
- jest.restoreAllMocks();
- });
-
- it('dispatches one aggregated batch per workspace on shutdown', async () => {
- recorder.accumulate('ws-1', API_REQUEST);
- recorder.accumulate('ws-1', API_REQUEST);
- recorder.accumulate('ws-2', API_REQUEST);
-
- await recorder.onModuleDestroy();
-
- expect(dispatch).toHaveBeenCalledTimes(2);
- expect(dispatchedRows()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ workspaceId: 'ws-1', quantity: 2 }),
- expect.objectContaining({ workspaceId: 'ws-2', quantity: 1 }),
- ]),
- );
- });
-
- it('re-buffers the counts of a failed dispatch instead of dropping them', async () => {
- dispatch.mockRejectedValueOnce(new Error('clickhouse unreachable'));
- recorder.accumulate('ws-1', API_REQUEST);
-
- await recorder.onModuleDestroy();
-
- recorder.accumulate('ws-1', API_REQUEST);
- await recorder.onModuleDestroy();
-
- expect(dispatchedRows()).toContainEqual(
- expect.objectContaining({ workspaceId: 'ws-1', quantity: 2 }),
- );
- });
-
- // Available credits are a plain sum over a signed Int64, so a negative amount
- // hands the workspace credits, and a fractional or out-of-range one is not a
- // value that column can hold.
- it.each([
- ['a negative amount', -1_000_000],
- ['negative infinity', Number.NEGATIVE_INFINITY],
- ['positive infinity', Number.POSITIVE_INFINITY],
- ['NaN', Number.NaN],
- ['a fractional amount', 1_000.5],
- ['an amount beyond the safe integer range', Number.MAX_SAFE_INTEGER + 2],
- ])('records zero credits rather than %s', async (_case, creditsUsedMicro) => {
- recorder.accumulate('ws-1', { ...API_REQUEST, creditsUsedMicro });
-
- await recorder.onModuleDestroy();
-
- expect(dispatchedRows()).toEqual([
- expect.objectContaining({ workspaceId: 'ws-1', creditsUsedMicro: 0 }),
- ]);
- });
-
- it('keeps the event so the activity stays visible when its credits are refused', async () => {
- recorder.accumulate('ws-1', { ...API_REQUEST, creditsUsedMicro: -5 });
-
- await recorder.onModuleDestroy();
-
- expect(dispatchedRows()).toEqual([
- expect.objectContaining({
- operationType: UsageOperationType.API_REQUEST,
- quantity: 1,
- creditsUsedMicro: 0,
- }),
- ]);
- });
-
- it('records a positive integer amount unchanged', async () => {
- recorder.accumulate('ws-1', { ...API_REQUEST, creditsUsedMicro: 1_234 });
-
- await recorder.onModuleDestroy();
-
- expect(dispatchedRows()).toEqual([
- expect.objectContaining({ creditsUsedMicro: 1_234 }),
- ]);
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.spec.ts b/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.spec.ts
deleted file mode 100644
index 6c36b391b18..00000000000
--- a/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.spec.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
-import { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
-
-import { UserSessionService } from './user-session.service';
-
-describe('UserSessionService.issueSessionForTokenPair', () => {
- const userSessionRepository = {
- create: jest.fn((input) => input),
- save: jest.fn(),
- };
- const jwtWrapperService = {
- decode: jest.fn().mockReturnValue({
- type: JwtTokenTypeEnum.ACCESS,
- userId: 'user-id',
- workspaceId: 'workspace-id',
- userWorkspaceId: 'user-workspace-id',
- authProvider: AuthProviderEnum.Password,
- }),
- };
- const twentyConfigService = {
- get: jest.fn().mockReturnValue('30d'),
- };
- const userSessionCookieService = {
- attachSessionTokenToResponse: jest.fn(),
- clearSessionCookie: jest.fn(),
- extractSessionTokenFromRequest: jest.fn(),
- };
- const service = new UserSessionService(
- userSessionRepository as never,
- {} as never,
- {} as never,
- twentyConfigService as never,
- jwtWrapperService as never,
- {} as never,
- userSessionCookieService as never,
- );
- const tokenPair = {
- accessOrWorkspaceAgnosticToken: {
- token: 'access-token',
- expiresAt: new Date('2026-01-01T00:00:00.000Z'),
- },
- refreshToken: {
- token: 'refresh-token',
- expiresAt: new Date('2026-01-01T00:00:00.000Z'),
- },
- };
-
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('preserves the presented session when replacement creation fails', async () => {
- const creationError = new Error('session insert failed');
-
- userSessionCookieService.extractSessionTokenFromRequest.mockReturnValue(
- 'presented-session-token',
- );
- userSessionRepository.save.mockRejectedValue(creationError);
-
- const revokeSessionByToken = jest.spyOn(service, 'revokeSessionByToken');
-
- await expect(
- service.issueSessionForTokenPair({
- tokenPair,
- request: { headers: {}, ip: '127.0.0.1', res: {} } as never,
- origin: 'sign_in',
- }),
- ).rejects.toBe(creationError);
-
- expect(revokeSessionByToken).not.toHaveBeenCalled();
- expect(
- userSessionCookieService.attachSessionTokenToResponse,
- ).not.toHaveBeenCalled();
- expect(userSessionCookieService.clearSessionCookie).not.toHaveBeenCalled();
- });
-
- it('fails when the required response is unavailable', async () => {
- await expect(
- service.issueSessionForTokenPair({
- tokenPair,
- request: { headers: {} } as never,
- origin: 'sign_in',
- }),
- ).rejects.toThrow('Cannot issue a user session without an HTTP response');
-
- expect(userSessionRepository.save).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/user-workspace/services/__tests__/user-workspace-auth-context.service.spec.ts b/packages/twenty-server/src/engine/core-modules/user-workspace/services/__tests__/user-workspace-auth-context.service.spec.ts
deleted file mode 100644
index c011af21d99..00000000000
--- a/packages/twenty-server/src/engine/core-modules/user-workspace/services/__tests__/user-workspace-auth-context.service.spec.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-import { withWorkspaceAuthContext } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
-import { type UserWorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { UserWorkspaceAuthContextService } from 'src/engine/core-modules/user-workspace/services/user-workspace-auth-context.service';
-
-const args = { workspaceId: 'workspace', userWorkspaceId: 'membership' };
-const build = () => {
- const repository = {
- findOne: jest.fn().mockResolvedValue({
- id: 'membership',
- userId: 'user',
- user: { id: 'user', createdAt: new Date(), updatedAt: new Date() },
- }),
- };
- const member = {
- id: 'member',
- userId: 'user',
- deletedAt: null as Date | null,
- };
- const cache = {
- getOrRecompute: jest.fn().mockResolvedValue({
- flatWorkspaceMemberMaps: {
- idByUserId: { user: 'member' },
- byId: { member },
- },
- }),
- };
- return {
- service: new UserWorkspaceAuthContextService(
- repository as never,
- cache as never,
- ),
- repository,
- cache,
- member,
- };
-};
-
-describe('Fresh workspace user context', () => {
- it('reloads the live membership for each authorization check', async () => {
- const { service, repository } = build();
- await expect(service.resolve(args)).resolves.toMatchObject({
- type: 'user',
- userWorkspaceId: 'membership',
- workspaceMemberId: 'member',
- });
- repository.findOne.mockResolvedValue(null);
- await expect(service.resolve(args)).rejects.toMatchObject({
- code: 'UNAUTHENTICATED',
- });
- expect(repository.findOne).toHaveBeenCalledWith({
- where: { id: 'membership', workspaceId: 'workspace' },
- relations: { user: true },
- });
- });
-
- it('denies a soft-deleted workspace member', async () => {
- const { service, member } = build();
- member.deletedAt = new Date();
- await expect(service.resolve(args)).rejects.toMatchObject({
- code: 'UNAUTHENTICATED',
- });
- });
-
- it('denies a disabled user even while their membership remains', async () => {
- const { service, repository } = build();
- repository.findOne.mockResolvedValue({
- id: 'membership',
- userId: 'user',
- user: { id: 'user', disabled: true },
- });
- await expect(service.resolve(args)).rejects.toMatchObject({
- code: 'UNAUTHENTICATED',
- });
- });
-
- it('rejects missing membership identifiers before querying', async () => {
- const { service, repository } = build();
- await expect(
- service.resolve({ ...args, userWorkspaceId: '' }),
- ).rejects.toMatchObject({ code: 'UNAUTHENTICATED' });
- expect(repository.findOne).not.toHaveBeenCalled();
- });
-
- it('retains the request application restriction when rebuilding the same user', async () => {
- const { service } = build();
- const context = {
- type: 'user',
- workspace: { id: 'workspace' },
- userWorkspaceId: 'membership',
- application: { id: 'app', defaultRoleId: 'app-role' },
- } as UserWorkspaceAuthContext;
- await withWorkspaceAuthContext(context, async () => {
- await expect(service.resolve(args)).resolves.toMatchObject({
- application: context.application,
- });
- const anotherRecipient = await service.resolve({
- ...args,
- userWorkspaceId: 'another-recipient',
- });
- expect(anotherRecipient.application).toBeUndefined();
- });
- });
-});
-
-describe('Persisted application scope', () => {
- it('reloads the application role when executing a queued message', async () => {
- const { service, cache } = build();
- cache.getOrRecompute
- .mockResolvedValueOnce({
- flatWorkspaceMemberMaps: {
- idByUserId: { user: 'member' },
- byId: { member: { id: 'member' } },
- },
- } as never)
- .mockResolvedValueOnce({
- flatApplicationMaps: {
- byId: { app: { id: 'app', defaultRoleId: 'current-role' } },
- },
- } as never);
- await expect(
- service.resolve({ ...args, applicationId: 'app' }),
- ).resolves.toMatchObject({
- application: { id: 'app', defaultRoleId: 'current-role' },
- });
- });
- it('fails closed when the original application was removed', async () => {
- const { service, cache } = build();
- cache.getOrRecompute
- .mockResolvedValueOnce({
- flatWorkspaceMemberMaps: {
- idByUserId: { user: 'member' },
- byId: { member: { id: 'member' } },
- },
- } as never)
- .mockResolvedValueOnce({ flatApplicationMaps: { byId: {} } } as never);
- await expect(
- service.resolve({ ...args, applicationId: 'removed' }),
- ).rejects.toMatchObject({ code: 'UNAUTHENTICATED' });
- });
- it('does not inherit an ambient application when a queued sender has explicit direct access', async () => {
- const { service } = build();
- const request = {
- type: 'user',
- workspace: { id: args.workspaceId },
- userWorkspaceId: args.userWorkspaceId,
- application: { id: 'app' },
- } as UserWorkspaceAuthContext;
- await withWorkspaceAuthContext(request, async () => {
- expect(
- (await service.resolve({ ...args, applicationId: null })).application,
- ).toBeUndefined();
- });
- });
-});
-
-describe('Workspace member authorization', () => {
- const memberArgs = { workspaceId: 'workspace', workspaceMemberId: 'member' };
- it('resolves a member to a fresh membership scoped to the same workspace', async () => {
- const { service, repository } = build();
- await expect(
- service.resolveWorkspaceMember(memberArgs),
- ).resolves.toMatchObject({
- userWorkspaceId: 'membership',
- workspaceMemberId: 'member',
- });
- expect(repository.findOne).toHaveBeenCalledWith({
- where: { workspaceId: 'workspace', userId: 'user' },
- select: { id: true },
- });
- repository.findOne.mockResolvedValue(null);
- await expect(
- service.resolveWorkspaceMember(memberArgs),
- ).rejects.toMatchObject({ code: 'UNAUTHENTICATED' });
- });
- it.each(['', 'unknown'])(
- 'rejects missing member %s without looking up membership',
- async (workspaceMemberId) => {
- const { service, repository } = build();
- await expect(
- service.resolveWorkspaceMember({ ...memberArgs, workspaceMemberId }),
- ).rejects.toMatchObject({ code: 'UNAUTHENTICATED' });
- expect(repository.findOne).not.toHaveBeenCalled();
- },
- );
- it('rejects a deleted member before resolving membership', async () => {
- const { service, repository, member } = build();
- member.deletedAt = new Date();
- await expect(
- service.resolveWorkspaceMember(memberArgs),
- ).rejects.toMatchObject({ code: 'UNAUTHENTICATED' });
- expect(repository.findOne).not.toHaveBeenCalled();
- });
- it('rejects a member replaced during authorization', async () => {
- const { service } = build();
- jest
- .spyOn(service, 'resolve')
- .mockResolvedValue({ workspaceMemberId: 'replacement' } as never);
- await expect(
- service.resolveWorkspaceMember(memberArgs),
- ).rejects.toMatchObject({ code: 'UNAUTHENTICATED' });
- });
-});
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts
deleted file mode 100644
index 0ad54cde43f..00000000000
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/__tests__/core-workflow-version-mutation.workspace-service.spec.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-import { WorkflowActionType } from 'twenty-shared/workflow';
-
-import { CoreWorkflowVersionMutationWorkspaceService } from 'src/engine/core-modules/workflow/services/core-workflow-version-mutation.workspace-service';
-import { CoreWorkflowVersionPostCommitError } from 'src/engine/core-modules/workflow/services/core-workflow-version-write.service';
-import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
-
-const workspaceId = '20202020-0000-0000-0000-000000000001';
-const userWorkspaceId = '20202020-0000-0000-0000-000000000009';
-const coreWorkflowVersionId = '20202020-0000-0000-0000-000000000002';
-const stepId = '20202020-0000-0000-0000-000000000003';
-
-const existingCodeStep = {
- id: stepId,
- name: 'Code',
- type: WorkflowActionType.CODE,
- valid: true,
- settings: {
- input: {
- logicFunctionId: '20202020-0000-0000-0000-000000000004',
- logicFunctionInput: {},
- },
- outputSchema: {},
- errorHandlingOptions: {
- retryOnFailure: { value: 0 },
- continueOnFailure: { value: false },
- },
- },
- nextStepIds: [],
-} as WorkflowAction;
-
-const replacementEmptyStep = {
- id: '20202020-0000-0000-0000-000000000005',
- name: 'Empty',
- type: WorkflowActionType.EMPTY,
- valid: true,
- settings: {
- input: {},
- outputSchema: {},
- errorHandlingOptions: {
- retryOnFailure: { value: 0 },
- continueOnFailure: { value: false },
- },
- },
- nextStepIds: [],
-} as WorkflowAction;
-
-describe('CoreWorkflowVersionMutationWorkspaceService', () => {
- const getValidatedDraftCoreWorkflowVersion = jest.fn();
- const writeContentAndMirror = jest.fn();
- const runStepCreationSideEffectsAndBuildStep = jest.fn();
- const runWorkflowVersionStepDeletionSideEffects = jest.fn();
- const enrichOutputSchema = jest.fn();
-
- const service = new CoreWorkflowVersionMutationWorkspaceService(
- {} as never,
- {} as never,
- {
- getValidatedDraftCoreWorkflowVersion,
- writeContentAndMirror,
- } as never,
- {} as never,
- {} as never,
- {
- runStepCreationSideEffectsAndBuildStep,
- runWorkflowVersionStepDeletionSideEffects,
- } as never,
- { enrichOutputSchema } as never,
- );
-
- beforeEach(() => {
- jest.clearAllMocks();
- getValidatedDraftCoreWorkflowVersion.mockResolvedValue({
- coreWorkflowVersion: {
- triggers: [],
- steps: [existingCodeStep],
- },
- trigger: null,
- steps: [existingCodeStep],
- });
- runStepCreationSideEffectsAndBuildStep.mockResolvedValue({
- builtStep: replacementEmptyStep,
- });
- enrichOutputSchema.mockImplementation(
- async ({ step }: { step: WorkflowAction }) => step,
- );
- runWorkflowVersionStepDeletionSideEffects.mockResolvedValue(undefined);
- });
-
- it('keeps the existing step resource when the optimistic write is rejected', async () => {
- const writeError = new Error('Workflow version changed');
-
- writeContentAndMirror.mockRejectedValue(writeError);
-
- await expect(
- service.updateStep({
- workspaceId,
- userWorkspaceId,
- coreWorkflowVersionId,
- step: { ...replacementEmptyStep, id: stepId },
- }),
- ).rejects.toBe(writeError);
-
- expect(runWorkflowVersionStepDeletionSideEffects).not.toHaveBeenCalledWith({
- step: existingCodeStep,
- workspaceId,
- });
- expect(runWorkflowVersionStepDeletionSideEffects).toHaveBeenCalledWith({
- step: expect.objectContaining({ type: WorkflowActionType.EMPTY }),
- workspaceId,
- });
- });
-
- it('deletes the existing step resource only after the replacement is stored', async () => {
- writeContentAndMirror.mockResolvedValue(undefined);
-
- await service.updateStep({
- workspaceId,
- userWorkspaceId,
- coreWorkflowVersionId,
- step: { ...replacementEmptyStep, id: stepId },
- });
-
- expect(runWorkflowVersionStepDeletionSideEffects).toHaveBeenCalledWith({
- step: existingCodeStep,
- workspaceId,
- });
- expect(writeContentAndMirror.mock.invocationCallOrder[0]).toBeLessThan(
- runWorkflowVersionStepDeletionSideEffects.mock.invocationCallOrder[0],
- );
- });
-
- it('keeps the committed replacement and deletes the old resource when cache invalidation fails', async () => {
- const cacheError = new CoreWorkflowVersionPostCommitError(
- new Error('Cache unavailable'),
- );
-
- writeContentAndMirror.mockRejectedValue(cacheError);
-
- await expect(
- service.updateStep({
- workspaceId,
- userWorkspaceId,
- coreWorkflowVersionId,
- step: { ...replacementEmptyStep, id: stepId },
- }),
- ).rejects.toBe(cacheError);
-
- expect(runWorkflowVersionStepDeletionSideEffects).toHaveBeenCalledTimes(1);
- expect(runWorkflowVersionStepDeletionSideEffects).toHaveBeenCalledWith({
- step: existingCodeStep,
- workspaceId,
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/run-agent-attachment.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/run-agent-attachment.service.spec.ts
deleted file mode 100644
index 7af001e3f80..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/run-agent-attachment.service.spec.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-import { FileFolder } from 'twenty-shared/types';
-import { In, Like } from 'typeorm';
-
-import { RunAgentAttachmentService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/run-agent-attachment.service';
-import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
-
-const WORKSPACE_ID = 'workspace-id';
-const FILE_ID = '6fdbd0ba-9a10-4b71-b0b7-2b1d64f8dc27';
-
-describe('RunAgentAttachmentService', () => {
- it('resolves attachments only against uploaded agent chat files of the workspace', async () => {
- const fileRepository = {
- find: jest
- .fn()
- .mockResolvedValue([{ id: FILE_ID, mimeType: 'image/png' }]),
- };
- const service = new RunAgentAttachmentService(
- fileRepository as never,
- {
- signFileByIdUrl: jest
- .fn()
- .mockResolvedValue('https://twenty.test/file'),
- } as never,
- );
-
- await service.buildModelMessagesOrThrow({
- messages: [
- { role: 'user', content: 'hi', attachments: [{ fileId: FILE_ID }] },
- ],
- workspaceId: WORKSPACE_ID,
- modalities: ['image'],
- });
-
- expect(fileRepository.find).toHaveBeenCalledWith(WORKSPACE_ID, {
- where: {
- id: In([FILE_ID]),
- path: Like(`${FileFolder.AgentChat}/%`),
- status: 'UPLOADED',
- },
- });
- });
-
- it('does not query files for a conversation that carries no attachment', async () => {
- const fileRepository = { find: jest.fn() };
- const service = new RunAgentAttachmentService(
- fileRepository as never,
- {
- signFileByIdUrl: jest.fn(),
- } as never,
- );
-
- expect(
- await service.buildModelMessagesOrThrow({
- messages: [{ role: 'user', content: 'hello' }],
- workspaceId: WORKSPACE_ID,
- modalities: ['image'],
- }),
- ).toEqual([{ role: 'user', content: 'hello' }]);
- expect(fileRepository.find).not.toHaveBeenCalled();
- });
-
- it('hands a supported attachment to the model as a file part', async () => {
- const fileRepository = {
- find: jest
- .fn()
- .mockResolvedValue([{ id: FILE_ID, mimeType: 'image/png' }]),
- };
- const service = new RunAgentAttachmentService(
- fileRepository as never,
- {
- signFileByIdUrl: jest
- .fn()
- .mockResolvedValue('https://twenty.test/file'),
- } as never,
- );
-
- expect(
- await service.buildModelMessagesOrThrow({
- messages: [
- {
- role: 'user',
- content: 'what is in this?',
- attachments: [{ fileId: FILE_ID, filename: 'screenshot.png' }],
- },
- ],
- workspaceId: WORKSPACE_ID,
- modalities: ['image'],
- }),
- ).toEqual([
- {
- role: 'user',
- content: [
- { type: 'text', text: 'what is in this?' },
- {
- type: 'file',
- data: 'https://twenty.test/file',
- mediaType: 'image/png',
- filename: 'screenshot.png',
- },
- ],
- },
- ]);
- });
-
- it('degrades an attachment the resolved model cannot read into text', async () => {
- const fileRepository = {
- find: jest
- .fn()
- .mockResolvedValue([{ id: FILE_ID, mimeType: 'application/pdf' }]),
- };
- const service = new RunAgentAttachmentService(
- fileRepository as never,
- {
- signFileByIdUrl: jest
- .fn()
- .mockResolvedValue('https://twenty.test/file'),
- } as never,
- );
-
- expect(
- await service.buildModelMessagesOrThrow({
- messages: [
- {
- role: 'user',
- content: 'summarize this',
- attachments: [{ fileId: FILE_ID, filename: 'report.pdf' }],
- },
- ],
- workspaceId: WORKSPACE_ID,
- modalities: ['image'],
- }),
- ).toEqual([
- {
- role: 'user',
- content: [
- { type: 'text', text: 'summarize this' },
- {
- type: 'text',
- text: '[Attached file: report.pdf (type: application/pdf) — file type is not supported for direct analysis]',
- },
- ],
- },
- ]);
- });
-
- it('still refuses a file id that resolves to nothing in the workspace', async () => {
- const fileRepository = { find: jest.fn().mockResolvedValue([]) };
- const service = new RunAgentAttachmentService(
- fileRepository as never,
- {
- signFileByIdUrl: jest.fn(),
- } as never,
- );
-
- await expect(
- service.buildModelMessagesOrThrow({
- messages: [
- { role: 'user', content: 'hi', attachments: [{ fileId: FILE_ID }] },
- ],
- workspaceId: WORKSPACE_ID,
- modalities: ['image'],
- }),
- ).rejects.toThrow(
- expect.objectContaining({ code: AiExceptionCode.INVALID_AGENT_INPUT }),
- );
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-actor.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-actor.service.spec.ts
deleted file mode 100644
index 6e2f5317967..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-actor.service.spec.ts
+++ /dev/null
@@ -1,285 +0,0 @@
-import { withWorkspaceAuthContext } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
-import { AgentChatActorService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service';
-import { AgentMessageStatus } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
-
-const workspaceId = 'workspace';
-const threadId = 'thread';
-const sender = { userWorkspaceId: 'sender', applicationId: null };
-const build = () => {
- const message = {
- id: 'message',
- threadId,
- turnId: 'turn',
- senderUserWorkspaceId: 'sender' as string | null,
- senderApplicationId: null as string | null,
- status: AgentMessageStatus.SENT,
- };
- const messages = { findOne: jest.fn().mockResolvedValue(message) };
- const threads = {
- findOneOrFail: jest
- .fn()
- .mockResolvedValue({ workspaceMemberId: 'owner-member' }),
- };
- const chat = {
- getWritableThread: jest
- .fn()
- .mockResolvedValue({ id: threadId, deletedAt: null }),
- };
- const auth = {
- resolveWorkspaceMember: jest
- .fn()
- .mockResolvedValue({ userWorkspaceId: 'owner' }),
- resolve: jest
- .fn()
- .mockImplementation(async ({ userWorkspaceId, applicationId }) => ({
- type: 'user',
- workspace: { id: workspaceId },
- userWorkspaceId,
- workspaceMemberId: userWorkspaceId + '-member',
- user: { id: 'user' },
- workspaceMember: { id: 'member' },
- ...(applicationId
- ? { application: { id: applicationId, defaultRoleId: 'app-role' } }
- : {}),
- })),
- };
- const permissions = {
- userHasWorkspaceSettingPermission: jest.fn().mockResolvedValue(true),
- };
- const cache = {
- getOrRecompute: jest.fn().mockResolvedValue({
- userWorkspaceRoleMap: { sender: 'sender-role', owner: 'owner-role' },
- }),
- };
- const service = new AgentChatActorService(
- messages as never,
- threads as never,
- chat as never,
- auth as never,
- permissions as never,
- cache as never,
- );
- return {
- service,
- message,
- messages,
- threads,
- chat,
- auth,
- permissions,
- cache,
- };
-};
-const job = {
- workspaceId,
- threadId,
- messageId: 'message',
- turnId: 'turn',
- userWorkspaceId: 'sender',
-};
-
-describe('Chat execution sender', () => {
- it('executes as the saved sender rather than the thread owner', async () => {
- const { service, chat } = build();
- await expect(service.authorizeJob(job)).resolves.toMatchObject({ sender });
- expect(chat.getWritableThread).toHaveBeenCalledWith({
- workspaceId,
- threadId,
- workspaceMemberId: 'sender-member',
- });
- });
- it('rejects unattributed messages on ownerless threads', async () => {
- const { service, message, threads, auth } = build();
- message.senderUserWorkspaceId = null;
- threads.findOneOrFail.mockResolvedValue({ workspaceMemberId: null });
- await expect(service.resolveMessage(job)).rejects.toMatchObject({
- code: 'RUN_AS_WORKSPACE_MEMBER_NOT_FOUND',
- });
- expect(auth.resolveWorkspaceMember).not.toHaveBeenCalled();
- });
- it('rejects a job attempting to execute another participant’s message', async () => {
- const { service, chat } = build();
- await expect(
- service.authorizeJob({ ...job, userWorkspaceId: 'owner' }),
- ).rejects.toMatchObject({ code: 'MESSAGE_NOT_FOUND' });
- expect(chat.getWritableThread).not.toHaveBeenCalled();
- });
- it('rejects a mismatched turn', async () => {
- const { service } = build();
- await expect(
- service.authorizeJob({ ...job, turnId: 'other-turn' }),
- ).rejects.toMatchObject({ code: 'MESSAGE_NOT_FOUND' });
- });
- it('does not execute a message still in the queue', async () => {
- const { service, message } = build();
- message.status = AgentMessageStatus.QUEUED;
- await expect(service.authorizeJob(job)).rejects.toMatchObject({
- code: 'MESSAGE_NOT_FOUND',
- });
- });
- it('uses the original participant for historical messages without attribution', async () => {
- const { service, message } = build();
- message.senderUserWorkspaceId = null;
- await expect(
- service.authorizeJob({ ...job, userWorkspaceId: 'owner' }),
- ).resolves.toMatchObject({
- sender: { userWorkspaceId: 'owner', applicationId: null },
- });
- await expect(service.authorizeJob(job)).rejects.toMatchObject({
- code: 'MESSAGE_NOT_FOUND',
- });
- });
- it('resolves old queued job payloads from their persisted turn', async () => {
- const { service, messages } = build();
- await service.authorizeJob({ ...job, messageId: undefined });
- expect(messages.findOne).toHaveBeenCalledWith(
- workspaceId,
- expect.objectContaining({
- where: { threadId, turnId: 'turn', role: 'user' },
- }),
- );
- });
- it('rejects jobs without a durable message or turn identity', async () => {
- const { service, messages } = build();
- await expect(
- service.authorizeJob({ ...job, messageId: undefined, turnId: undefined }),
- ).rejects.toMatchObject({ code: 'MESSAGE_NOT_FOUND' });
- expect(messages.findOne).not.toHaveBeenCalled();
- });
- it('intersects current sender and application roles', async () => {
- const { service } = build();
- await expect(
- service.authorize({
- workspaceId,
- threadId,
- sender: { ...sender, applicationId: 'app' },
- }),
- ).resolves.toMatchObject({
- rolePermissionConfig: { intersectionOf: ['sender-role', 'app-role'] },
- });
- });
- it('does not inherit ambient request application restrictions from another participant', async () => {
- const { service, auth } = build();
- await service.authorize({ workspaceId, threadId, sender });
- expect(auth.resolve).toHaveBeenCalledWith({ workspaceId, ...sender });
- });
- it('checks live membership again after a message has been accepted', async () => {
- const { service, auth } = build();
- await service.authorizeJob(job);
- auth.resolve.mockRejectedValue(new Error('Membership removed'));
- await expect(service.authorizeJob(job)).rejects.toThrow(
- 'Membership removed',
- );
- });
- it('checks the current thread permission before execution', async () => {
- const { service, chat } = build();
- chat.getWritableThread.mockRejectedValue(new Error('Access revoked'));
- await expect(service.authorizeJob(job)).rejects.toThrow('Access revoked');
- });
- it('denies revoked AI permission', async () => {
- const { service, permissions } = build();
- permissions.userHasWorkspaceSettingPermission.mockResolvedValue(false);
- await expect(service.authorizeJob(job)).rejects.toMatchObject({
- code: 'THREAD_NOT_FOUND',
- });
- });
- it('denies soft deleted threads', async () => {
- const { service, chat } = build();
- chat.getWritableThread.mockResolvedValue({
- id: threadId,
- deletedAt: new Date().toISOString(),
- } as never);
- await expect(service.authorizeJob(job)).rejects.toMatchObject({
- code: 'THREAD_NOT_FOUND',
- });
- });
- it('denies a sender without a current role', async () => {
- const { service, cache } = build();
- cache.getOrRecompute.mockResolvedValue({ userWorkspaceRoleMap: {} });
- await expect(service.authorizeJob(job)).rejects.toMatchObject({
- code: 'THREAD_NOT_FOUND',
- });
- });
- it.each([null, 'other-app'])(
- 'rejects retrying an application message from a different context (%s)',
- async (applicationId) => {
- const { service, message } = build();
- message.senderApplicationId = 'original-app';
- await expect(
- withWorkspaceAuthContext(
- {
- type: 'user',
- workspace: { id: workspaceId },
- userWorkspaceId: 'sender',
- application: applicationId ? { id: applicationId } : undefined,
- } as never,
- () => service.authorizeRetry(job),
- ),
- ).rejects.toMatchObject({ code: 'MESSAGE_NOT_FOUND' });
- },
- );
-
- it('allows retrying in the original sender and application context', async () => {
- const { service, message } = build();
- message.senderApplicationId = 'original-app';
- await expect(
- withWorkspaceAuthContext(
- {
- type: 'user',
- workspace: { id: workspaceId },
- userWorkspaceId: 'sender',
- application: { id: 'original-app' },
- } as never,
- () => service.authorizeRetry(job),
- ),
- ).resolves.toMatchObject({
- sender: { userWorkspaceId: 'sender', applicationId: 'original-app' },
- });
- });
- it.each([null, 'other-app'])(
- 'rejects resolving an application tool call from a different context (%s)',
- async (applicationId) => {
- const { service, message } = build();
- message.senderApplicationId = 'original-app';
- await expect(
- withWorkspaceAuthContext(
- {
- type: 'user',
- workspace: { id: workspaceId },
- userWorkspaceId: 'sender',
- application: applicationId ? { id: applicationId } : undefined,
- } as never,
- () => service.authorizeToolCallResolution(job),
- ),
- ).rejects.toMatchObject({ code: 'TOOL_CALL_RESOLUTION_FORBIDDEN' });
- },
- );
-
- it.each([null, 'original-app'])(
- 'allows another participant to resolve in the same application context (%s)',
- async (applicationId) => {
- const { service, message } = build();
- message.senderApplicationId = applicationId;
- await expect(
- withWorkspaceAuthContext(
- {
- type: 'user',
- workspace: { id: workspaceId },
- userWorkspaceId: 'another-participant',
- application: applicationId ? { id: applicationId } : undefined,
- } as never,
- () => service.authorizeToolCallResolution(job),
- ),
- ).resolves.toBeUndefined();
- },
- );
-
- it('rejects a resolution without an authenticated request context', async () => {
- const { service } = build();
- await expect(
- service.authorizeToolCallResolution(job),
- ).rejects.toMatchObject({
- code: 'TOOL_CALL_RESOLUTION_FORBIDDEN',
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts
deleted file mode 100644
index f4fbadee29e..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts
+++ /dev/null
@@ -1,329 +0,0 @@
-import { type AgentHistoryStorageContext } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';
-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
-import { MetadataReadability } from 'twenty-shared/types';
-
-import {
- AuthException,
- AuthExceptionCode,
-} from 'src/engine/core-modules/auth/auth.exception';
-import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';
-
-const WORKSPACE_ID = '20202020-0000-4000-8000-000000000001';
-const THREAD_ID = '20202020-0000-4000-8000-000000000002';
-const args = {
- workspaceId: WORKSPACE_ID,
- threadId: THREAD_ID,
- workspaceMemberId: 'reader',
-};
-
-const buildService = () => {
- const query = jest.fn().mockResolvedValue([{ id: THREAD_ID }]);
- const thread: Record<string, unknown> = {
- id: THREAD_ID,
- workspaceMemberId: 'owner',
- };
- const threadRepository = {
- query: jest
- .fn()
- .mockImplementation(
- async (
- _workspaceId: string,
- work: (context: AgentHistoryStorageContext) => Promise<unknown>,
- ) =>
- work({
- manager: { query },
- table: () => '"workspace"."agentChatThread"',
- } as never),
- ),
- findOne: jest.fn().mockResolvedValue(thread),
- find: jest.fn().mockResolvedValue([thread]),
- };
- const authContext = {
- workspace: { id: WORKSPACE_ID },
- workspaceMemberId: 'reader',
- userWorkspaceId: 'reader-membership',
- };
- const userAuthContextService = {
- resolveWorkspaceMember: jest.fn().mockResolvedValue(authContext),
- };
- const repository = {
- validateWriteIsPermitted: jest.fn(),
- findRecordIdsAllowedForOperation: jest.fn().mockResolvedValue([THREAD_ID]),
- find: jest.fn().mockResolvedValue([{ id: THREAD_ID }]),
- };
- const manager = {
- executeInWorkspaceContext: jest
- .fn()
- .mockImplementation(async (work: () => Promise<unknown>) => work()),
- getRepositoryWithContextPermissions: () => repository,
- };
- const objectMetadata = {
- id: 'object',
- readability: MetadataReadability.PRIVATE,
- };
- const flatFieldMetadataMaps = {
- byUniversalIdentifier: {} as Record<string, unknown>,
- };
- const cache = {
- getOrRecompute: jest.fn().mockResolvedValue({
- flatObjectMetadataMaps: {
- byUniversalIdentifier: {
- [STANDARD_OBJECTS.agentChatThread.universalIdentifier]:
- objectMetadata,
- },
- },
- flatFieldMetadataMaps,
- }),
- };
- const aiPermissions = {
- userHasWorkspaceSettingPermission: jest.fn().mockResolvedValue(true),
- };
- const permissions = {
- canRead: true,
- canUpdate: false,
- canDelete: false,
- canSoftDelete: false,
- };
- const sharing = {
- getPermissions: jest.fn().mockResolvedValue(permissions),
- getPermissionsForRecords: jest
- .fn()
- .mockResolvedValue(new Map([[THREAD_ID, permissions]])),
- };
- const service = new AgentChatSharingService(
- threadRepository as never,
- userAuthContextService as never,
- { deleteByRecordIdsInTransaction: jest.fn() } as never,
- cache as never,
- aiPermissions as never,
- sharing as never,
- manager as never,
- );
- return {
- query,
- service,
- thread,
- flatFieldMetadataMaps,
- threadRepository,
- userAuthContextService,
- repository,
- manager,
- objectMetadata,
- aiPermissions,
- sharing,
- permissions,
- authContext,
- };
-};
-
-describe('Conversation common record access', () => {
- it('creates threads owned by the member, with the legacy owner', async () => {
- const { service, query } = buildService();
- await expect(
- service.createThread({
- workspaceId: WORKSPACE_ID,
- workspaceMemberId: 'reader',
- id: THREAD_ID,
- }),
- ).resolves.toMatchObject({ id: THREAD_ID });
- const [insert, parameters] = query.mock.calls[0];
- expect(insert).toContain('"workspaceMemberId"');
- expect(insert).toContain('"userWorkspaceId"');
- expect(parameters).toEqual([
- THREAD_ID,
- null,
- 'reader',
- 'reader-membership',
- ]);
- });
-
- it('uses the common record policy for a non-owner reader', async () => {
- const { service, repository } = buildService();
- await expect(service.getReadableThread(args)).resolves.toMatchObject({
- id: THREAD_ID,
- });
- expect(repository.findRecordIdsAllowedForOperation).toHaveBeenCalledWith({
- recordIds: [THREAD_ID],
- operationType: 'select',
- updatedColumns: [],
- withDeleted: true,
- });
- });
-
- it.each(['update', 'delete', 'soft-delete', 'restore'] as const)(
- 'uses the corresponding %s permission without an owner override',
- async (operation) => {
- const { service, repository } = buildService();
- await expect(
- service.getThreadWithAccess({ ...args, operationType: operation }),
- ).resolves.toBeDefined();
- repository.findRecordIdsAllowedForOperation.mockResolvedValue([]);
- await expect(
- service.getThreadWithAccess({
- ...args,
- workspaceMemberId: 'owner',
- operationType: operation,
- }),
- ).rejects.toMatchObject({ code: 'THREAD_NOT_FOUND' });
- },
- );
-
- it('checks field permissions when renaming', async () => {
- const { service, repository } = buildService();
- await service.getThreadWithAccess({
- ...args,
- operationType: 'update',
- updatedColumns: ['title'],
- });
- expect(repository.findRecordIdsAllowedForOperation).toHaveBeenCalledWith({
- recordIds: [THREAD_ID],
- operationType: 'update',
- updatedColumns: ['title'],
- withDeleted: true,
- });
- });
-
- it('restores a soft deleted conversation through the restore permission', async () => {
- const { service, query, repository } = buildService();
- const deletedThread = {
- id: THREAD_ID,
- workspaceMemberId: 'owner',
- deletedAt: '2026-09-01T00:00:00.000Z',
- };
- query.mockImplementation(async (sql: string) =>
- sql.includes('FOR UPDATE')
- ? [deletedThread]
- : sql.includes('restored_thread')
- ? [{ ...deletedThread, deletedAt: null }]
- : [],
- );
- await expect(service.restoreThreadWithAccess(args)).resolves.toEqual({
- ...deletedThread,
- deletedAt: null,
- });
- expect(repository.findRecordIdsAllowedForOperation).toHaveBeenCalledWith({
- recordIds: [THREAD_ID],
- operationType: 'restore',
- updatedColumns: [],
- withDeleted: true,
- });
- expect(
- query.mock.calls.some(([sql]) => sql.includes('"deletedAt" = NULL')),
- ).toBe(true);
- });
-
- it('leaves a conversation that is not deleted untouched on restore', async () => {
- const { service, query } = buildService();
- const liveThread = { id: THREAD_ID, workspaceMemberId: 'owner' };
- query.mockImplementation(async (sql: string) =>
- sql.includes('FOR UPDATE') ? [liveThread] : [],
- );
- await expect(service.restoreThreadWithAccess(args)).resolves.toEqual(
- liveThread,
- );
- expect(
- query.mock.calls.some(([sql]) => sql.includes('restored_thread')),
- ).toBe(false);
- });
-
- it('refuses restore without the restore permission', async () => {
- const { service, query, repository } = buildService();
- query.mockImplementation(async (sql: string) =>
- sql.includes('FOR UPDATE')
- ? [{ id: THREAD_ID, deletedAt: '2026-09-01T00:00:00.000Z' }]
- : [],
- );
- repository.findRecordIdsAllowedForOperation.mockResolvedValue([]);
- await expect(service.restoreThreadWithAccess(args)).rejects.toMatchObject({
- code: 'THREAD_NOT_FOUND',
- });
- expect(
- query.mock.calls.some(([sql]) => sql.includes('restored_thread')),
- ).toBe(false);
- });
-
- it('rechecks the authenticated subject and policy on every read', async () => {
- const { service, repository, userAuthContextService } = buildService();
- await expect(service.getReadableThread(args)).resolves.toBeDefined();
- repository.findRecordIdsAllowedForOperation.mockResolvedValue([]);
- await expect(service.getReadableThread(args)).rejects.toMatchObject({
- code: 'THREAD_NOT_FOUND',
- });
- expect(userAuthContextService.resolveWorkspaceMember).toHaveBeenCalledTimes(
- 2,
- );
- });
-
- it('hides history from removed members', async () => {
- const { service, userAuthContextService, threadRepository } =
- buildService();
- userAuthContextService.resolveWorkspaceMember.mockRejectedValue(
- new AuthException('Removed', AuthExceptionCode.UNAUTHENTICATED),
- );
- await expect(service.getReadableThread(args)).rejects.toMatchObject({
- code: 'THREAD_NOT_FOUND',
- });
- expect(threadRepository.findOne).not.toHaveBeenCalled();
- });
-
- it('does not hide infrastructure failures as missing records', async () => {
- const { service, userAuthContextService } = buildService();
- userAuthContextService.resolveWorkspaceMember.mockRejectedValue(
- new Error('Database unavailable'),
- );
- await expect(service.getReadableThread(args)).rejects.toThrow(
- 'Database unavailable',
- );
- });
-
- it('denies access when AI permission has been revoked', async () => {
- const { service, aiPermissions } = buildService();
- aiPermissions.userHasWorkspaceSettingPermission.mockResolvedValue(false);
- await expect(service.getReadableThread(args)).rejects.toMatchObject({
- code: 'THREAD_NOT_FOUND',
- });
- });
-
- it('does not bypass the common policy for owners of SYSTEM history', async () => {
- const { service, objectMetadata, repository } = buildService();
- objectMetadata.readability = MetadataReadability.SYSTEM;
- repository.findRecordIdsAllowedForOperation.mockResolvedValue([]);
- await expect(service.getReadableThread(args)).rejects.toMatchObject({
- code: 'THREAD_NOT_FOUND',
- });
- await expect(
- service.getReadableThread({ ...args, workspaceMemberId: 'owner' }),
- ).rejects.toMatchObject({ code: 'THREAD_NOT_FOUND' });
- expect(repository.findRecordIdsAllowedForOperation).toHaveBeenCalledTimes(
- 2,
- );
- });
-
- it('returns common capabilities, including destructive permission differences', async () => {
- const { service, sharing, permissions, authContext } = buildService();
- await expect(service.getPermissions(args)).resolves.toEqual(permissions);
- expect(sharing.getPermissionsForRecords).toHaveBeenCalledWith({
- authContext,
- objectMetadataId: 'object',
- recordIds: [THREAD_ID],
- withDeleted: true,
- });
- });
-
- it('batches capabilities', async () => {
- const { service, sharing } = buildService();
- await service.getPermissionsForThreads({ ...args, threadIds: [THREAD_ID] });
- expect(sharing.getPermissionsForRecords).toHaveBeenCalledTimes(1);
- });
-
- it.each(['update', 'delete', 'soft-delete', 'restore'] as const)(
- 'lets whoever may %s a workflow run conversation do so, like any other',
- async (operation) => {
- const { service, thread } = buildService();
- thread.workflowRunId = 'workflow-run';
- await expect(
- service.getThreadWithAccess({ ...args, operationType: operation }),
- ).resolves.toBe(thread);
- },
- );
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-thread-target.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-thread-target.service.spec.ts
deleted file mode 100644
index 1b59a02840f..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-thread-target.service.spec.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { AGENT_CHAT_THREAD_TARGET_FLAT_ENTITY_MAPS_MOCK } from 'src/engine/metadata-modules/ai/ai-chat/__mocks__/agent-chat-thread-target-flat-entity-maps.mock';
-import { AgentChatThreadTargetService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-target.service';
-import {
- PermissionsException,
- PermissionsExceptionCode,
-} from 'src/engine/metadata-modules/permissions/permissions.exception';
-
-const WORKSPACE_ID = '20202020-0000-4000-8000-000000000001';
-const THREAD_ID = '20202020-0000-4000-8000-000000000002';
-const RECORD_ID = '20202020-0000-4000-8000-000000000004';
-const TRASHED_RECORD_ID = '20202020-0000-4000-8000-000000000005';
-const UNREADABLE_RECORD_ID = '20202020-0000-4000-8000-000000000008';
-
-const MEMBER_AUTH_CONTEXT = {
- type: 'user',
- workspace: { id: WORKSPACE_ID },
- userWorkspaceId: 'member-user-workspace',
- workspaceMemberId: 'member',
-} as unknown as WorkspaceAuthContext;
-
-const args = {
- workspaceId: WORKSPACE_ID,
- threadId: THREAD_ID,
- objectNameSingular: 'company',
- recordId: RECORD_ID,
- authContext: MEMBER_AUTH_CONTEXT,
-};
-
-const buildService = () => {
- const targetRepository = {
- existsBy: jest.fn().mockResolvedValue(false),
- insert: jest.fn(),
- };
-
- // Records the member can read. A trashed record is left out, as a lookup
- // without deleted records leaves it out, and one outside the member's grants
- // is refused by the ORM.
- const readableRecordIds = new Set([RECORD_ID]);
-
- const recordRepository = {
- findOne: jest.fn().mockImplementation(async ({ where }) => {
- if (where.id === UNREADABLE_RECORD_ID) {
- throw new PermissionsException(
- 'denied',
- PermissionsExceptionCode.PERMISSION_DENIED,
- );
- }
-
- return readableRecordIds.has(where.id) ? { id: where.id } : null;
- }),
- };
-
- const workspaceOrmManager = {
- executeInWorkspaceContext: jest
- .fn()
- .mockImplementation((work: () => Promise<unknown>) => work()),
- getRepositoryWithContextPermissions: jest
- .fn()
- .mockImplementation((objectMetadataName: string) =>
- objectMetadataName === 'agentChatThreadTarget'
- ? targetRepository
- : recordRepository,
- ),
- };
-
- const workspaceCacheService = {
- getOrRecompute: jest
- .fn()
- .mockResolvedValue(AGENT_CHAT_THREAD_TARGET_FLAT_ENTITY_MAPS_MOCK),
- };
-
- return {
- service: new AgentChatThreadTargetService(
- workspaceOrmManager as never,
- workspaceCacheService as never,
- ),
- targetRepository,
- recordRepository,
- workspaceOrmManager,
- };
-};
-
-describe('Attaching a conversation to a record', () => {
- it('stores the link on the leg of the record object', async () => {
- const { service, targetRepository } = buildService();
-
- await service.attachThreadToRecord(args);
-
- expect(targetRepository.insert).toHaveBeenCalledWith(
- { threadId: THREAD_ID, targetCompanyId: RECORD_ID },
- { onConflictDoNothing: true },
- );
- });
-
- // Custom legs carry no unique index, so a second attach must not add a row.
- it('keeps a single link when the conversation is already attached', async () => {
- const { service, targetRepository } = buildService();
-
- targetRepository.existsBy.mockResolvedValueOnce(true);
-
- await service.attachThreadToRecord(args);
-
- expect(targetRepository.existsBy).toHaveBeenCalledWith({
- threadId: THREAD_ID,
- targetCompanyId: RECORD_ID,
- });
- expect(targetRepository.insert).not.toHaveBeenCalled();
- });
-
- // The ORM refuses a link whose conversation the member cannot edit, as it
- // would through the record API.
- it('writes the link as the member the chat turn runs for', async () => {
- const { service, workspaceOrmManager } = buildService();
-
- await service.attachThreadToRecord(args);
-
- expect(workspaceOrmManager.executeInWorkspaceContext).toHaveBeenCalledWith(
- expect.any(Function),
- MEMBER_AUTH_CONTEXT,
- );
- expect(
- workspaceOrmManager.getRepositoryWithContextPermissions,
- ).toHaveBeenCalledWith('agentChatThreadTarget');
- });
-
- it('reports the refusal of a conversation the member cannot edit', async () => {
- const { service, targetRepository } = buildService();
- const refusal = new PermissionsException(
- 'the "agentChatThread" record a "agentChatThreadTarget" is attached to is not writable',
- PermissionsExceptionCode.PERMISSION_DENIED,
- );
-
- targetRepository.insert.mockRejectedValueOnce(refusal);
-
- await expect(service.attachThreadToRecord(args)).rejects.toBe(refusal);
- });
-
- it('rejects an object name the workspace does not have', async () => {
- const { service, targetRepository } = buildService();
-
- await expect(
- service.attachThreadToRecord({ ...args, objectNameSingular: 'unicorn' }),
- ).rejects.toMatchObject({
- code: 'INVALID_AGENT_INPUT',
- message: 'Unknown object "unicorn"',
- });
-
- expect(targetRepository.insert).not.toHaveBeenCalled();
- });
-
- it('rejects an object the target has no leg for', async () => {
- const { service, targetRepository } = buildService();
-
- await expect(
- service.attachThreadToRecord({ ...args, objectNameSingular: 'task' }),
- ).rejects.toMatchObject({
- code: 'INVALID_AGENT_INPUT',
- message: 'Conversations cannot be attached to task records',
- });
-
- expect(targetRepository.insert).not.toHaveBeenCalled();
- });
-});
-
-describe('Finding the record a conversation is attached to', () => {
- it('reads the record as the member', async () => {
- const { service, recordRepository, workspaceOrmManager } = buildService();
-
- await service.attachThreadToRecord(args);
-
- expect(
- workspaceOrmManager.getRepositoryWithContextPermissions,
- ).toHaveBeenCalledWith('company');
- expect(recordRepository.findOne).toHaveBeenCalledWith({
- where: { id: RECORD_ID },
- select: { id: true },
- });
- });
-
- it('refuses a record that does not exist', async () => {
- const { service, targetRepository } = buildService();
-
- await expect(
- service.attachThreadToRecord({
- ...args,
- recordId: '20202020-0000-4000-8000-000000000009',
- }),
- ).rejects.toMatchObject({ code: 'RECORD_NOT_FOUND' });
-
- expect(targetRepository.insert).not.toHaveBeenCalled();
- });
-
- it('files nothing under a record in the trash', async () => {
- const { service, targetRepository } = buildService();
-
- await expect(
- service.attachThreadToRecord({ ...args, recordId: TRASHED_RECORD_ID }),
- ).rejects.toMatchObject({ code: 'RECORD_NOT_FOUND' });
-
- expect(targetRepository.insert).not.toHaveBeenCalled();
- });
-
- // Surfacing the denial would leak that the record exists.
- it('treats a record the member cannot read as one that does not exist', async () => {
- const { service, targetRepository } = buildService();
-
- await expect(
- service.attachThreadToRecord({ ...args, recordId: UNREADABLE_RECORD_ID }),
- ).rejects.toMatchObject({ code: 'RECORD_NOT_FOUND' });
-
- expect(targetRepository.insert).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-history-storage.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-history-storage.service.spec.ts
deleted file mode 100644
index c3d70b7fddb..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-history-storage.service.spec.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { type DataSource, type QueryRunner } from 'typeorm';
-import { ServiceUnavailableException } from '@nestjs/common';
-
-import { AgentHistoryStorageService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-storage.service';
-import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
-
-describe('AgentHistoryStorageService', () => {
- const workspaceId = '20202020-1111-4111-8111-111111111111';
- const runner = {
- hasSchema: jest.fn(),
- connect: jest.fn(),
- startTransaction: jest.fn(),
- commitTransaction: jest.fn(),
- rollbackTransaction: jest.fn(),
- release: jest.fn(),
- query: jest.fn(),
- manager: {},
- isTransactionActive: true,
- };
- const service = new AgentHistoryStorageService({
- createQueryRunner: () => runner,
- } as unknown as DataSource);
-
- beforeEach(() => {
- jest.clearAllMocks();
- runner.query.mockReset();
- });
-
- it('reads the authoritative route on every operation and keeps the fence through completion', async () => {
- runner.query.mockResolvedValueOnce([]).mockResolvedValueOnce([
- {
- workspaceId,
- type: 'CONFIG_VARIABLE',
- value: { storage: 'workspace' },
- },
- ]);
- await service.run(workspaceId, async ({ table }) => {
- expect(table('agentMessage')).toBe(
- `"${getWorkspaceSchemaName(workspaceId)}"."agentMessage"`,
- );
- expect(runner.commitTransaction).not.toHaveBeenCalled();
- });
- expect(runner.query.mock.calls[0][0]).toContain(
- 'pg_advisory_xact_lock_shared',
- );
- expect(runner.commitTransaction).toHaveBeenCalledTimes(1);
- expect(runner.release).toHaveBeenCalledTimes(1);
- });
-
- it('refuses history still stored in core', async () => {
- runner.query
- .mockResolvedValueOnce([])
- .mockResolvedValueOnce([
- { workspaceId, type: 'CONFIG_VARIABLE', value: { storage: 'core' } },
- ]);
- const operation = jest.fn();
- await expect(service.run(workspaceId, operation)).rejects.toBeInstanceOf(
- ServiceUnavailableException,
- );
- expect(operation).not.toHaveBeenCalled();
- expect(runner.rollbackTransaction).toHaveBeenCalledTimes(1);
- });
-
- it('does not fall back or execute writes while a migration is incomplete', async () => {
- runner.query.mockResolvedValueOnce([]).mockResolvedValueOnce([
- {
- workspaceId,
- type: 'CONFIG_VARIABLE',
- value: {
- storage: 'core',
- migration: {
- phase: 'copying',
- target: 'workspace',
- tableIndex: 2,
- lastId: null,
- },
- },
- },
- ]);
- const operation = jest.fn();
- await expect(service.run(workspaceId, operation)).rejects.toBeInstanceOf(
- ServiceUnavailableException,
- );
- expect(operation).not.toHaveBeenCalled();
- expect(runner.rollbackTransaction).toHaveBeenCalledTimes(1);
- expect(runner.release).toHaveBeenCalledTimes(1);
- });
-
- it('fails closed on a corrupt route', async () => {
- runner.query.mockResolvedValue([{ value: { storage: 'unknown' } }]);
- await expect(
- service.readState(runner as unknown as QueryRunner, workspaceId),
- ).rejects.toThrow('Invalid agent history storage state');
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-history-workspace-storage.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-history-workspace-storage.service.spec.ts
deleted file mode 100644
index fd1a6bdc136..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/__tests__/agent-history-workspace-storage.service.spec.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { type DataSource } from 'typeorm';
-
-import { AgentHistoryWorkspaceStorageService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';
-import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
-
-const WORKSPACE_ID = '20202020-1111-4111-8111-111111111111';
-
-describe('AgentHistoryWorkspaceStorageService', () => {
- const runner = {
- connect: jest.fn(),
- startTransaction: jest.fn(),
- commitTransaction: jest.fn(),
- rollbackTransaction: jest.fn(),
- release: jest.fn(),
- query: jest.fn(),
- manager: {},
- isTransactionActive: true,
- };
- const service = new AgentHistoryWorkspaceStorageService({
- createQueryRunner: () => runner,
- } as unknown as DataSource);
-
- beforeEach(() => {
- jest.clearAllMocks();
- runner.query.mockResolvedValue([{ ready: true }]);
- });
-
- it('uses workspace tables after checking upgrade readiness', async () => {
- const result = await service.run(WORKSPACE_ID, async ({ table }) => {
- expect(table('agentMessage')).toBe(
- `"${getWorkspaceSchemaName(WORKSPACE_ID)}"."agentMessage"`,
- );
- expect(runner.commitTransaction).not.toHaveBeenCalled();
- return 'saved';
- });
-
- expect(result).toBe('saved');
- expect(runner.query).toHaveBeenCalledTimes(2);
- expect(runner.commitTransaction).toHaveBeenCalledTimes(1);
- expect(runner.release).toHaveBeenCalledTimes(1);
- });
-
- it.each([
- ['shared', 'pg_advisory_xact_lock_shared'],
- ['exclusive', 'pg_advisory_xact_lock'],
- ] as const)(
- 'holds the %s workspace fence until the operation completes',
- async (lockMode, lockFunction) => {
- await service.run(
- WORKSPACE_ID,
- async () => {
- expect(runner.query).toHaveBeenNthCalledWith(
- 1,
- `SELECT ${lockFunction}(hashtextextended($1, 0))`,
- [`agent-history-storage-v1:${WORKSPACE_ID}`],
- );
- expect(runner.commitTransaction).not.toHaveBeenCalled();
- expect(runner.release).not.toHaveBeenCalled();
- },
- { lockMode },
- );
-
- expect(runner.commitTransaction).toHaveBeenCalledTimes(1);
- expect(runner.release).toHaveBeenCalledTimes(1);
- },
- );
-
- it.each([[], undefined])(
- 'rejects incomplete upgrades before running domain writes (%s)',
- async (ready) => {
- runner.query.mockResolvedValueOnce([]).mockResolvedValueOnce(ready ?? []);
- const work = jest.fn();
- await expect(service.run(WORKSPACE_ID, work)).rejects.toThrow(
- 'finishes upgrading',
- );
- expect(work).not.toHaveBeenCalled();
- expect(runner.rollbackTransaction).toHaveBeenCalled();
- },
- );
-
- it('rolls back domain writes on failure', async () => {
- await expect(
- service.run(WORKSPACE_ID, async () => {
- throw new Error('write failed');
- }),
- ).rejects.toThrow('write failed');
-
- expect(runner.rollbackTransaction).toHaveBeenCalledTimes(1);
- expect(runner.commitTransaction).not.toHaveBeenCalled();
- expect(runner.release).toHaveBeenCalledTimes(1);
- });
-
- it('rejects an empty workspace scope before opening a transaction', async () => {
- await expect(service.run('', jest.fn())).rejects.toMatchObject({
- code: 'INVALID_WORKSPACE',
- });
- expect(runner.connect).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/__tests__/ai-model-registry-evaluation.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/__tests__/ai-model-registry-evaluation.service.spec.ts
deleted file mode 100644
index 524a7a7149a..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/__tests__/ai-model-registry-evaluation.service.spec.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import { Test } from '@nestjs/testing';
-
-import { CustomAiProviderAccessService } from 'src/engine/core-modules/enterprise/services/custom-ai-provider-access.service';
-import { ConfigGroupHashService } from 'src/engine/core-modules/twenty-config/services/config-group-hash.service';
-import { AiModelPreferencesService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-preferences.service';
-import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
-import { ProviderConfigService } from 'src/engine/metadata-modules/ai/ai-models/services/provider-config.service';
-import { SdkProviderFactoryService } from 'src/engine/metadata-modules/ai/ai-models/services/sdk-provider-factory.service';
-
-// Covers the catalog-to-cache hop rather than the assertions built on it: a
-// capability that the catalog declares but registration drops is silently
-// inert, and every check reading it passes for the wrong reason.
-describe('AiModelRegistryService evaluation catalog', () => {
- let registry: AiModelRegistryService;
- const setModelAdminEnabledMock = jest.fn();
- let disabledModelIds: string[] = [];
-
- beforeEach(async () => {
- disabledModelIds = [];
-
- const module = await Test.createTestingModule({
- providers: [
- AiModelRegistryService,
- {
- provide: ProviderConfigService,
- useValue: {
- getResolvedProviders: () => ({
- 'typesafe-ai': {
- npm: '@ai-sdk/typesafe-ai',
- label: 'TypeSafe AI',
- apiKey: 'test-key',
- models: [
- {
- name: 'jev-latest',
- label: 'Jev',
- kind: 'evaluation',
- inputCostPerMillionTokens: 0.042,
- outputCostPerMillionTokens: 0,
- supportedQuestionTypes: ['choice', 'score', 'boolean'],
- maxCriteriaPerQuestion: 255,
- maxScoreLevels: 10,
- medianLatencyMs: 200,
- },
- ],
- },
- }),
- },
- },
- {
- provide: SdkProviderFactoryService,
- useValue: {
- clearCache: jest.fn(),
- createProvider: () => ({
- createEvaluationModel: () => ({
- specificationVersion: 'v4',
- provider: 'typesafe-ai',
- modelId: 'jev-latest',
- supportedQuestionTypes: ['choice', 'score', 'boolean'],
- doEvaluate: jest.fn(),
- }),
- }),
- },
- },
- {
- provide: AiModelPreferencesService,
- useValue: {
- getDisabledModelIds: () => disabledModelIds,
- getDefaultModelIdsForTier: () => [],
- setModelAdminEnabled: setModelAdminEnabledMock,
- },
- },
- {
- provide: ConfigGroupHashService,
- useValue: { computeHash: () => 'test' },
- },
- {
- provide: CustomAiProviderAccessService,
- useValue: { getCachedHasAccess: () => true },
- },
- ],
- }).compile();
-
- registry = module.get(AiModelRegistryService);
- });
-
- it('carries every declared capability into the evaluation config', () => {
- const modelConfig = registry.getEvaluationModelConfig(
- 'typesafe-ai/jev-latest',
- );
-
- expect(modelConfig).toMatchObject({
- modelId: 'typesafe-ai/jev-latest',
- supportedQuestionTypes: ['choice', 'score', 'boolean'],
- maxCriteriaPerQuestion: 255,
- maxScoreLevels: 10,
- medianLatencyMs: 200,
- });
- });
-
- it('keeps an evaluation model out of the language model registry', () => {
- expect(registry.getModel('typesafe-ai/jev-latest')).toBeUndefined();
- expect(registry.getModelConfig('typesafe-ai/jev-latest')).toBeUndefined();
- expect(
- registry
- .getAdminFilteredModels()
- .some(({ modelId }) => modelId.startsWith('typesafe-ai/')),
- ).toBe(false);
- });
-
- it('registers the model as runnable when the provider is configured', () => {
- expect(registry.getEvaluationModel('typesafe-ai/jev-latest')).toBeDefined();
- });
-
- it('carries the route identity so a caller need not split the id apart', () => {
- expect(
- registry.getEvaluationModelConfig('typesafe-ai/jev-latest'),
- ).toMatchObject({ providerName: 'typesafe-ai', name: 'jev-latest' });
- });
-
- // The admin panel lists every kind; an evaluation model absent from this is
- // a provider page with an empty table and no way to turn the model off.
- it('reports evaluation models to the admin panel with their status', () => {
- expect(registry.getAllEvaluationModelsWithStatus()).toEqual([
- expect.objectContaining({
- isAvailable: true,
- isAdminEnabled: true,
- modelConfig: expect.objectContaining({
- modelId: 'typesafe-ai/jev-latest',
- }),
- }),
- ]);
- });
-
- it('should let an administrator disable an evaluation model', async () => {
- await expect(
- registry.setModelAdminEnabled('typesafe-ai/jev-latest', false),
- ).resolves.not.toThrow();
-
- expect(setModelAdminEnabledMock).toHaveBeenCalledWith(
- 'typesafe-ai/jev-latest',
- false,
- );
- });
-
- // An administrator withdrawing the only evaluation model has to send
- // unpinned Classify steps to the language fallback, not keep running them on
- // the model that was withdrawn.
- it('should not offer an admin-disabled model as the instance default', () => {
- expect(registry.getDefaultEvaluationModel()?.modelId).toBe(
- 'typesafe-ai/jev-latest',
- );
-
- disabledModelIds = ['typesafe-ai/jev-latest'];
-
- expect(registry.getDefaultEvaluationModel()).toBeUndefined();
- expect(registry.hasEvaluationModel()).toBe(false);
- });
-
- it('should refuse to toggle a model no provider declares', async () => {
- await expect(
- registry.setModelAdminEnabled('typesafe-ai/nope', false),
- ).rejects.toThrow();
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/__tests__/default-ai-catalog.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/__tests__/default-ai-catalog.service.spec.ts
deleted file mode 100644
index c946938d476..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/__tests__/default-ai-catalog.service.spec.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { Readable } from 'stream';
-
-import { type ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
-import { type FileStorageDriverFactory } from 'src/engine/core-modules/file-storage/file-storage-driver.factory';
-import { type TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { DefaultAiCatalogService } from 'src/engine/metadata-modules/ai/ai-models/services/default-ai-catalog.service';
-
-const buildService = (storedCatalog?: string) => {
- const captureExceptions = jest.fn();
-
- const service = new DefaultAiCatalogService(
- {
- get: () =>
- storedCatalog === undefined ? undefined : 'config/ai-catalog.json',
- } as unknown as TwentyConfigService,
- {
- getCurrentDriver: () => ({
- readFile: async () => Readable.from([Buffer.from(storedCatalog ?? '')]),
- }),
- } as unknown as FileStorageDriverFactory,
- { captureExceptions } as unknown as ExceptionHandlerService,
- );
-
- return { service, captureExceptions };
-};
-
-const readableProvider = {
- npm: '@ai-sdk/openai',
- apiKey: '{{OPENAI_API_KEY}}',
- models: [{ name: 'gpt-5.6-luna', label: 'GPT-5.6 Luna' }],
-};
-
-describe('DefaultAiCatalogService', () => {
- it('keeps the providers it can read when the stored catalog names one it cannot', async () => {
- const { service, captureExceptions } = buildService(
- JSON.stringify({
- openai: readableProvider,
- 'future-provider': {
- npm: '@ai-sdk/future-provider',
- models: [
- { name: 'future-model', label: 'Future', kind: 'future-kind' },
- ],
- },
- }),
- );
-
- await service.onModuleInit();
-
- const catalog = service.getDefaultAiCatalog();
-
- expect(Object.keys(catalog)).toEqual(['openai']);
- expect(catalog.openai.models?.map((model) => model.name)).toEqual([
- 'gpt-5.6-luna',
- ]);
- expect(captureExceptions).toHaveBeenCalledTimes(1);
- expect(captureExceptions.mock.calls[0][0][0].message).toContain(
- 'future-provider',
- );
- });
-
- it('serves nothing and reports when the stored catalog cannot be parsed', async () => {
- const { service, captureExceptions } = buildService('{ not json');
-
- await service.onModuleInit();
-
- expect(service.getDefaultAiCatalog()).toEqual({});
- expect(captureExceptions).toHaveBeenCalledTimes(1);
- });
-
- it('uses the built-in catalog when no stored catalog is configured', async () => {
- const { service, captureExceptions } = buildService();
-
- await service.onModuleInit();
-
- expect(Object.keys(service.getDefaultAiCatalog()).length).toBeGreaterThan(
- 0,
- );
- expect(captureExceptions).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.spec.ts
deleted file mode 100644
index 7ad02150215..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.spec.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { Test } from '@nestjs/testing';
-
-import { CustomAiProviderAccessService } from 'src/engine/core-modules/enterprise/services/custom-ai-provider-access.service';
-import { ConfigGroupHashService } from 'src/engine/core-modules/twenty-config/services/config-group-hash.service';
-import { AiModelPreferencesService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-preferences.service';
-import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
-import { ProviderConfigService } from 'src/engine/metadata-modules/ai/ai-models/services/provider-config.service';
-import { SdkProviderFactoryService } from 'src/engine/metadata-modules/ai/ai-models/services/sdk-provider-factory.service';
-
-describe('AiModelRegistryService effort catalog', () => {
- let registry: AiModelRegistryService;
- const getDisabledModelIds = jest.fn((): string[] => []);
-
- beforeEach(async () => {
- getDisabledModelIds.mockReturnValue([]);
- const module = await Test.createTestingModule({
- providers: [
- AiModelRegistryService,
- {
- provide: ProviderConfigService,
- useValue: {
- getResolvedProviders: () => ({
- openai: {
- npm: '@ai-sdk/openai',
- apiKey: 'test-key',
- models: ['sol', 'astra'].map((name) => ({
- name,
- label: name,
- efforts: ['medium', 'high'],
- benchmarkByEffort: {
- medium: { intelligenceIndex: 42 },
- },
- })),
- },
- }),
- },
- },
- {
- provide: SdkProviderFactoryService,
- useValue: {
- clearCache: jest.fn(),
- createProvider: () => ({ createModel: () => ({}) }),
- },
- },
- {
- provide: AiModelPreferencesService,
- useValue: {
- getDisabledModelIds,
- getDefaultModelIdsForTier: () => ['openai/sol@high'],
- },
- },
- {
- provide: ConfigGroupHashService,
- useValue: { computeHash: () => 'test' },
- },
- {
- provide: CustomAiProviderAccessService,
- useValue: { getCachedHasAccess: () => true },
- },
- ],
- }).compile();
-
- registry = module.get(AiModelRegistryService);
- });
-
- it('lists every selectable effort before any variant is requested', () => {
- expect(
- registry.getAdminFilteredModels().map(({ modelId }) => modelId),
- ).toEqual(
- expect.arrayContaining([
- 'openai/sol@medium',
- 'openai/sol@high',
- 'openai/astra@medium',
- 'openai/astra@high',
- ]),
- );
- expect(registry.getModelConfig('openai/astra@medium')?.benchmark).toEqual({
- intelligenceIndex: 42,
- });
- expect(registry.getModel('openai/astra@low')).toBeUndefined();
- });
-
- it('excludes all efforts of an admin-disabled model', () => {
- getDisabledModelIds.mockReturnValue(['openai/astra']);
-
- expect(
- registry
- .getAdminFilteredModels()
- .some(({ modelId }) => modelId.startsWith('openai/astra')),
- ).toBe(false);
- });
-
- it('exposes only base models in provider management after resolving variants', () => {
- registry.getModelConfig('openai/astra@medium');
-
- expect(
- registry.getAllModelsWithStatus().map(({ modelConfig, name }) => ({
- modelId: modelConfig.modelId,
- name,
- })),
- ).toEqual([
- { modelId: 'openai/sol', name: 'sol' },
- { modelId: 'openai/astra', name: 'astra' },
- ]);
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer.service.spec.ts
deleted file mode 100644
index 698882b3d88..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer.service.spec.ts
+++ /dev/null
@@ -1,966 +0,0 @@
-import { withWorkspaceAuthContext } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
-import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
-import { AgentChatTurnPreflightService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service';
-import { ToolCallAnswerService } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service';
-
-const QUESTIONS = [
- {
- header: 'Plan',
- question: 'Which plan?',
- options: [{ label: 'Pro' }, { label: 'Team' }],
- },
-];
-
-const ANSWERS = [{ questionIndex: 0, selectedOptionIndices: [1] }];
-
-const PROPOSED_EMAIL = {
- recipients: { to: '[email protected]', cc: '', bcc: '' },
- subject: 'Renewal',
- body: 'Hi Tim,\n\nYour plan renews next week.',
-};
-
-const FORM_FIELDS = [
- { id: 'field-id', name: 'discount', label: 'Discount', type: 'TEXT' },
-];
-
-const questionPart = {
- id: 'part-id',
- messageId: 'question-message-id',
- turnId: 'question-turn-id',
- toolName: 'ask_questions',
- toolInput: { questions: QUESTIONS },
- toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },
-};
-
-const waitingThread = {
- id: 'thread-id',
- workflowRunId: null as string | null,
- activeStreamId: null,
- pendingQuestionMessageId: 'question-message-id',
-};
-
-type BuildOptions = {
- thread?: typeof waitingThread | null;
- toolPart?: Record<string, unknown> | null;
- hasClaimedStream?: boolean;
- isStillAwaiting?: boolean;
- hasOtherAwaitingCalls?: boolean;
- hasPermission?: boolean;
-};
-
-describe('ToolCallAnswerService', () => {
- const workspace = { id: 'workspace-id' } as WorkspaceEntity;
-
- const answerArguments = {
- threadId: 'thread-id',
- toolCallId: 'tool-call-id',
- response: { answers: ANSWERS } as Record<string, unknown>,
- userWorkspaceId: 'user-workspace-id',
- workspaceMemberId: 'member-id',
- workspace,
- };
-
- const buildService = ({
- thread = waitingThread,
- toolPart = questionPart,
- hasClaimedStream = true,
- isStillAwaiting = true,
- hasOtherAwaitingCalls = false,
- hasPermission = true,
- }: BuildOptions = {}) => {
- const publishedEvents: Array<{ type: string }> = [];
- const threadRepository = {
- findOne: jest.fn().mockResolvedValue(thread),
- };
- const agentChatService = {
- findToolPart: jest.fn().mockResolvedValue(toolPart),
- findAwaitingToolParts: jest
- .fn()
- .mockResolvedValue([
- ...(isStillAwaiting ? [toolPart] : []),
- ...(hasOtherAwaitingCalls ? [{ id: 'other-part-id' }] : []),
- ]),
- getWritableThread: jest.fn().mockResolvedValue(thread),
- recordToolCallAnswer: jest.fn().mockResolvedValue(undefined),
- addMessage: jest
- .fn()
- .mockResolvedValue({ id: 'answer-message-id', turnId: 'answer-turn' }),
- closePendingToolCalls: jest.fn().mockResolvedValue(undefined),
- };
- const agentChatStreamingService = {
- reapDeadStream: jest.fn().mockResolvedValue(null),
- tryClaimStream: jest.fn().mockResolvedValue(hasClaimedStream),
- releaseStreamClaim: jest.fn().mockResolvedValue(undefined),
- enqueueResumeStream: jest.fn().mockResolvedValue(undefined),
- };
- const actorService = {
- authorizeToolCallResolution: jest.fn().mockResolvedValue(undefined),
- };
- const eventPublisherService = {
- publish: jest.fn().mockImplementation(({ event }) => {
- publishedEvents.push(event);
-
- return Promise.resolve();
- }),
- };
- const workflowRunnerWorkspaceService = {
- resumeAnsweredStep: jest.fn().mockResolvedValue(undefined),
- completeFormStep: jest.fn().mockResolvedValue(true),
- resume: jest.fn().mockResolvedValue(undefined),
- };
- const step = { id: 'step-id', type: 'AI_AGENT' };
- const workflowRunWorkspaceService = {
- findStepAwaitingAnswer: jest.fn().mockResolvedValue(step),
- endWorkflowRun: jest.fn().mockResolvedValue(undefined),
- getWorkflowRun: jest.fn().mockResolvedValue({
- state: { stepInfos: { 'step-id': { threadId: 'thread-id' } } },
- }),
- };
- const permissionsService = {
- userHasWorkspaceSettingPermission: jest
- .fn()
- .mockResolvedValue(hasPermission),
- };
- const aiModelRegistryService = {
- getAvailableModels: jest.fn().mockReturnValue([{ modelId: 'model' }]),
- validateModelAvailability: jest.fn(),
- };
- const aiBillingService = {
- assertAiExecutionAllowed: jest.fn().mockResolvedValue(undefined),
- };
- const workflowRunRepository = {
- findOne: jest.fn().mockResolvedValue({ id: 'workflow-run-id' }),
- };
- const workspaceOrmManager = {
- executeInWorkspaceContext: jest.fn().mockImplementation((work) => work()),
- getRepositoryWithContextPermissions: jest
- .fn()
- .mockReturnValue(workflowRunRepository),
- };
- const toolRegistryService = {
- resolveAndExecute: jest.fn().mockResolvedValue({
- success: true,
- message: 'Email sent successfully to [email protected]',
- result: { messageId: 'sent-message-id' },
- }),
- };
-
- const agentHistoryWorkspaceStorageService = {
- run: jest.fn().mockImplementation((_workspaceId, work) => work()),
- };
-
- const service = new ToolCallAnswerService(
- threadRepository as never,
- agentChatService as never,
- agentChatStreamingService as never,
- actorService as never,
- eventPublisherService as never,
- workflowRunnerWorkspaceService as never,
- workflowRunWorkspaceService as never,
- permissionsService as never,
- new AgentChatTurnPreflightService(
- aiModelRegistryService as never,
- agentChatService as never,
- aiBillingService as never,
- ),
- workspaceOrmManager as never,
- {
- getOrRecompute: jest.fn().mockResolvedValue({
- userWorkspaceRoleMap: { 'user-workspace-id': 'role-id' },
- }),
- } as never,
- {
- buildUserAndAgentActorContext: jest.fn().mockResolvedValue({
- actorContext: {},
- roleId: 'role-id',
- userId: 'user-id',
- userContext: { locale: 'en' },
- }),
- } as never,
- toolRegistryService as never,
- agentHistoryWorkspaceStorageService as never,
- );
-
- return {
- service,
- agentHistoryWorkspaceStorageService,
- step,
- agentChatService,
- agentChatStreamingService,
- workflowRunnerWorkspaceService,
- workflowRunWorkspaceService,
- permissionsService,
- workflowRunRepository,
- toolRegistryService,
- publishedEvents,
- };
- };
-
- it('treats a tool call it cannot find as not found', async () => {
- const { service } = buildService({ toolPart: null });
-
- await expect(service.answer(answerArguments)).rejects.toMatchObject({
- code: 'TOOL_CALL_NOT_FOUND',
- });
- });
-
- it('refuses a call the conversation no longer waits on, before touching anything', async () => {
- const { service, agentChatStreamingService, agentChatService } =
- buildService({
- thread: { ...waitingThread, pendingQuestionMessageId: 'later-id' },
- });
-
- await expect(service.answer(answerArguments)).rejects.toMatchObject({
- code: 'TOOL_CALL_NOT_PENDING',
- });
- expect(agentChatStreamingService.tryClaimStream).not.toHaveBeenCalled();
- expect(agentChatService.addMessage).not.toHaveBeenCalled();
- });
-
- describe('a chat tool call', () => {
- it('records the answer, stops waiting and resumes the stream, claimed only while the conversation waits on the call', async () => {
- const {
- service,
- agentChatService,
- agentChatStreamingService,
- publishedEvents,
- } = buildService();
-
- const result = await service.answer(answerArguments);
-
- expect(result).toEqual({
- streamId: expect.any(String),
- turnId: 'answer-turn',
- });
- expect(agentChatStreamingService.tryClaimStream).toHaveBeenCalledWith({
- threadId: 'thread-id',
- workspaceId: 'workspace-id',
- streamId: result.streamId,
- where: { pendingQuestionMessageId: 'question-message-id' },
- });
- expect(agentChatService.recordToolCallAnswer).toHaveBeenCalledWith({
- threadId: 'thread-id',
- messageId: 'question-message-id',
- partId: 'part-id',
- isLastAnswer: true,
- workspaceId: 'workspace-id',
- toolOutput: expect.objectContaining({
- result: {
- questions: QUESTIONS,
- status: 'answered',
- answers: ANSWERS,
- },
- }),
- });
- expect(agentChatService.addMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- userWorkspaceId: 'user-workspace-id',
- uiMessage: {
- role: 'user',
- parts: [{ type: 'text', text: 'Which plan?\nTeam' }],
- },
- }),
- );
- expect(
- agentChatStreamingService.enqueueResumeStream,
- ).toHaveBeenCalledWith(
- expect.objectContaining({
- streamId: result.streamId,
- messageId: 'answer-message-id',
- turnId: 'answer-turn',
- }),
- );
- expect(publishedEvents).toContainEqual({
- type: 'tool-call-resolved',
- toolCallId: 'tool-call-id',
- });
- });
-
- it('records the answer but leaves the agent paused while another call of the step waits', async () => {
- const { service, agentChatService, agentChatStreamingService } =
- buildService({ hasOtherAwaitingCalls: true });
-
- expect(await service.answer(answerArguments)).toEqual({
- streamId: null,
- turnId: 'answer-turn',
- });
- expect(agentChatService.recordToolCallAnswer).toHaveBeenCalledWith(
- expect.objectContaining({ isLastAnswer: false }),
- );
- expect(
- agentChatStreamingService.enqueueResumeStream,
- ).not.toHaveBeenCalled();
- expect(agentChatStreamingService.releaseStreamClaim).toHaveBeenCalledWith(
- 'thread-id',
- 'workspace-id',
- expect.any(String),
- );
- });
-
- it.each([
- { answers: [] },
- {
- answers: [
- { questionIndex: 0, selectedOptionIndices: [], freeText: ' ' },
- ],
- },
- { answers: [{ questionIndex: 3, selectedOptionIndices: [0] }] },
- { answers: [{ questionIndex: 0, selectedOptionIndices: [0, 1] }] },
- ])('rejects a response the call cannot accept (%j)', async (response) => {
- const { service, agentChatStreamingService } = buildService();
-
- await expect(
- service.answer({ ...answerArguments, response }),
- ).rejects.toMatchObject({ code: 'INVALID_TOOL_CALL_OUTPUT' });
- expect(agentChatStreamingService.tryClaimStream).not.toHaveBeenCalled();
- });
-
- it('refuses someone without the AI permission', async () => {
- const { service, agentChatStreamingService } = buildService({
- hasPermission: false,
- });
-
- await expect(service.answer(answerArguments)).rejects.toMatchObject({
- code: 'TOOL_CALL_RESOLUTION_FORBIDDEN',
- });
- expect(agentChatStreamingService.tryClaimStream).not.toHaveBeenCalled();
- });
-
- it('refuses while another answer or response holds the conversation, recording nothing', async () => {
- const { service, agentChatService } = buildService({
- hasClaimedStream: false,
- });
-
- await expect(service.answer(answerArguments)).rejects.toMatchObject({
- code: 'TOOL_CALL_NOT_PENDING',
- });
- expect(agentChatService.recordToolCallAnswer).not.toHaveBeenCalled();
- });
-
- it('releases the conversation it claimed when an earlier answer already closed the call', async () => {
- const { service, agentChatStreamingService, agentChatService } =
- buildService({ isStillAwaiting: false });
-
- await expect(service.answer(answerArguments)).rejects.toMatchObject({
- code: 'TOOL_CALL_NOT_PENDING',
- });
-
- const [[{ streamId: claimedStreamId }]] =
- agentChatStreamingService.tryClaimStream.mock.calls;
-
- expect(agentChatStreamingService.releaseStreamClaim).toHaveBeenCalledWith(
- 'thread-id',
- 'workspace-id',
- claimedStreamId,
- );
- expect(agentChatService.recordToolCallAnswer).not.toHaveBeenCalled();
- expect(agentChatService.addMessage).not.toHaveBeenCalled();
- });
-
- it('leaves a retryable failed turn when the resume cannot be scheduled', async () => {
- const { service, agentChatStreamingService, publishedEvents } =
- buildService();
-
- agentChatStreamingService.enqueueResumeStream.mockRejectedValue(
- new Error('redis down'),
- );
-
- await expect(service.answer(answerArguments)).rejects.toThrow(
- 'redis down',
- );
- expect(agentChatStreamingService.releaseStreamClaim).toHaveBeenCalledWith(
- 'thread-id',
- 'workspace-id',
- expect.any(String),
- {
- lastStreamError: expect.objectContaining({
- message: 'redis down',
- failedAt: expect.any(String),
- }),
- },
- );
- expect(publishedEvents.map((event) => event.type)).toContain(
- 'stream-error',
- );
- });
- });
-
- describe('an email approval', () => {
- const emailPart = {
- ...questionPart,
- toolName: 'propose_email',
- toolInput: PROPOSED_EMAIL,
- toolOutput: { result: { status: 'pending', email: PROPOSED_EMAIL } },
- };
-
- it('sends the edited email as the person, only once the conversation is claimed', async () => {
- const {
- service,
- toolRegistryService,
- agentChatStreamingService,
- agentChatService,
- } = buildService({ toolPart: emailPart });
- const editedEmail = { ...PROPOSED_EMAIL, subject: 'Your renewal' };
-
- // The email goes out as whoever answered, from their request.
- await withWorkspaceAuthContext(
- {
- type: 'user',
- workspace: { id: 'workspace-id' },
- userWorkspaceId: 'user-workspace-id',
- } as never,
- () =>
- service.answer({
- ...answerArguments,
- response: { decision: 'send', email: editedEmail },
- }),
- );
-
- expect(toolRegistryService.resolveAndExecute).toHaveBeenCalledWith(
- 'send_email',
- {
- recipients: PROPOSED_EMAIL.recipients,
- subject: 'Your renewal',
- body: '<p>Hi Tim,</p><p>Your plan renews next week.</p>',
- },
- expect.objectContaining({
- userWorkspaceId: 'user-workspace-id',
- roleId: 'role-id',
- }),
- );
- expect(
- agentChatStreamingService.tryClaimStream.mock.invocationCallOrder[0],
- ).toBeLessThan(
- toolRegistryService.resolveAndExecute.mock.invocationCallOrder[0],
- );
- expect(agentChatService.recordToolCallAnswer).toHaveBeenCalledWith(
- expect.objectContaining({
- toolOutput: expect.objectContaining({
- success: true,
- result: expect.objectContaining({
- status: 'sent',
- email: editedEmail,
- }),
- }),
- }),
- );
- });
-
- it('sends nothing when the person discards the email', async () => {
- const { service, toolRegistryService, agentChatService } = buildService({
- toolPart: emailPart,
- });
-
- await service.answer({
- ...answerArguments,
- response: { decision: 'discard' },
- });
-
- expect(toolRegistryService.resolveAndExecute).not.toHaveBeenCalled();
- expect(agentChatService.recordToolCallAnswer).toHaveBeenCalledWith(
- expect.objectContaining({
- toolOutput: expect.objectContaining({
- result: expect.objectContaining({ status: 'discarded' }),
- }),
- }),
- );
- });
-
- it('sends nothing when an earlier answer already closed the call', async () => {
- const { service, toolRegistryService } = buildService({
- toolPart: emailPart,
- isStillAwaiting: false,
- });
-
- await expect(
- service.answer({
- ...answerArguments,
- response: { decision: 'send', email: PROPOSED_EMAIL },
- }),
- ).rejects.toMatchObject({ code: 'TOOL_CALL_NOT_PENDING' });
- expect(toolRegistryService.resolveAndExecute).not.toHaveBeenCalled();
- });
- });
-
- describe('a call in a workflow run', () => {
- const runThread = { ...waitingThread, workflowRunId: 'workflow-run-id' };
-
- it('records the answer and hands it to the run, with no chat stream', async () => {
- const {
- service,
- step,
- agentChatService,
- agentChatStreamingService,
- workflowRunnerWorkspaceService,
- workflowRunWorkspaceService,
- permissionsService,
- } = buildService({ thread: runThread });
-
- expect(await service.answer(answerArguments)).toEqual({
- streamId: null,
- turnId: 'answer-turn',
- });
- expect(
- permissionsService.userHasWorkspaceSettingPermission,
- ).toHaveBeenCalledWith(expect.objectContaining({ setting: 'WORKFLOWS' }));
- expect(agentChatService.getWritableThread).not.toHaveBeenCalled();
- expect(agentChatService.recordToolCallAnswer).toHaveBeenCalledWith(
- expect.objectContaining({ isLastAnswer: true }),
- );
- expect(agentChatStreamingService.releaseStreamClaim).toHaveBeenCalled();
- expect(
- workflowRunnerWorkspaceService.resumeAnsweredStep,
- ).toHaveBeenCalledWith({
- workspaceId: 'workspace-id',
- workflowRunId: 'workflow-run-id',
- step,
- threadId: 'thread-id',
- response: { answers: ANSWERS },
- });
- expect(workflowRunWorkspaceService.endWorkflowRun).not.toHaveBeenCalled();
- });
-
- it('resumes nothing while another call of the step waits', async () => {
- const { service, workflowRunnerWorkspaceService } = buildService({
- thread: runThread,
- hasOtherAwaitingCalls: true,
- });
-
- await service.answer(answerArguments);
-
- expect(
- workflowRunnerWorkspaceService.resumeAnsweredStep,
- ).not.toHaveBeenCalled();
- });
-
- it('refuses an answer the run no longer waits for, closing its calls instead', async () => {
- const {
- service,
- agentChatService,
- agentChatStreamingService,
- workflowRunWorkspaceService,
- } = buildService({ thread: runThread });
-
- workflowRunWorkspaceService.findStepAwaitingAnswer.mockResolvedValue(
- null,
- );
-
- await expect(service.answer(answerArguments)).rejects.toMatchObject({
- code: 'TOOL_CALL_NOT_PENDING',
- });
- expect(agentChatService.recordToolCallAnswer).not.toHaveBeenCalled();
- expect(agentChatService.closePendingToolCalls).toHaveBeenCalledWith({
- threadId: 'thread-id',
- messageId: 'question-message-id',
- workspaceId: 'workspace-id',
- });
- expect(agentChatStreamingService.releaseStreamClaim).toHaveBeenCalled();
- });
-
- it('fails the run when the answer is recorded but its message cannot be added', async () => {
- const {
- service,
- agentChatService,
- workflowRunnerWorkspaceService,
- workflowRunWorkspaceService,
- } = buildService({ thread: runThread });
-
- agentChatService.addMessage.mockRejectedValue(new Error('Write failed'));
-
- await expect(service.answer(answerArguments)).rejects.toThrow(
- 'Write failed',
- );
- expect(
- workflowRunnerWorkspaceService.resumeAnsweredStep,
- ).not.toHaveBeenCalled();
- expect(workflowRunWorkspaceService.endWorkflowRun).toHaveBeenCalledWith(
- expect.objectContaining({ status: 'FAILED' }),
- );
- });
-
- it('fails the run when the answered step cannot resume', async () => {
- const {
- service,
- workflowRunnerWorkspaceService,
- workflowRunWorkspaceService,
- } = buildService({ thread: runThread });
-
- workflowRunnerWorkspaceService.resumeAnsweredStep.mockRejectedValue(
- new Error('Queue unavailable'),
- );
-
- await expect(service.answer(answerArguments)).rejects.toThrow(
- 'Queue unavailable',
- );
- expect(workflowRunWorkspaceService.endWorkflowRun).toHaveBeenCalledWith(
- expect.objectContaining({
- workflowRunId: 'workflow-run-id',
- workspaceId: 'workspace-id',
- status: 'FAILED',
- }),
- );
- });
-
- it('treats a run the caller cannot read as not found', async () => {
- const { service, workflowRunRepository, agentChatStreamingService } =
- buildService({ thread: runThread });
-
- workflowRunRepository.findOne.mockResolvedValue(null);
-
- await expect(service.answer(answerArguments)).rejects.toMatchObject({
- code: 'TOOL_CALL_NOT_FOUND',
- });
- expect(agentChatStreamingService.tryClaimStream).not.toHaveBeenCalled();
- });
-
- describe('issued by a form step', () => {
- const formPart = {
- ...questionPart,
- toolName: 'request_form',
- toolInput: { fields: FORM_FIELDS },
- toolOutput: { result: { status: 'pending' } },
- };
-
- it('hands the values to the run', async () => {
- const { service, workflowRunnerWorkspaceService } = buildService({
- thread: runThread,
- toolPart: formPart,
- });
-
- await service.answer({
- ...answerArguments,
- toolCallId: 'step-id',
- response: { discount: '20%' },
- });
-
- expect(
- workflowRunnerWorkspaceService.resumeAnsweredStep,
- ).toHaveBeenCalledWith(
- expect.objectContaining({ response: { discount: '20%' } }),
- );
- });
-
- it('rejects a value for a field the form does not have', async () => {
- const { service, agentChatStreamingService } = buildService({
- thread: runThread,
- toolPart: formPart,
- });
-
- await expect(
- service.answer({ ...answerArguments, response: { price: 10 } }),
- ).rejects.toMatchObject({ code: 'INVALID_TOOL_CALL_OUTPUT' });
- expect(agentChatStreamingService.tryClaimStream).not.toHaveBeenCalled();
- });
-
- it('refuses someone without the Workflows permission', async () => {
- const { service, workflowRunnerWorkspaceService } = buildService({
- thread: runThread,
- toolPart: formPart,
- hasPermission: false,
- });
-
- await expect(
- service.answer({ ...answerArguments, response: { discount: '20%' } }),
- ).rejects.toMatchObject({ code: 'TOOL_CALL_RESOLUTION_FORBIDDEN' });
- expect(
- workflowRunnerWorkspaceService.resumeAnsweredStep,
- ).not.toHaveBeenCalled();
- });
- });
- });
-
- describe('form submissions without a conversation', () => {
- const formArguments = {
- workflowRunId: 'workflow-run-id',
- stepId: 'step-id',
- response: { discount: '20%' },
- userWorkspaceId: 'user-workspace-id',
- workspaceMemberId: 'member-id',
- workspace,
- };
- const formStep = {
- id: 'step-id',
- type: 'FORM',
- settings: { input: FORM_FIELDS },
- };
- const pendingRun = {
- status: 'RUNNING',
- state: {
- stepInfos: { 'step-id': { status: 'PENDING' } },
- flow: { steps: [formStep] },
- },
- };
- const buildFormService = (options: BuildOptions = {}) => {
- const result = buildService(options);
- result.workflowRunWorkspaceService.getWorkflowRun.mockResolvedValue(
- pendingRun,
- );
- return result;
- };
-
- it('validates and resumes a form that has no conversation yet', async () => {
- const { service, workflowRunnerWorkspaceService, agentChatService } =
- buildFormService();
-
- await service.answerFormStep(formArguments);
-
- expect(
- workflowRunnerWorkspaceService.completeFormStep,
- ).toHaveBeenCalledWith({
- workspaceId: workspace.id,
- workflowRunId: formArguments.workflowRunId,
- step: formStep,
- expectedThreadId: null,
- response: formArguments.response,
- });
- expect(agentChatService.findToolPart).not.toHaveBeenCalled();
- expect(workflowRunnerWorkspaceService.resume).toHaveBeenCalledWith({
- workspaceId: workspace.id,
- workflowRunId: formArguments.workflowRunId,
- lastExecutedStepId: formArguments.stepId,
- });
- });
-
- it('fails the run after releasing the history fence if its accepted answer cannot be resumed', async () => {
- const {
- service,
- workflowRunnerWorkspaceService,
- workflowRunWorkspaceService,
- agentHistoryWorkspaceStorageService,
- } = buildFormService();
- const queueError = new Error('Queue unavailable');
- let isHistoryFenceHeld = false;
-
- agentHistoryWorkspaceStorageService.run.mockImplementation(
- async (_workspaceId, work) => {
- isHistoryFenceHeld = true;
-
- try {
- return await work();
- } finally {
- isHistoryFenceHeld = false;
- }
- },
- );
- workflowRunnerWorkspaceService.completeFormStep.mockImplementation(
- async () => {
- expect(isHistoryFenceHeld).toBe(true);
-
- return true;
- },
- );
- workflowRunnerWorkspaceService.resume.mockImplementation(async () => {
- expect(isHistoryFenceHeld).toBe(false);
-
- throw queueError;
- });
- workflowRunWorkspaceService.endWorkflowRun.mockImplementation(
- async () => {
- expect(isHistoryFenceHeld).toBe(false);
- },
- );
-
- await expect(service.answerFormStep(formArguments)).rejects.toBe(
- queueError,
- );
- expect(workflowRunWorkspaceService.endWorkflowRun).toHaveBeenCalledWith({
- workspaceId: workspace.id,
- workflowRunId: formArguments.workflowRunId,
- status: 'FAILED',
- error: 'The run could not resume after its form was answered',
- });
- });
-
- it('uses the conversation if the backfill finished before the submission acquired its lock', async () => {
- const {
- service,
- workflowRunWorkspaceService,
- workflowRunnerWorkspaceService,
- agentHistoryWorkspaceStorageService,
- } = buildFormService();
- workflowRunWorkspaceService.getWorkflowRun
- .mockResolvedValueOnce(pendingRun)
- .mockResolvedValueOnce({
- ...pendingRun,
- state: {
- ...pendingRun.state,
- stepInfos: {
- 'step-id': { status: 'PENDING', threadId: 'backfilled-thread' },
- },
- },
- });
- const answer = jest
- .spyOn(service, 'answer')
- .mockResolvedValue({ streamId: null, turnId: null });
-
- await service.answerFormStep(formArguments);
-
- expect(agentHistoryWorkspaceStorageService.run).toHaveBeenCalledWith(
- workspace.id,
- expect.any(Function),
- { lockMode: 'exclusive' },
- );
- expect(answer).toHaveBeenCalledWith(
- expect.objectContaining({
- threadId: 'backfilled-thread',
- toolCallId: 'step-id',
- }),
- );
- expect(
- workflowRunnerWorkspaceService.completeFormStep,
- ).not.toHaveBeenCalled();
- expect(workflowRunnerWorkspaceService.resume).not.toHaveBeenCalled();
- });
-
- it('requires workflow permission before reading or answering the run', async () => {
- const {
- service,
- workflowRunWorkspaceService,
- workflowRunnerWorkspaceService,
- } = buildFormService({ hasPermission: false });
-
- await expect(service.answerFormStep(formArguments)).rejects.toMatchObject(
- { code: 'TOOL_CALL_RESOLUTION_FORBIDDEN' },
- );
- expect(workflowRunWorkspaceService.getWorkflowRun).not.toHaveBeenCalled();
- expect(
- workflowRunnerWorkspaceService.completeFormStep,
- ).not.toHaveBeenCalled();
- });
-
- it('requires access to the specific run', async () => {
- const { service, workflowRunRepository, workflowRunnerWorkspaceService } =
- buildFormService();
- workflowRunRepository.findOne.mockResolvedValue(null);
-
- await expect(service.answerFormStep(formArguments)).rejects.toMatchObject(
- { code: 'TOOL_CALL_NOT_FOUND' },
- );
- expect(
- workflowRunnerWorkspaceService.completeFormStep,
- ).not.toHaveBeenCalled();
- });
-
- it.each([
- { ...pendingRun, status: 'STOPPED' },
- {
- ...pendingRun,
- state: {
- ...pendingRun.state,
- stepInfos: { 'step-id': { status: 'SUCCESS' } },
- },
- },
- {
- ...pendingRun,
- state: {
- ...pendingRun.state,
- stepInfos: { 'step-id': { status: 'PENDING', error: 'failed' } },
- },
- },
- {
- ...pendingRun,
- state: {
- ...pendingRun.state,
- flow: { steps: [{ ...formStep, type: 'AI_AGENT' }] },
- },
- },
- { ...pendingRun, state: { ...pendingRun.state, flow: { steps: [] } } },
- ])('rejects a run without an answerable form: %j', async (run) => {
- const {
- service,
- workflowRunWorkspaceService,
- workflowRunnerWorkspaceService,
- } = buildFormService();
- workflowRunWorkspaceService.getWorkflowRun.mockResolvedValue(run);
-
- await expect(service.answerFormStep(formArguments)).rejects.toMatchObject(
- { code: 'TOOL_CALL_NOT_PENDING' },
- );
- expect(
- workflowRunnerWorkspaceService.completeFormStep,
- ).not.toHaveBeenCalled();
- });
-
- it('validates answers with the same schema as conversation forms', async () => {
- const { service, workflowRunnerWorkspaceService } = buildFormService();
-
- await expect(
- service.answerFormStep({
- ...formArguments,
- response: { unknownField: 'value' },
- }),
- ).rejects.toMatchObject({ code: 'INVALID_TOOL_CALL_OUTPUT' });
- expect(
- workflowRunnerWorkspaceService.completeFormStep,
- ).not.toHaveBeenCalled();
- });
-
- it('rejects an answer when another submission or a conversation claimed the step', async () => {
- const {
- service,
- workflowRunnerWorkspaceService,
- workflowRunWorkspaceService,
- } = buildFormService();
- workflowRunnerWorkspaceService.completeFormStep.mockResolvedValue(false);
-
- await expect(service.answerFormStep(formArguments)).rejects.toMatchObject(
- { code: 'TOOL_CALL_NOT_PENDING' },
- );
- expect(workflowRunnerWorkspaceService.resume).not.toHaveBeenCalled();
- expect(workflowRunWorkspaceService.endWorkflowRun).not.toHaveBeenCalled();
- });
- });
-
- describe('the deprecated entry points', () => {
- it('answers a form step through the call named after it in its conversation', async () => {
- const { service, agentChatService } = buildService({
- thread: { ...waitingThread, workflowRunId: 'workflow-run-id' },
- toolPart: {
- ...questionPart,
- toolName: 'request_form',
- toolInput: { fields: FORM_FIELDS },
- toolOutput: { result: { status: 'pending' } },
- },
- });
-
- await service.answerFormStep({
- workflowRunId: 'workflow-run-id',
- stepId: 'step-id',
- response: { discount: '20%' },
- userWorkspaceId: 'user-workspace-id',
- workspaceMemberId: 'member-id',
- workspace,
- });
-
- expect(agentChatService.findToolPart).toHaveBeenCalledWith({
- threadId: 'thread-id',
- toolCallId: 'step-id',
- workspaceId: 'workspace-id',
- });
- });
-
- it('answers the questions a message asked', async () => {
- const { service, agentChatService } = buildService();
-
- agentChatService.findAwaitingToolParts.mockResolvedValueOnce([
- { ...questionPart, toolCallId: 'tool-call-id' },
- ]);
-
- await service.answerQuestionsOfMessage({
- threadId: 'thread-id',
- messageId: 'question-message-id',
- response: { answers: ANSWERS },
- userWorkspaceId: 'user-workspace-id',
- workspaceMemberId: 'member-id',
- workspace,
- });
-
- expect(agentChatService.findToolPart).toHaveBeenCalledWith({
- threadId: 'thread-id',
- toolCallId: 'tool-call-id',
- workspaceId: 'workspace-id',
- });
- expect(agentChatService.recordToolCallAnswer).toHaveBeenCalled();
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-channels.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-channels.service.spec.ts
deleted file mode 100644
index ea053b7fd79..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-channels.service.spec.ts
+++ /dev/null
@@ -1,432 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-import { getRepositoryToken } from '@nestjs/typeorm';
-
-import {
- ConnectedAccountProvider,
- MessageChannelType,
- MessageChannelVisibility,
-} from 'twenty-shared/types';
-import { type Repository } from 'typeorm';
-
-import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
-import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
-import {
- MessageChannelException,
- MessageChannelExceptionCode,
-} from 'src/engine/metadata-modules/message-channel/message-channel.exception';
-import { ApplicationMessageChannelsService } from 'src/engine/metadata-modules/message-channel/services/application-message-channels.service';
-import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
-
-const APPLICATION_ID = '11111111-1111-4111-8111-111111111111';
-const OTHER_APPLICATION_ID = '22222222-2222-4222-8222-222222222222';
-const WORKSPACE_ID = '33333333-3333-4333-8333-333333333333';
-const CONNECTED_ACCOUNT_ID = '44444444-4444-4444-8444-444444444444';
-const MESSAGE_CHANNEL_ID = '55555555-5555-4555-8555-555555555555';
-const ALICE_USER_WORKSPACE_ID = '99999999-9999-4999-8999-999999999999';
-const BOB_USER_WORKSPACE_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
-
-describe('ApplicationMessageChannelsService', () => {
- let service: ApplicationMessageChannelsService;
- let messageChannelRepository: jest.Mocked<Repository<MessageChannelEntity>>;
- let connectedAccountRepository: jest.Mocked<
- Repository<ConnectedAccountEntity>
- >;
- let workspaceEventEmitter: jest.Mocked<WorkspaceEventEmitter>;
-
- // No request user: a cron/webhook run acting as the application itself.
- const scope = {
- applicationId: APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- requestUserWorkspaceId: null,
- };
-
- beforeEach(async () => {
- messageChannelRepository = {
- find: jest.fn().mockResolvedValue([]),
- findOne: jest.fn().mockResolvedValue(null),
- findOneOrFail: jest.fn(),
- create: jest.fn().mockImplementation((data) => data),
- save: jest.fn().mockImplementation(async (data) => data),
- update: jest.fn(),
- delete: jest.fn(),
- } as unknown as jest.Mocked<Repository<MessageChannelEntity>>;
-
- connectedAccountRepository = {
- find: jest.fn().mockResolvedValue([]),
- findOne: jest.fn().mockResolvedValue(null),
- } as unknown as jest.Mocked<Repository<ConnectedAccountEntity>>;
-
- workspaceEventEmitter = {
- emitCustomBatchEvent: jest.fn(),
- } as unknown as jest.Mocked<WorkspaceEventEmitter>;
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- ApplicationMessageChannelsService,
- {
- provide: getRepositoryToken(MessageChannelEntity),
- useValue: messageChannelRepository,
- },
- {
- provide: getRepositoryToken(ConnectedAccountEntity),
- useValue: connectedAccountRepository,
- },
- { provide: WorkspaceEventEmitter, useValue: workspaceEventEmitter },
- ],
- }).compile();
-
- service = module.get(ApplicationMessageChannelsService);
- });
-
- const givenTheAppOwnsTheConnection = () => {
- connectedAccountRepository.findOne.mockResolvedValue({
- id: CONNECTED_ACCOUNT_ID,
- applicationId: APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- provider: ConnectedAccountProvider.APP,
- visibility: 'workspace',
- userWorkspaceId: ALICE_USER_WORKSPACE_ID,
- } as ConnectedAccountEntity);
- connectedAccountRepository.find.mockResolvedValue([
- {
- id: CONNECTED_ACCOUNT_ID,
- visibility: 'workspace',
- userWorkspaceId: ALICE_USER_WORKSPACE_ID,
- },
- ] as ConnectedAccountEntity[]);
- };
-
- describe('create', () => {
- it('creates an APP channel on a connection the app owns', async () => {
- givenTheAppOwnsTheConnection();
-
- const channel = await service.create({
- ...scope,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- handle: 'urn:li:person:abc',
- displayName: ' Ada Lovelace ',
- visibility: MessageChannelVisibility.METADATA,
- });
-
- expect(channel).toEqual(
- expect.objectContaining({
- workspaceId: WORKSPACE_ID,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- handle: 'urn:li:person:abc',
- displayName: 'Ada Lovelace',
- type: MessageChannelType.APP,
- visibility: MessageChannelVisibility.METADATA,
- isSyncEnabled: true,
- }),
- );
- });
-
- it('persists the visibility the app asked for rather than a default', async () => {
- givenTheAppOwnsTheConnection();
-
- const channel = await service.create({
- ...scope,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- handle: 'urn:li:person:abc',
- visibility: MessageChannelVisibility.SHARE_EVERYTHING,
- });
-
- expect(channel.visibility).toBe(
- MessageChannelVisibility.SHARE_EVERYTHING,
- );
- });
-
- it('refuses a connection belonging to another application', async () => {
- connectedAccountRepository.findOne.mockResolvedValue(null);
-
- await expect(
- service.create({
- applicationId: OTHER_APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- requestUserWorkspaceId: null,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- handle: 'urn:li:person:abc',
- visibility: MessageChannelVisibility.METADATA,
- }),
- ).rejects.toThrow(MessageChannelException);
-
- expect(messageChannelRepository.save).not.toHaveBeenCalled();
- });
-
- it('refuses a second channel for the same handle on one connection', async () => {
- givenTheAppOwnsTheConnection();
- messageChannelRepository.findOne.mockResolvedValue({
- id: MESSAGE_CHANNEL_ID,
- } as MessageChannelEntity);
-
- await expect(
- service.create({
- ...scope,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- handle: 'urn:li:person:abc',
- visibility: MessageChannelVisibility.METADATA,
- }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
- });
- });
- });
-
- describe('update', () => {
- it('refuses a channel owned by another application', async () => {
- messageChannelRepository.findOne.mockResolvedValue({
- id: MESSAGE_CHANNEL_ID,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- type: MessageChannelType.APP,
- } as MessageChannelEntity);
- connectedAccountRepository.findOne.mockResolvedValue(null);
-
- await expect(
- service.update({
- applicationId: OTHER_APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- requestUserWorkspaceId: null,
- id: MESSAGE_CHANNEL_ID,
- displayName: 'stolen',
- }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.MESSAGE_CHANNEL_NOT_FOUND,
- });
-
- expect(messageChannelRepository.update).not.toHaveBeenCalled();
- });
-
- it('clears the display name on an explicit null but leaves it on omission', async () => {
- const existing = {
- id: MESSAGE_CHANNEL_ID,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- type: MessageChannelType.APP,
- displayName: 'Ada',
- } as MessageChannelEntity;
-
- messageChannelRepository.findOne.mockResolvedValue(existing);
- messageChannelRepository.findOneOrFail.mockResolvedValue(existing);
- givenTheAppOwnsTheConnection();
-
- await service.update({ ...scope, id: MESSAGE_CHANNEL_ID });
- expect(messageChannelRepository.update).not.toHaveBeenCalled();
-
- await service.update({
- ...scope,
- id: MESSAGE_CHANNEL_ID,
- displayName: null,
- });
- expect(messageChannelRepository.update).toHaveBeenCalledWith(
- { id: MESSAGE_CHANNEL_ID, workspaceId: WORKSPACE_ID },
- { displayName: null },
- );
- });
-
- it('does not resolve a channel that is not app-owned', async () => {
- messageChannelRepository.findOne.mockResolvedValue(null);
-
- await expect(
- service.update({
- ...scope,
- id: MESSAGE_CHANNEL_ID,
- isSyncEnabled: false,
- }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.MESSAGE_CHANNEL_NOT_FOUND,
- });
-
- expect(messageChannelRepository.findOne).toHaveBeenCalledWith({
- where: {
- id: MESSAGE_CHANNEL_ID,
- workspaceId: WORKSPACE_ID,
- type: MessageChannelType.APP,
- },
- });
- });
- });
-
- describe('delete', () => {
- it('emits the channel-deleted event so ingested messages are cleaned up', async () => {
- messageChannelRepository.findOne.mockResolvedValue({
- id: MESSAGE_CHANNEL_ID,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- type: MessageChannelType.APP,
- } as MessageChannelEntity);
- givenTheAppOwnsTheConnection();
-
- await service.delete({ ...scope, id: MESSAGE_CHANNEL_ID });
-
- expect(messageChannelRepository.delete).toHaveBeenCalledWith({
- id: MESSAGE_CHANNEL_ID,
- workspaceId: WORKSPACE_ID,
- });
- expect(workspaceEventEmitter.emitCustomBatchEvent).toHaveBeenCalledWith(
- expect.any(String),
- [{ messageChannelId: MESSAGE_CHANNEL_ID }],
- WORKSPACE_ID,
- );
- });
- });
-
- describe('list', () => {
- it('returns nothing when the app holds no connections', async () => {
- connectedAccountRepository.find.mockResolvedValue([]);
-
- await expect(service.list(scope)).resolves.toEqual([]);
- expect(messageChannelRepository.find).not.toHaveBeenCalled();
- });
-
- it('refuses to filter by a connection the app does not own', async () => {
- connectedAccountRepository.find.mockResolvedValue([
- {
- id: CONNECTED_ACCOUNT_ID,
- visibility: 'workspace',
- userWorkspaceId: ALICE_USER_WORKSPACE_ID,
- },
- ] as ConnectedAccountEntity[]);
-
- await expect(
- service.list({ ...scope, connectedAccountId: 'someone-elses' }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.MESSAGE_CHANNEL_OWNERSHIP_VIOLATION,
- });
- });
- });
- // Owning the app is not permission to administer another person's private
- // connection. Same application, two users, one private connection.
- describe("another user's private connection", () => {
- const givenAlicePrivateConnection = () => {
- const alicesAccount = {
- id: CONNECTED_ACCOUNT_ID,
- applicationId: APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- provider: ConnectedAccountProvider.APP,
- visibility: 'user',
- userWorkspaceId: ALICE_USER_WORKSPACE_ID,
- } as ConnectedAccountEntity;
-
- connectedAccountRepository.findOne.mockResolvedValue(alicesAccount);
- connectedAccountRepository.find.mockResolvedValue([alicesAccount]);
- messageChannelRepository.findOne.mockResolvedValue({
- id: MESSAGE_CHANNEL_ID,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- type: MessageChannelType.APP,
- } as MessageChannelEntity);
- };
-
- const asBob = {
- applicationId: APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- requestUserWorkspaceId: BOB_USER_WORKSPACE_ID,
- };
- const asAlice = {
- applicationId: APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- requestUserWorkspaceId: ALICE_USER_WORKSPACE_ID,
- };
-
- it("hides Alice's channel from Bob's listing", async () => {
- givenAlicePrivateConnection();
-
- await expect(service.list(asBob)).resolves.toEqual([]);
- expect(messageChannelRepository.find).not.toHaveBeenCalled();
- });
-
- it("refuses Bob a visibility change on Alice's channel", async () => {
- givenAlicePrivateConnection();
-
- await expect(
- service.update({
- ...asBob,
- id: MESSAGE_CHANNEL_ID,
- visibility: MessageChannelVisibility.SHARE_EVERYTHING,
- }),
- ).rejects.toMatchObject({
- // Indistinguishable from a channel that does not exist.
- code: MessageChannelExceptionCode.MESSAGE_CHANNEL_NOT_FOUND,
- });
-
- expect(messageChannelRepository.update).not.toHaveBeenCalled();
- });
-
- it("refuses Bob deletion of Alice's channel", async () => {
- givenAlicePrivateConnection();
-
- await expect(
- service.delete({ ...asBob, id: MESSAGE_CHANNEL_ID }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.MESSAGE_CHANNEL_NOT_FOUND,
- });
-
- expect(messageChannelRepository.delete).not.toHaveBeenCalled();
- });
-
- it("refuses Bob a channel on Alice's connection", async () => {
- givenAlicePrivateConnection();
-
- await expect(
- service.create({
- ...asBob,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- handle: 'urn:li:person:abc',
- visibility: MessageChannelVisibility.METADATA,
- }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.MESSAGE_CHANNEL_OWNERSHIP_VIOLATION,
- });
-
- expect(messageChannelRepository.save).not.toHaveBeenCalled();
- });
-
- it('still lets Alice reach her own channel', async () => {
- givenAlicePrivateConnection();
- messageChannelRepository.findOneOrFail.mockResolvedValue({
- id: MESSAGE_CHANNEL_ID,
- } as MessageChannelEntity);
-
- await expect(
- service.update({
- ...asAlice,
- id: MESSAGE_CHANNEL_ID,
- visibility: MessageChannelVisibility.SHARE_EVERYTHING,
- }),
- ).resolves.toBeDefined();
- expect(messageChannelRepository.update).toHaveBeenCalled();
- });
-
- it('still lets a background run with no request user through', async () => {
- givenAlicePrivateConnection();
- messageChannelRepository.findOneOrFail.mockResolvedValue({
- id: MESSAGE_CHANNEL_ID,
- } as MessageChannelEntity);
-
- await expect(
- service.update({
- ...scope,
- id: MESSAGE_CHANNEL_ID,
- isSyncEnabled: false,
- }),
- ).resolves.toBeDefined();
- });
- });
- it('never names the connection when refusing a channel it cannot reach', async () => {
- messageChannelRepository.findOne.mockResolvedValue({
- id: MESSAGE_CHANNEL_ID,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- type: MessageChannelType.APP,
- } as MessageChannelEntity);
- connectedAccountRepository.findOne.mockResolvedValue(null);
-
- await expect(
- service.update({
- applicationId: OTHER_APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- requestUserWorkspaceId: null,
- id: MESSAGE_CHANNEL_ID,
- displayName: 'probe',
- }),
- ).rejects.toMatchObject({
- message: expect.not.stringContaining(CONNECTED_ACCOUNT_ID),
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-ingestion.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-ingestion.service.spec.ts
deleted file mode 100644
index 1195a1e7810..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-ingestion.service.spec.ts
+++ /dev/null
@@ -1,453 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import {
- MessageChannelType,
- MessageParticipantRole,
-} from 'twenty-shared/types';
-
-import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
-import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
-import { type AppMessageInput } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input';
-import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
-import { MessageChannelExceptionCode } from 'src/engine/metadata-modules/message-channel/message-channel.exception';
-import { ApplicationMessageChannelsService } from 'src/engine/metadata-modules/message-channel/services/application-message-channels.service';
-import { ApplicationMessageIngestionService } from 'src/engine/metadata-modules/message-channel/services/application-message-ingestion.service';
-import { MessageDirection } from 'src/modules/messaging/common/enums/message-direction.enum';
-import { MessagingSaveMessagesAndEnqueueContactCreationService } from 'src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-
-const APPLICATION_ID = '11111111-1111-4111-8111-111111111111';
-const WORKSPACE_ID = '33333333-3333-4333-8333-333333333333';
-const CONNECTED_ACCOUNT_ID = '44444444-4444-4444-8444-444444444444';
-const MESSAGE_CHANNEL_ID = '55555555-5555-4555-8555-555555555555';
-const CHANNEL_HANDLE = 'urn:li:person:self';
-
-describe('ApplicationMessageIngestionService', () => {
- let service: ApplicationMessageIngestionService;
- let channelsService: jest.Mocked<ApplicationMessageChannelsService>;
- let saveMessagesService: jest.Mocked<MessagingSaveMessagesAndEnqueueContactCreationService>;
- let existingRecordIds: string[];
- let recordLookup: jest.Mock;
- let cacheLockService: { withLock: jest.Mock };
-
- const scope = {
- applicationId: APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- requestUserWorkspaceId: null,
- messageChannelId: MESSAGE_CHANNEL_ID,
- };
-
- const aMessage = (overrides: Partial<AppMessageInput> = {}) =>
- ({
- externalId: 'msg-1',
- threadExternalId: 'thread-1',
- text: 'hello',
- receivedAt: new Date('2026-01-01T00:00:00Z'),
- participants: [
- {
- role: MessageParticipantRole.FROM,
- handle: 'urn:li:person:ada',
- displayName: 'Ada',
- },
- { role: MessageParticipantRole.TO, handle: CHANNEL_HANDLE },
- ],
- ...overrides,
- }) as AppMessageInput;
-
- beforeEach(async () => {
- existingRecordIds = [];
- recordLookup = jest
- .fn()
- .mockImplementation(async () => existingRecordIds.map((id) => ({ id })));
- cacheLockService = { withLock: jest.fn((fn: () => unknown) => fn()) };
-
- channelsService = {
- findOwnedOrThrow: jest.fn().mockResolvedValue({
- messageChannel: {
- id: MESSAGE_CHANNEL_ID,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- handle: CHANNEL_HANDLE,
- type: MessageChannelType.APP,
- isSyncEnabled: true,
- } as MessageChannelEntity,
- connectedAccount: {
- id: CONNECTED_ACCOUNT_ID,
- handle: CHANNEL_HANDLE,
- handleAliases: [],
- } as unknown as ConnectedAccountEntity,
- }),
- } as unknown as jest.Mocked<ApplicationMessageChannelsService>;
-
- saveMessagesService = {
- saveMessagesAndEnqueueContactCreation: jest.fn().mockResolvedValue({
- messageExternalIdsAndIdsMap: new Map([['msg-1', 'message-uuid']]),
- messageExternalIdToMessageThreadIdMap: new Map([
- ['msg-1', 'thread-uuid'],
- ]),
- }),
- } as unknown as jest.Mocked<MessagingSaveMessagesAndEnqueueContactCreationService>;
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- ApplicationMessageIngestionService,
- { provide: CacheLockService, useValue: cacheLockService },
- {
- provide: ApplicationMessageChannelsService,
- useValue: channelsService,
- },
- {
- provide: MessagingSaveMessagesAndEnqueueContactCreationService,
- useValue: saveMessagesService,
- },
- {
- provide: WorkspaceOrmManager,
- useValue: {
- executeInWorkspaceContext: (callback: () => unknown) => callback(),
- getRepository: () => ({ find: recordLookup }),
- },
- },
- ],
- }).compile();
-
- service = module.get(ApplicationMessageIngestionService);
- });
-
- const savedMessages = () =>
- saveMessagesService.saveMessagesAndEnqueueContactCreation.mock.calls[0][0];
-
- it('routes through the shared save path rather than writing records directly', async () => {
- await service.ingest({ ...scope, messages: [aMessage()] });
-
- expect(
- saveMessagesService.saveMessagesAndEnqueueContactCreation,
- ).toHaveBeenCalledTimes(1);
- expect(savedMessages()[0]).toEqual(
- expect.objectContaining({
- externalId: 'msg-1',
- messageThreadExternalId: 'thread-1',
- text: 'hello',
- isDraft: false,
- }),
- );
- });
-
- it('namespaces the dedup key by application and channel', async () => {
- await service.ingest({ ...scope, messages: [aMessage()] });
-
- expect(savedMessages()[0].headerMessageId).toBe(
- `app:${APPLICATION_ID}:${MESSAGE_CHANNEL_ID}:msg-1`,
- );
- });
-
- it('derives direction from the sender rather than trusting the app', async () => {
- await service.ingest({ ...scope, messages: [aMessage()] });
- expect(savedMessages()[0].direction).toBe(MessageDirection.INCOMING);
-
- saveMessagesService.saveMessagesAndEnqueueContactCreation.mockClear();
-
- await service.ingest({
- ...scope,
- messages: [
- aMessage({
- participants: [
- { role: MessageParticipantRole.FROM, handle: CHANNEL_HANDLE },
- { role: MessageParticipantRole.TO, handle: 'urn:li:person:ada' },
- ],
- }),
- ],
- });
- expect(savedMessages()[0].direction).toBe(MessageDirection.OUTGOING);
- });
-
- it('defaults a missing subject to null rather than an empty string', async () => {
- await service.ingest({ ...scope, messages: [aMessage()] });
-
- expect(savedMessages()[0].subject).toBeNull();
- });
-
- it('rejects a message with no sender', async () => {
- await expect(
- service.ingest({
- ...scope,
- messages: [
- aMessage({
- participants: [
- { role: MessageParticipantRole.TO, handle: CHANNEL_HANDLE },
- ],
- }),
- ],
- }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
- });
-
- expect(
- saveMessagesService.saveMessagesAndEnqueueContactCreation,
- ).not.toHaveBeenCalled();
- });
-
- it('rejects a message with two senders', async () => {
- await expect(
- service.ingest({
- ...scope,
- messages: [
- aMessage({
- participants: [
- { role: MessageParticipantRole.FROM, handle: 'a' },
- { role: MessageParticipantRole.FROM, handle: 'b' },
- ],
- }),
- ],
- }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
- });
- });
-
- it('rejects a batch repeating one external id', async () => {
- await expect(
- service.ingest({
- ...scope,
- messages: [aMessage(), aMessage()],
- }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
- });
-
- expect(
- saveMessagesService.saveMessagesAndEnqueueContactCreation,
- ).not.toHaveBeenCalled();
- });
-
- it('refuses to ingest into a paused channel', async () => {
- channelsService.findOwnedOrThrow.mockResolvedValue({
- messageChannel: {
- id: MESSAGE_CHANNEL_ID,
- connectedAccountId: CONNECTED_ACCOUNT_ID,
- handle: CHANNEL_HANDLE,
- type: MessageChannelType.APP,
- isSyncEnabled: false,
- } as MessageChannelEntity,
- connectedAccount: {
- id: CONNECTED_ACCOUNT_ID,
- handle: CHANNEL_HANDLE,
- handleAliases: [],
- } as unknown as ConnectedAccountEntity,
- });
-
- await expect(
- service.ingest({ ...scope, messages: [aMessage()] }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
- });
-
- expect(
- saveMessagesService.saveMessagesAndEnqueueContactCreation,
- ).not.toHaveBeenCalled();
- });
-
- it('gates on channel ownership before touching anything else', async () => {
- channelsService.findOwnedOrThrow.mockRejectedValue(new Error('not yours'));
-
- await expect(
- service.ingest({ ...scope, messages: [aMessage()] }),
- ).rejects.toThrow('not yours');
- });
-
- it('returns the ids the app needs to link its own records', async () => {
- const result = await service.ingest({ ...scope, messages: [aMessage()] });
-
- expect(result.messages).toEqual([
- {
- externalId: 'msg-1',
- messageId: 'message-uuid',
- messageThreadId: 'thread-uuid',
- },
- ]);
- });
- describe('explicit identity', () => {
- const PERSON_ID = '66666666-6666-4666-8666-666666666666';
-
- it('passes a supplied personId through to the saved participant', async () => {
- existingRecordIds = [PERSON_ID];
-
- await service.ingest({
- ...scope,
- messages: [
- aMessage({
- participants: [
- {
- role: MessageParticipantRole.FROM,
- handle: 'urn:li:person:ada',
- personId: PERSON_ID,
- },
- { role: MessageParticipantRole.TO, handle: CHANNEL_HANDLE },
- ],
- }),
- ],
- });
-
- expect(savedMessages()[0].participants[0]).toEqual(
- expect.objectContaining({ personId: PERSON_ID }),
- );
- });
-
- it('defaults an omitted identity to null rather than undefined', async () => {
- await service.ingest({ ...scope, messages: [aMessage()] });
-
- expect(savedMessages()[0].participants[0]).toEqual(
- expect.objectContaining({ personId: null, workspaceMemberId: null }),
- );
- });
-
- it('rejects a workspaceMemberId that does not exist in the workspace', async () => {
- existingRecordIds = [];
-
- await expect(
- service.ingest({
- ...scope,
- messages: [
- aMessage({
- participants: [
- {
- role: MessageParticipantRole.FROM,
- handle: 'urn:li:person:ada',
- workspaceMemberId: PERSON_ID,
- },
- ],
- }),
- ],
- }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
- });
-
- expect(
- saveMessagesService.saveMessagesAndEnqueueContactCreation,
- ).not.toHaveBeenCalled();
- });
-
- it('rejects a personId that does not exist in the workspace', async () => {
- existingRecordIds = [];
-
- await expect(
- service.ingest({
- ...scope,
- messages: [
- aMessage({
- participants: [
- {
- role: MessageParticipantRole.FROM,
- handle: 'urn:li:person:ada',
- personId: PERSON_ID,
- },
- ],
- }),
- ],
- }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
- });
-
- expect(
- saveMessagesService.saveMessagesAndEnqueueContactCreation,
- ).not.toHaveBeenCalled();
- });
-
- // The assertion that matters is the absence of the lookup: without it the
- // test passes just as well with the early return deleted.
- it('does not query for records when no identity is supplied', async () => {
- await service.ingest({ ...scope, messages: [aMessage()] });
-
- expect(recordLookup).not.toHaveBeenCalled();
- expect(
- saveMessagesService.saveMessagesAndEnqueueContactCreation,
- ).toHaveBeenCalled();
- });
- });
-
- it("refuses to ingest into another member's private channel", async () => {
- channelsService.findOwnedOrThrow.mockRejectedValue(
- new Error('ownership violation'),
- );
-
- await expect(
- service.ingest({
- ...scope,
- requestUserWorkspaceId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
- messages: [aMessage()],
- }),
- ).rejects.toThrow('ownership violation');
-
- expect(
- saveMessagesService.saveMessagesAndEnqueueContactCreation,
- ).not.toHaveBeenCalled();
- });
-
- it('passes the request user to the ownership gate', async () => {
- await service.ingest({
- ...scope,
- requestUserWorkspaceId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
- messages: [aMessage()],
- });
-
- expect(channelsService.findOwnedOrThrow).toHaveBeenCalledWith(
- expect.objectContaining({
- requestUserWorkspaceId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
- }),
- );
- });
- it('serialises the save per channel so a redelivery cannot race its original', async () => {
- await service.ingest({ ...scope, messages: [aMessage()] });
-
- expect(cacheLockService.withLock).toHaveBeenCalledWith(
- expect.any(Function),
- `app-message-ingestion:${WORKSPACE_ID}:${MESSAGE_CHANNEL_ID}`,
- expect.objectContaining({ ttl: expect.any(Number) }),
- );
- });
-
- it('holds the lock around the save rather than after it', async () => {
- const order: string[] = [];
-
- cacheLockService.withLock.mockImplementation(async (fn: () => unknown) => {
- order.push('lock-acquired');
- const result = await fn();
-
- order.push('lock-released');
-
- return result;
- });
- saveMessagesService.saveMessagesAndEnqueueContactCreation.mockImplementation(
- async () => {
- order.push('saved');
-
- return {
- messageExternalIdsAndIdsMap: new Map([['msg-1', 'message-uuid']]),
- messageExternalIdToMessageThreadIdMap: new Map([
- ['msg-1', 'thread-uuid'],
- ]),
- };
- },
- );
-
- await service.ingest({ ...scope, messages: [aMessage()] });
-
- expect(order).toEqual(['lock-acquired', 'saved', 'lock-released']);
- });
-
- it('fails loudly rather than returning fewer messages than were sent', async () => {
- saveMessagesService.saveMessagesAndEnqueueContactCreation.mockResolvedValue(
- {
- messageExternalIdsAndIdsMap: new Map(),
- messageExternalIdToMessageThreadIdMap: new Map(),
- } as never,
- );
-
- await expect(
- service.ingest({ ...scope, messages: [aMessage()] }),
- ).rejects.toMatchObject({
- code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/field-metadata/services/__tests__/field-search-field-metadata-on-create-side-effect-handler.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/field-metadata/services/__tests__/field-search-field-metadata-on-create-side-effect-handler.service.spec.ts
deleted file mode 100644
index 81f93d0a029..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/field-metadata/services/__tests__/field-search-field-metadata-on-create-side-effect-handler.service.spec.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-import { getFieldUniversalIdentifier } from 'twenty-shared/application';
-import { FieldMetadataType } from 'twenty-shared/types';
-
-import { FieldSearchFieldMetadataOnCreateSideEffectHandlerService } from 'src/engine/metadata-modules/metadata-side-effect/handlers/field-metadata/services/field-search-field-metadata-on-create-side-effect-handler.service';
-import { type BuildSideEffectsArgs } from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
-
-const APPLICATION_UNIVERSAL_IDENTIFIER = 'a1a2a3a4-a5a6-4000-8000-000000000001';
-const OBJECT_UNIVERSAL_IDENTIFIER = 'b1b2b3b4-b5b6-4000-8000-000000000001';
-const FIELD_UNIVERSAL_IDENTIFIER = 'd1d2d3d4-d5d6-4000-8000-000000000001';
-const TS_VECTOR_FIELD_UNIVERSAL_IDENTIFIER =
- 'd1d2d3d4-d5d6-4000-8000-000000000002';
-const EXISTING_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER =
- 'f1f2f3f4-f5f6-4000-8000-000000000001';
-
-const buildArgs = ({
- isSearchable,
- isLabelIdentifier = false,
- hasTsVectorField = true,
- parentIsPendingCreate = false,
- objectSearchFieldMetadatas = {},
- pendingSearchFieldMetadataCreatesByFieldUniversalIdentifier = {},
-}: {
- isSearchable: boolean;
- isLabelIdentifier?: boolean;
- hasTsVectorField?: boolean;
- parentIsPendingCreate?: boolean;
- objectSearchFieldMetadatas?: Record<string, { position: number }>;
- pendingSearchFieldMetadataCreatesByFieldUniversalIdentifier?: Record<
- string,
- { position: number }
- >;
-}): BuildSideEffectsArgs<'fieldMetadata'> =>
- ({
- flatEntity: {
- universalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- name: 'city',
- type: FieldMetadataType.TEXT,
- isSearchable,
- },
- allFlatEntityOperationRecordByMetadataName: {
- ...(parentIsPendingCreate
- ? {
- objectMetadata: {
- flatEntityToCreate: {
- [OBJECT_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier:
- APPLICATION_UNIVERSAL_IDENTIFIER,
- isSearchable: true,
- labelIdentifierFieldMetadataUniversalIdentifier: undefined,
- fieldUniversalIdentifiers: [FIELD_UNIVERSAL_IDENTIFIER],
- searchFieldMetadataUniversalIdentifiers: [],
- },
- },
- flatEntityToUpdate: {},
- flatEntityToDelete: {},
- },
- }
- : {}),
- searchFieldMetadata: {
- flatEntityToCreate: Object.fromEntries(
- Object.entries(
- pendingSearchFieldMetadataCreatesByFieldUniversalIdentifier,
- ).map(([fieldMetadataUniversalIdentifier, { position }], index) => [
- `pending-${index}`,
- {
- universalIdentifier: `pending-${index}`,
- position,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- fieldMetadataUniversalIdentifier,
- },
- ]),
- ),
- flatEntityToUpdate: {},
- flatEntityToDelete: {},
- },
- },
- relatedFlatEntityMaps: {
- flatFieldMetadataMaps: {
- byUniversalIdentifier: {
- ...(hasTsVectorField
- ? {
- [TS_VECTOR_FIELD_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: TS_VECTOR_FIELD_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.TS_VECTOR,
- name: 'searchVector',
- },
- }
- : {}),
- },
- },
- flatObjectMetadataMaps: {
- byUniversalIdentifier: {
- [OBJECT_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- labelIdentifierFieldMetadataUniversalIdentifier: isLabelIdentifier
- ? FIELD_UNIVERSAL_IDENTIFIER
- : undefined,
- fieldUniversalIdentifiers: [
- FIELD_UNIVERSAL_IDENTIFIER,
- ...(hasTsVectorField
- ? [TS_VECTOR_FIELD_UNIVERSAL_IDENTIFIER]
- : []),
- ],
- searchFieldMetadataUniversalIdentifiers: Object.keys(
- objectSearchFieldMetadatas,
- ),
- },
- },
- },
- flatSearchFieldMetadataMaps: {
- byUniversalIdentifier: Object.fromEntries(
- Object.entries(objectSearchFieldMetadatas).map(
- ([universalIdentifier, { position }]) => [
- universalIdentifier,
- {
- universalIdentifier,
- position,
- fieldMetadataUniversalIdentifier: 'some-other-field',
- },
- ],
- ),
- ),
- },
- },
- }) as unknown as BuildSideEffectsArgs<'fieldMetadata'>;
-
-describe('FieldSearchFieldMetadataOnCreateSideEffectHandlerService', () => {
- const handler =
- new (FieldSearchFieldMetadataOnCreateSideEffectHandlerService as unknown as new () => FieldSearchFieldMetadataOnCreateSideEffectHandlerService)();
-
- it('should create a searchFieldMetadata row appended at the end when the field is created searchable', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- isSearchable: true,
- objectSearchFieldMetadatas: {
- [EXISTING_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER]: {
- position: 2,
- },
- },
- }),
- );
-
- expect(result.status).toBe('success');
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- const created = Object.values(
- result.operations.searchFieldMetadata?.flatEntityToCreate ?? {},
- );
-
- expect(created).toHaveLength(1);
- expect(created[0]).toMatchObject({
- fieldMetadataUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
- tsVectorFieldMetadataUniversalIdentifier:
- TS_VECTOR_FIELD_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- position: 3,
- isSystemSideEffect: true,
- });
- });
-
- it('should append after rows already created earlier in the same batch', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- isSearchable: true,
- pendingSearchFieldMetadataCreatesByFieldUniversalIdentifier: {
- 'e1e2e3e4-e5e6-4000-8000-000000000001': { position: 0 },
- },
- }),
- );
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- expect(
- Object.values(
- result.operations.searchFieldMetadata?.flatEntityToCreate ?? {},
- )[0],
- ).toMatchObject({ position: 1 });
- });
-
- it('should be a noop when the field is created non-searchable', () => {
- const result = handler.buildSideEffects(buildArgs({ isSearchable: false }));
-
- expect(result.status).toBe('noop');
- });
-
- it('should be a noop for the label identifier, whose row the object-create side effect owns', () => {
- const result = handler.buildSideEffects(
- buildArgs({ isSearchable: true, isLabelIdentifier: true }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('should be a noop when the object has no search vector field', () => {
- const result = handler.buildSideEffects(
- buildArgs({ isSearchable: true, hasTsVectorField: false }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('should reference the deterministic searchVector field when the object is created in the same batch', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- isSearchable: true,
- parentIsPendingCreate: true,
- hasTsVectorField: false,
- }),
- );
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- expect(
- Object.values(
- result.operations.searchFieldMetadata?.flatEntityToCreate ?? {},
- )[0],
- ).toMatchObject({
- fieldMetadataUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
- tsVectorFieldMetadataUniversalIdentifier: getFieldUniversalIdentifier({
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- name: 'searchVector',
- }),
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/field-metadata/services/__tests__/field-search-field-metadata-on-update-side-effect-handler.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/field-metadata/services/__tests__/field-search-field-metadata-on-update-side-effect-handler.service.spec.ts
deleted file mode 100644
index e183e8fe8df..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/field-metadata/services/__tests__/field-search-field-metadata-on-update-side-effect-handler.service.spec.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-import { FieldMetadataType } from 'twenty-shared/types';
-
-import { FieldSearchFieldMetadataOnUpdateSideEffectHandlerService } from 'src/engine/metadata-modules/metadata-side-effect/handlers/field-metadata/services/field-search-field-metadata-on-update-side-effect-handler.service';
-import { type BuildSideEffectsArgs } from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
-
-const APPLICATION_UNIVERSAL_IDENTIFIER = 'a1a2a3a4-a5a6-4000-8000-000000000001';
-const OBJECT_UNIVERSAL_IDENTIFIER = 'b1b2b3b4-b5b6-4000-8000-000000000001';
-const FIELD_UNIVERSAL_IDENTIFIER = 'd1d2d3d4-d5d6-4000-8000-000000000001';
-const TS_VECTOR_FIELD_UNIVERSAL_IDENTIFIER =
- 'd1d2d3d4-d5d6-4000-8000-000000000002';
-const EXISTING_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER =
- 'f1f2f3f4-f5f6-4000-8000-000000000001';
-const FIELD_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER =
- 'f1f2f3f4-f5f6-4000-8000-000000000002';
-
-const buildArgs = ({
- isSearchable,
- existingIsSearchable,
- fieldSearchFieldMetadataUniversalIdentifiers = [],
- objectSearchFieldMetadatas = {},
- pendingSearchFieldMetadataCreates = {},
- hasTsVectorField = true,
-}: {
- isSearchable: boolean;
- existingIsSearchable: boolean;
- fieldSearchFieldMetadataUniversalIdentifiers?: string[];
- objectSearchFieldMetadatas?: Record<string, { position: number }>;
- pendingSearchFieldMetadataCreates?: Record<string, { position: number }>;
- hasTsVectorField?: boolean;
-}): BuildSideEffectsArgs<'fieldMetadata'> =>
- ({
- flatEntity: {
- universalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- name: 'city',
- type: FieldMetadataType.TEXT,
- isSearchable,
- },
- allFlatEntityOperationRecordByMetadataName: {
- searchFieldMetadata: {
- flatEntityToCreate: Object.fromEntries(
- Object.entries(pendingSearchFieldMetadataCreates).map(
- ([universalIdentifier, { position }]) => [
- universalIdentifier,
- {
- universalIdentifier,
- position,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- fieldMetadataUniversalIdentifier: universalIdentifier,
- },
- ],
- ),
- ),
- flatEntityToUpdate: {},
- flatEntityToDelete: {},
- },
- },
- relatedFlatEntityMaps: {
- flatFieldMetadataMaps: {
- byUniversalIdentifier: {
- [FIELD_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- isSearchable: existingIsSearchable,
- searchFieldMetadataUniversalIdentifiers:
- fieldSearchFieldMetadataUniversalIdentifiers,
- },
- ...(hasTsVectorField
- ? {
- [TS_VECTOR_FIELD_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: TS_VECTOR_FIELD_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.TS_VECTOR,
- name: 'searchVector',
- },
- }
- : {}),
- },
- },
- flatObjectMetadataMaps: {
- byUniversalIdentifier: {
- [OBJECT_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- fieldUniversalIdentifiers: [
- FIELD_UNIVERSAL_IDENTIFIER,
- ...(hasTsVectorField
- ? [TS_VECTOR_FIELD_UNIVERSAL_IDENTIFIER]
- : []),
- ],
- searchFieldMetadataUniversalIdentifiers: Object.keys(
- objectSearchFieldMetadatas,
- ),
- },
- },
- },
- flatSearchFieldMetadataMaps: {
- byUniversalIdentifier: Object.fromEntries(
- Object.entries(objectSearchFieldMetadatas).map(
- ([universalIdentifier, { position }]) => [
- universalIdentifier,
- {
- universalIdentifier,
- position,
- fieldMetadataUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
- },
- ],
- ),
- ),
- },
- },
- context: {},
- }) as unknown as BuildSideEffectsArgs<'fieldMetadata'>;
-
-describe('FieldSearchFieldMetadataOnUpdateSideEffectHandlerService', () => {
- const handler =
- new (FieldSearchFieldMetadataOnUpdateSideEffectHandlerService as unknown as new () => FieldSearchFieldMetadataOnUpdateSideEffectHandlerService)();
-
- it('should create a searchFieldMetadata row appended at the end when isSearchable is turned on', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- isSearchable: true,
- existingIsSearchable: false,
- objectSearchFieldMetadatas: {
- [EXISTING_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER]: {
- position: 4,
- },
- },
- }),
- );
-
- expect(result.status).toBe('success');
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- const created = Object.values(
- result.operations.searchFieldMetadata?.flatEntityToCreate ?? {},
- );
-
- expect(created).toHaveLength(1);
- expect(created[0]).toMatchObject({
- fieldMetadataUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
- tsVectorFieldMetadataUniversalIdentifier:
- TS_VECTOR_FIELD_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- position: 5,
- isSystemSideEffect: true,
- });
- });
-
- it('should append after rows already created earlier in the same batch', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- isSearchable: true,
- existingIsSearchable: false,
- objectSearchFieldMetadatas: {
- [EXISTING_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER]: {
- position: 4,
- },
- },
- pendingSearchFieldMetadataCreates: {
- 'f1f2f3f4-f5f6-4000-8000-000000000009': { position: 5 },
- },
- }),
- );
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- expect(
- Object.values(
- result.operations.searchFieldMetadata?.flatEntityToCreate ?? {},
- )[0],
- ).toMatchObject({ position: 6 });
- });
-
- it('should create the row at position 0 when the object has no search field yet', () => {
- const result = handler.buildSideEffects(
- buildArgs({ isSearchable: true, existingIsSearchable: false }),
- );
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- expect(
- Object.values(
- result.operations.searchFieldMetadata?.flatEntityToCreate ?? {},
- )[0],
- ).toMatchObject({ position: 0 });
- });
-
- it('should delete every searchFieldMetadata row indexing the field when isSearchable is turned off', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- isSearchable: false,
- existingIsSearchable: true,
- fieldSearchFieldMetadataUniversalIdentifiers: [
- FIELD_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER,
- ],
- objectSearchFieldMetadatas: {
- [FIELD_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER]: { position: 2 },
- },
- }),
- );
-
- expect(result.status).toBe('success');
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- expect(
- Object.keys(
- result.operations.searchFieldMetadata?.flatEntityToDelete ?? {},
- ),
- ).toEqual([FIELD_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER]);
- });
-
- it('should be a noop when isSearchable stays true', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- isSearchable: true,
- existingIsSearchable: true,
- fieldSearchFieldMetadataUniversalIdentifiers: [
- FIELD_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER,
- ],
- objectSearchFieldMetadatas: {
- [FIELD_SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER]: { position: 2 },
- },
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('should be a noop when isSearchable stays false', () => {
- const result = handler.buildSideEffects(
- buildArgs({ isSearchable: false, existingIsSearchable: false }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('should be a noop when the object has no search vector field', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- isSearchable: true,
- existingIsSearchable: false,
- hasTsVectorField: false,
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-navigation-command-on-create-side-effect-handler.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-navigation-command-on-create-side-effect-handler.service.spec.ts
deleted file mode 100644
index c92abb28e09..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-navigation-command-on-create-side-effect-handler.service.spec.ts
+++ /dev/null
@@ -1,282 +0,0 @@
-import { getSystemNavigationCommandMenuItemUniversalIdentifier } from 'twenty-shared/application';
-import { MetadataReadability } from 'twenty-shared/types';
-
-import { EngineComponentKey } from 'src/engine/metadata-modules/command-menu-item/enums/engine-component-key.enum';
-import { type AllFlatEntityOperationRecordByMetadataName } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-operation-record-by-metadata-name.type';
-import { ObjectNavigationCommandOnCreateSideEffectHandlerService } from 'src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-navigation-command-on-create-side-effect-handler.service';
-import { type BuildSideEffectsArgs } from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
-
-const APPLICATION_UNIVERSAL_IDENTIFIER = 'a1a2a3a4-a5a6-4000-8000-000000000001';
-const OTHER_APPLICATION_UNIVERSAL_IDENTIFIER =
- 'a1a2a3a4-a5a6-4000-8000-000000000002';
-const OBJECT_UNIVERSAL_IDENTIFIER = 'b1b2b3b4-b5b6-4000-8000-000000000001';
-const OTHER_OBJECT_UNIVERSAL_IDENTIFIER =
- 'b1b2b3b4-b5b6-4000-8000-000000000002';
-const OBJECT_ID = 'c1c2c3c4-c5c6-4000-8000-000000000001';
-const OTHER_OBJECT_ID = 'c1c2c3c4-c5c6-4000-8000-000000000002';
-
-const DERIVED_UNIVERSAL_IDENTIFIER =
- getSystemNavigationCommandMenuItemUniversalIdentifier({
- objectMetadataApplicationUniversalIdentifier:
- APPLICATION_UNIVERSAL_IDENTIFIER,
- objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- });
-
-type ObjectMetadataOverrides = Partial<{
- id: string | undefined;
- universalIdentifier: string;
- applicationUniversalIdentifier: string;
- isActive: boolean;
- nameSingular: string;
- shortcut: string | null;
- readability: MetadataReadability;
- commandMenuItemUniversalIdentifiers: string[];
-}>;
-
-const buildFlatObjectMetadata = (overrides: ObjectMetadataOverrides = {}) => ({
- id: OBJECT_ID,
- universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- isActive: true,
- nameSingular: 'ticket',
- shortcut: 'T',
- readability: MetadataReadability.OPEN,
- commandMenuItemUniversalIdentifiers: [],
- ...overrides,
-});
-
-const buildArgs = ({
- flatObjectMetadata = buildFlatObjectMetadata(),
- otherFlatObjectMetadatasInBatch = [],
- pendingFlatCommandMenuItems = [],
- syncedFlatCommandMenuItems = [],
-}: {
- flatObjectMetadata?: ReturnType<typeof buildFlatObjectMetadata>;
- otherFlatObjectMetadatasInBatch?: ReturnType<
- typeof buildFlatObjectMetadata
- >[];
- pendingFlatCommandMenuItems?: object[];
- syncedFlatCommandMenuItems?: {
- universalIdentifier: string;
- position: number;
- }[];
-} = {}): BuildSideEffectsArgs<'objectMetadata'> =>
- ({
- flatEntity: flatObjectMetadata,
- allFlatEntityOperationRecordByMetadataName: {
- objectMetadata: {
- flatEntityToCreate: Object.fromEntries(
- [flatObjectMetadata, ...otherFlatObjectMetadatasInBatch].map(
- (batchFlatObjectMetadata) => [
- batchFlatObjectMetadata.universalIdentifier,
- batchFlatObjectMetadata,
- ],
- ),
- ),
- flatEntityToUpdate: {},
- flatEntityToDelete: {},
- },
- ...(pendingFlatCommandMenuItems.length > 0 && {
- commandMenuItem: {
- flatEntityToCreate: Object.fromEntries(
- pendingFlatCommandMenuItems.map((pendingFlatCommandMenuItem) => [
- (pendingFlatCommandMenuItem as { universalIdentifier: string })
- .universalIdentifier,
- pendingFlatCommandMenuItem,
- ]),
- ),
- flatEntityToUpdate: {},
- flatEntityToDelete: {},
- },
- }),
- } as unknown as AllFlatEntityOperationRecordByMetadataName,
- relatedFlatEntityMaps: {
- flatCommandMenuItemMaps: {
- byUniversalIdentifier: Object.fromEntries(
- syncedFlatCommandMenuItems.map((syncedFlatCommandMenuItem) => [
- syncedFlatCommandMenuItem.universalIdentifier,
- syncedFlatCommandMenuItem,
- ]),
- ),
- },
- },
- context: {},
- }) as unknown as BuildSideEffectsArgs<'objectMetadata'>;
-
-describe('ObjectNavigationCommandOnCreateSideEffectHandlerService', () => {
- const handler =
- new (ObjectNavigationCommandOnCreateSideEffectHandlerService as unknown as new () => ObjectNavigationCommandOnCreateSideEffectHandlerService)();
-
- const expectSuccess = (
- result: ReturnType<typeof handler.buildSideEffects>,
- ) => {
- if (result.status !== 'success') {
- throw new Error(`expected success, got ${result.status}`);
- }
-
- return result;
- };
-
- it('provisions the navigation command with the derived (application, object) identifier and denormalized fields', () => {
- const result = expectSuccess(handler.buildSideEffects(buildArgs()));
-
- const created = Object.values(
- result.operations.commandMenuItem?.flatEntityToCreate ?? {},
- );
-
- expect(created).toHaveLength(1);
-
- const [navigationCommand] = created as unknown as [
- {
- universalIdentifier: string;
- applicationUniversalIdentifier: string;
- engineComponentKey: EngineComponentKey;
- payload: unknown;
- hotKeys: string[] | null;
- conditionalAvailabilityExpression: string | null;
- isSystemSideEffect: boolean;
- position: number;
- },
- ];
-
- expect(navigationCommand.universalIdentifier).toBe(
- DERIVED_UNIVERSAL_IDENTIFIER,
- );
- expect(navigationCommand.applicationUniversalIdentifier).toBe(
- APPLICATION_UNIVERSAL_IDENTIFIER,
- );
- expect(navigationCommand.engineComponentKey).toBe(
- EngineComponentKey.NAVIGATION,
- );
- expect(navigationCommand.payload).toBeNull();
- expect(navigationCommand.hotKeys).toEqual(['G', 'T']);
- expect(navigationCommand.conditionalAvailabilityExpression).toBe(
- 'targetObjectReadPermissions.ticket',
- );
- expect(navigationCommand.isSystemSideEffect).toBe(true);
- expect(navigationCommand.position).toBe(0);
- });
-
- it('derives the identifier from the owning application, so an app-owned object gets an app-owned command', () => {
- const result = expectSuccess(
- handler.buildSideEffects(
- buildArgs({
- flatObjectMetadata: buildFlatObjectMetadata({
- applicationUniversalIdentifier:
- OTHER_APPLICATION_UNIVERSAL_IDENTIFIER,
- }),
- }),
- ),
- );
-
- const [navigationCommand] = Object.values(
- result.operations.commandMenuItem?.flatEntityToCreate ?? {},
- ) as unknown as [{ universalIdentifier: string }];
-
- expect(navigationCommand.universalIdentifier).toBe(
- getSystemNavigationCommandMenuItemUniversalIdentifier({
- objectMetadataApplicationUniversalIdentifier:
- OTHER_APPLICATION_UNIVERSAL_IDENTIFIER,
- objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- }),
- );
- expect(navigationCommand.universalIdentifier).not.toBe(
- DERIVED_UNIVERSAL_IDENTIFIER,
- );
- });
-
- it('provisions a disabled command when the object is created inactive', () => {
- const result = expectSuccess(
- handler.buildSideEffects(
- buildArgs({
- flatObjectMetadata: buildFlatObjectMetadata({ isActive: false }),
- }),
- ),
- );
-
- const [navigationCommand] = Object.values(
- result.operations.commandMenuItem?.flatEntityToCreate ?? {},
- ) as unknown as [{ isActive: boolean }];
-
- expect(navigationCommand.isActive).toBe(false);
- });
-
- it('noops when the object create carries no workspace id (manifest sync path)', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- flatObjectMetadata: buildFlatObjectMetadata({ id: undefined }),
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('noops when the object is SYSTEM-readable', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- flatObjectMetadata: buildFlatObjectMetadata({
- readability: MetadataReadability.SYSTEM,
- }),
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('appends after the synced maximum position', () => {
- const result = expectSuccess(
- handler.buildSideEffects(
- buildArgs({
- syncedFlatCommandMenuItems: [
- { universalIdentifier: 'existing-command', position: 41 } as never,
- ],
- }),
- ),
- );
-
- const [navigationCommand] = Object.values(
- result.operations.commandMenuItem?.flatEntityToCreate ?? {},
- ) as unknown as [{ position: number }];
-
- expect(navigationCommand.position).toBe(42);
- });
-
- it('derives distinct deterministic positions for objects created in the same batch', () => {
- const firstFlatObjectMetadata = buildFlatObjectMetadata();
- const secondFlatObjectMetadata = buildFlatObjectMetadata({
- id: OTHER_OBJECT_ID,
- universalIdentifier: OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
- nameSingular: 'invoice',
- shortcut: null,
- });
-
- const firstResult = expectSuccess(
- handler.buildSideEffects(
- buildArgs({
- flatObjectMetadata: firstFlatObjectMetadata,
- otherFlatObjectMetadatasInBatch: [secondFlatObjectMetadata],
- }),
- ),
- );
- const secondResult = expectSuccess(
- handler.buildSideEffects({
- ...buildArgs({
- flatObjectMetadata: firstFlatObjectMetadata,
- otherFlatObjectMetadatasInBatch: [secondFlatObjectMetadata],
- }),
- flatEntity:
- secondFlatObjectMetadata as unknown as BuildSideEffectsArgs<'objectMetadata'>['flatEntity'],
- }),
- );
-
- const [firstNavigationCommand] = Object.values(
- firstResult.operations.commandMenuItem?.flatEntityToCreate ?? {},
- ) as unknown as [{ position: number }];
- const [secondNavigationCommand] = Object.values(
- secondResult.operations.commandMenuItem?.flatEntityToCreate ?? {},
- ) as unknown as [{ position: number }];
-
- expect(firstNavigationCommand.position).toBe(0);
- expect(secondNavigationCommand.position).toBe(1);
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-navigation-command-on-update-side-effect-handler.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-navigation-command-on-update-side-effect-handler.service.spec.ts
deleted file mode 100644
index b241c702419..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-navigation-command-on-update-side-effect-handler.service.spec.ts
+++ /dev/null
@@ -1,346 +0,0 @@
-import { getSystemNavigationCommandMenuItemUniversalIdentifier } from 'twenty-shared/application';
-
-import { EngineComponentKey } from 'src/engine/metadata-modules/command-menu-item/enums/engine-component-key.enum';
-import { type AllFlatEntityOperationRecordByMetadataName } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-operation-record-by-metadata-name.type';
-import { ObjectNavigationCommandOnUpdateSideEffectHandlerService } from 'src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-navigation-command-on-update-side-effect-handler.service';
-import { type BuildSideEffectsArgs } from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
-
-const APPLICATION_UNIVERSAL_IDENTIFIER = 'a1a2a3a4-a5a6-4000-8000-000000000001';
-const OBJECT_UNIVERSAL_IDENTIFIER = 'b1b2b3b4-b5b6-4000-8000-000000000001';
-const OBJECT_ID = 'c1c2c3c4-c5c6-4000-8000-000000000001';
-
-const DERIVED_UNIVERSAL_IDENTIFIER =
- getSystemNavigationCommandMenuItemUniversalIdentifier({
- objectMetadataApplicationUniversalIdentifier:
- APPLICATION_UNIVERSAL_IDENTIFIER,
- objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- });
-const LEGACY_UNIVERSAL_IDENTIFIER = 'legacy-v5-derived-identifier';
-
-const buildFlatObjectMetadata = (
- overrides: Partial<{
- isActive: boolean;
- nameSingular: string;
- shortcut: string | null;
- commandMenuItemUniversalIdentifiers: string[];
- }> = {},
-) => ({
- id: OBJECT_ID,
- universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- isActive: true,
- nameSingular: 'ticket',
- shortcut: 'T',
- commandMenuItemUniversalIdentifiers: [DERIVED_UNIVERSAL_IDENTIFIER],
- ...overrides,
-});
-
-const buildNavigationCommand = (
- overrides: Partial<{
- universalIdentifier: string;
- isActive: boolean;
- conditionalAvailabilityExpression: string;
- hotKeys: string[] | null;
- payload: object;
- isSystemSideEffect: boolean;
- }> = {},
-) => ({
- universalIdentifier: DERIVED_UNIVERSAL_IDENTIFIER,
- engineComponentKey: EngineComponentKey.NAVIGATION,
- payload: { objectMetadataItemId: OBJECT_ID },
- isSystemSideEffect: true,
- isActive: true,
- conditionalAvailabilityExpression: 'targetObjectReadPermissions.ticket',
- hotKeys: ['G', 'T'],
- position: 7,
- ...overrides,
-});
-
-const buildArgs = ({
- updatedFlatObjectMetadata,
- existingFlatObjectMetadata = buildFlatObjectMetadata(),
- syncedFlatCommandMenuItems = [],
- pendingFlatCommandMenuItems = [],
-}: {
- updatedFlatObjectMetadata: ReturnType<typeof buildFlatObjectMetadata>;
- existingFlatObjectMetadata?: ReturnType<typeof buildFlatObjectMetadata>;
- syncedFlatCommandMenuItems?: object[];
- pendingFlatCommandMenuItems?: object[];
-}): BuildSideEffectsArgs<'objectMetadata'> =>
- ({
- flatEntity: updatedFlatObjectMetadata,
- allFlatEntityOperationRecordByMetadataName: {
- objectMetadata: {
- flatEntityToCreate: {},
- flatEntityToUpdate: {
- [updatedFlatObjectMetadata.universalIdentifier]:
- updatedFlatObjectMetadata,
- },
- flatEntityToDelete: {},
- },
- ...(pendingFlatCommandMenuItems.length > 0 && {
- commandMenuItem: {
- flatEntityToCreate: Object.fromEntries(
- pendingFlatCommandMenuItems.map((pendingFlatCommandMenuItem) => [
- (pendingFlatCommandMenuItem as { universalIdentifier: string })
- .universalIdentifier,
- pendingFlatCommandMenuItem,
- ]),
- ),
- flatEntityToUpdate: {},
- flatEntityToDelete: {},
- },
- }),
- } as unknown as AllFlatEntityOperationRecordByMetadataName,
- relatedFlatEntityMaps: {
- flatObjectMetadataMaps: {
- byUniversalIdentifier: {
- [existingFlatObjectMetadata.universalIdentifier]:
- existingFlatObjectMetadata,
- },
- },
- flatCommandMenuItemMaps: {
- byUniversalIdentifier: Object.fromEntries(
- syncedFlatCommandMenuItems.map((syncedFlatCommandMenuItem) => [
- (syncedFlatCommandMenuItem as { universalIdentifier: string })
- .universalIdentifier,
- syncedFlatCommandMenuItem,
- ]),
- ),
- },
- },
- context: {},
- }) as unknown as BuildSideEffectsArgs<'objectMetadata'>;
-
-describe('ObjectNavigationCommandOnUpdateSideEffectHandlerService', () => {
- const handler =
- new (ObjectNavigationCommandOnUpdateSideEffectHandlerService as unknown as new () => ObjectNavigationCommandOnUpdateSideEffectHandlerService)();
-
- const expectSuccess = (
- result: ReturnType<typeof handler.buildSideEffects>,
- ) => {
- if (result.status !== 'success') {
- throw new Error(`expected success, got ${result.status}`);
- }
-
- return result;
- };
-
- it('noops when a watched field changed but the recomputed command already matches the synced row', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata({ shortcut: 'U' }),
- syncedFlatCommandMenuItems: [
- buildNavigationCommand({ hotKeys: ['G', 'U'] }),
- ],
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('noops when none of isActive, nameSingular or shortcut changed', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata(),
- syncedFlatCommandMenuItems: [buildNavigationCommand()],
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('soft-disables the command when the object is deactivated', () => {
- const result = expectSuccess(
- handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata({
- isActive: false,
- }),
- syncedFlatCommandMenuItems: [buildNavigationCommand()],
- }),
- ),
- );
-
- const updated = result.operations.commandMenuItem?.flatEntityToUpdate ?? {};
-
- expect(Object.keys(updated)).toEqual([DERIVED_UNIVERSAL_IDENTIFIER]);
- expect(
- (updated[DERIVED_UNIVERSAL_IDENTIFIER] as { isActive: boolean }).isActive,
- ).toBe(false);
- });
-
- it('reactivates the command when the object is enabled', () => {
- const result = expectSuccess(
- handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata(),
- existingFlatObjectMetadata: buildFlatObjectMetadata({
- isActive: false,
- }),
- syncedFlatCommandMenuItems: [
- buildNavigationCommand({ isActive: false }),
- ],
- }),
- ),
- );
-
- const updated = result.operations.commandMenuItem?.flatEntityToUpdate ?? {};
-
- expect(
- (updated[DERIVED_UNIVERSAL_IDENTIFIER] as { isActive: boolean }).isActive,
- ).toBe(true);
- });
-
- it('recomputes conditionalAvailabilityExpression when nameSingular changes, keeping the identifier', () => {
- const result = expectSuccess(
- handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata({
- nameSingular: 'renamedTicket',
- }),
- syncedFlatCommandMenuItems: [buildNavigationCommand()],
- }),
- ),
- );
-
- const updated = result.operations.commandMenuItem?.flatEntityToUpdate ?? {};
-
- expect(Object.keys(updated)).toEqual([DERIVED_UNIVERSAL_IDENTIFIER]);
- expect(
- (
- updated[DERIVED_UNIVERSAL_IDENTIFIER] as {
- conditionalAvailabilityExpression: string;
- }
- ).conditionalAvailabilityExpression,
- ).toBe('targetObjectReadPermissions.renamedTicket');
- });
-
- it('recomputes hotKeys when the shortcut changes', () => {
- const result = expectSuccess(
- handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata({
- shortcut: 'K',
- }),
- syncedFlatCommandMenuItems: [buildNavigationCommand()],
- }),
- ),
- );
-
- const updated = result.operations.commandMenuItem?.flatEntityToUpdate ?? {};
-
- expect(
- (updated[DERIVED_UNIVERSAL_IDENTIFIER] as { hotKeys: string[] | null })
- .hotKeys,
- ).toEqual(['G', 'K']);
- });
-
- it('clears hotKeys when the shortcut is removed', () => {
- const result = expectSuccess(
- handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata({
- shortcut: null,
- }),
- syncedFlatCommandMenuItems: [buildNavigationCommand()],
- }),
- ),
- );
-
- const updated = result.operations.commandMenuItem?.flatEntityToUpdate ?? {};
-
- expect(
- (updated[DERIVED_UNIVERSAL_IDENTIFIER] as { hotKeys: string[] | null })
- .hotKeys,
- ).toBeNull();
- });
-
- it('noops on a command still holding a legacy identifier, until the 2-38 re-own converges it', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata({
- isActive: false,
- commandMenuItemUniversalIdentifiers: [LEGACY_UNIVERSAL_IDENTIFIER],
- }),
- existingFlatObjectMetadata: buildFlatObjectMetadata({
- commandMenuItemUniversalIdentifiers: [LEGACY_UNIVERSAL_IDENTIFIER],
- }),
- syncedFlatCommandMenuItems: [
- buildNavigationCommand({
- universalIdentifier: LEGACY_UNIVERSAL_IDENTIFIER,
- }),
- ],
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('noops when the object has no navigation command, as manifest-created objects do', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata(),
- existingFlatObjectMetadata: buildFlatObjectMetadata({
- isActive: false,
- }),
- syncedFlatCommandMenuItems: [],
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('leaves a caller-authored command targeting the same object alone, since it does not hold the derived identifier', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata({
- nameSingular: 'renamedTicket',
- commandMenuItemUniversalIdentifiers: ['app-authored-identifier'],
- }),
- existingFlatObjectMetadata: buildFlatObjectMetadata({
- commandMenuItemUniversalIdentifiers: ['app-authored-identifier'],
- }),
- syncedFlatCommandMenuItems: [
- buildNavigationCommand({
- universalIdentifier: 'app-authored-identifier',
- isSystemSideEffect: false,
- }),
- ],
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('noops when the derived identifier is held by a row the engine does not own', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata({
- nameSingular: 'renamedTicket',
- }),
- syncedFlatCommandMenuItems: [
- buildNavigationCommand({ isSystemSideEffect: false }),
- ],
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('fails when the existing object cannot be resolved', () => {
- const args = buildArgs({
- updatedFlatObjectMetadata: buildFlatObjectMetadata({ isActive: false }),
- });
-
- (
- args.relatedFlatEntityMaps as unknown as {
- flatObjectMetadataMaps: { byUniversalIdentifier: object };
- }
- ).flatObjectMetadataMaps.byUniversalIdentifier = {};
-
- const result = handler.buildSideEffects(args);
-
- expect(result.status).toBe('fail');
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-system-side-effects-on-delete-side-effect-handler.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-system-side-effects-on-delete-side-effect-handler.service.spec.ts
deleted file mode 100644
index 2120b144786..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/__tests__/object-system-side-effects-on-delete-side-effect-handler.service.spec.ts
+++ /dev/null
@@ -1,546 +0,0 @@
-import { EngineComponentKey } from 'src/engine/metadata-modules/command-menu-item/enums/engine-component-key.enum';
-import { ObjectSystemSideEffectsOnDeleteSideEffectHandlerService } from 'src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-system-side-effects-on-delete-side-effect-handler.service';
-import { type BuildSideEffectsArgs } from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
-
-const APPLICATION_UNIVERSAL_IDENTIFIER = 'a0a0a0a0-a0a0-4000-8000-000000000001';
-const OBJECT_ID = 'b0b0b0b0-b0b0-4000-8000-000000000001';
-const OBJECT_UNIVERSAL_IDENTIFIER = 'b1b2b3b4-b5b6-4000-8000-000000000001';
-const OTHER_OBJECT_UNIVERSAL_IDENTIFIER =
- 'c1c2c3c4-c5c6-4000-8000-000000000001';
-const OTHER_OBJECT_ID = 'b0b0b0b0-b0b0-4000-8000-000000000002';
-
-const SYSTEM_FIELD_UNIVERSAL_IDENTIFIER =
- 'd1d2d3d4-d5d6-4000-8000-000000000001';
-const AUTHOR_FIELD_UNIVERSAL_IDENTIFIER =
- 'd1d2d3d4-d5d6-4000-8000-000000000002';
-const FORWARD_FIELD_UNIVERSAL_IDENTIFIER =
- 'd1d2d3d4-d5d6-4000-8000-000000000003';
-const REVERSE_FIELD_UNIVERSAL_IDENTIFIER =
- 'd1d2d3d4-d5d6-4000-8000-000000000004';
-const GIN_INDEX_UNIVERSAL_IDENTIFIER = 'e1e2e3e4-e5e6-4000-8000-000000000001';
-const REVERSE_INDEX_UNIVERSAL_IDENTIFIER =
- 'e1e2e3e4-e5e6-4000-8000-000000000002';
-const SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER =
- 'f1f2f3f4-f5f6-4000-8000-000000000001';
-const INDEX_VIEW_UNIVERSAL_IDENTIFIER = 'a1a2a3a4-a5a6-4000-8000-000000000001';
-const INDEX_VIEW_FIELD_UNIVERSAL_IDENTIFIER =
- 'a1a2a3a4-a5a6-4000-8000-000000000002';
-const CALLER_VIEW_UNIVERSAL_IDENTIFIER = 'a1a2a3a4-a5a6-4000-8000-000000000003';
-const CALLER_VIEW_FIELD_UNIVERSAL_IDENTIFIER =
- 'a1a2a3a4-a5a6-4000-8000-000000000004';
-
-type FieldFixture = {
- universalIdentifier: string;
- isSystemSideEffect: boolean;
- objectMetadataUniversalIdentifier?: string;
- relationTargetFieldMetadataUniversalIdentifier?: string | null;
- viewFieldUniversalIdentifiers?: string[];
-};
-
-type ViewFixture = {
- universalIdentifier: string;
- isSystemSideEffect: boolean;
- viewFieldUniversalIdentifiers?: string[];
- viewFieldGroupUniversalIdentifiers?: string[];
-};
-
-const buildFieldMetadataMaps = (fields: FieldFixture[]) => ({
- byUniversalIdentifier: Object.fromEntries(
- fields.map((field) => [
- field.universalIdentifier,
- {
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- relationTargetFieldMetadataUniversalIdentifier: null,
- viewFieldUniversalIdentifiers: [],
- ...field,
- },
- ]),
- ),
-});
-
-const buildArgs = ({
- fieldUniversalIdentifiers = [],
- indexMetadataUniversalIdentifiers = [],
- searchFieldMetadataUniversalIdentifiers = [],
- viewUniversalIdentifiers = [],
- pageLayoutUniversalIdentifiers = [],
- commandMenuItemUniversalIdentifiers = [],
- relatedFlatEntityMaps = {},
-}: {
- fieldUniversalIdentifiers?: string[];
- indexMetadataUniversalIdentifiers?: string[];
- searchFieldMetadataUniversalIdentifiers?: string[];
- viewUniversalIdentifiers?: string[];
- pageLayoutUniversalIdentifiers?: string[];
- commandMenuItemUniversalIdentifiers?: string[];
- relatedFlatEntityMaps?: object;
-}): BuildSideEffectsArgs<'objectMetadata'> =>
- ({
- flatEntity: {
- id: OBJECT_ID,
- universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- fieldUniversalIdentifiers,
- indexMetadataUniversalIdentifiers,
- searchFieldMetadataUniversalIdentifiers,
- viewUniversalIdentifiers,
- pageLayoutUniversalIdentifiers,
- commandMenuItemUniversalIdentifiers,
- },
- allFlatEntityOperationRecordByMetadataName: {},
- relatedFlatEntityMaps: {
- flatObjectMetadataMaps: { byUniversalIdentifier: {} },
- flatFieldMetadataMaps: { byUniversalIdentifier: {} },
- flatIndexMaps: { byUniversalIdentifier: {} },
- flatSearchFieldMetadataMaps: { byUniversalIdentifier: {} },
- flatViewMaps: { byUniversalIdentifier: {} },
- flatViewFieldMaps: { byUniversalIdentifier: {} },
- flatViewFieldGroupMaps: { byUniversalIdentifier: {} },
- flatPageLayoutMaps: { byUniversalIdentifier: {} },
- flatPageLayoutTabMaps: { byUniversalIdentifier: {} },
- flatPageLayoutWidgetMaps: { byUniversalIdentifier: {} },
- flatCommandMenuItemMaps: { byUniversalIdentifier: {} },
- ...relatedFlatEntityMaps,
- },
- context: {},
- }) as unknown as BuildSideEffectsArgs<'objectMetadata'>;
-
-describe('ObjectSystemSideEffectsOnDeleteSideEffectHandlerService', () => {
- const handler =
- new (ObjectSystemSideEffectsOnDeleteSideEffectHandlerService as unknown as new () => ObjectSystemSideEffectsOnDeleteSideEffectHandlerService)();
-
- it('should cascade-delete engine-owned fields, indexes and searchFieldMetadata while leaving author fields untouched', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- fieldUniversalIdentifiers: [
- SYSTEM_FIELD_UNIVERSAL_IDENTIFIER,
- AUTHOR_FIELD_UNIVERSAL_IDENTIFIER,
- ],
- indexMetadataUniversalIdentifiers: [GIN_INDEX_UNIVERSAL_IDENTIFIER],
- searchFieldMetadataUniversalIdentifiers: [
- SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER,
- ],
- relatedFlatEntityMaps: {
- flatFieldMetadataMaps: buildFieldMetadataMaps([
- {
- universalIdentifier: SYSTEM_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- },
- {
- universalIdentifier: AUTHOR_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: false,
- },
- ]),
- flatIndexMaps: {
- byUniversalIdentifier: {
- [GIN_INDEX_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: GIN_INDEX_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- universalFlatIndexFieldMetadatas: [],
- },
- },
- },
- flatSearchFieldMetadataMaps: {
- byUniversalIdentifier: {
- [SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER,
- },
- },
- },
- },
- }),
- );
-
- expect(result.status).toBe('success');
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- const deletedFieldUniversalIdentifiers = Object.keys(
- result.operations.fieldMetadata?.flatEntityToDelete ?? {},
- );
-
- expect(deletedFieldUniversalIdentifiers).toEqual([
- SYSTEM_FIELD_UNIVERSAL_IDENTIFIER,
- ]);
- expect(deletedFieldUniversalIdentifiers).not.toContain(
- AUTHOR_FIELD_UNIVERSAL_IDENTIFIER,
- );
- expect(
- Object.keys(result.operations.index?.flatEntityToDelete ?? {}),
- ).toEqual([GIN_INDEX_UNIVERSAL_IDENTIFIER]);
- expect(
- Object.keys(
- result.operations.searchFieldMetadata?.flatEntityToDelete ?? {},
- ),
- ).toEqual([SEARCH_FIELD_METADATA_UNIVERSAL_IDENTIFIER]);
- });
-
- it('should cascade-delete the default-relation reverse morph field on a standard object and its join-column index', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- fieldUniversalIdentifiers: [FORWARD_FIELD_UNIVERSAL_IDENTIFIER],
- relatedFlatEntityMaps: {
- flatObjectMetadataMaps: {
- byUniversalIdentifier: {
- [OTHER_OBJECT_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
- indexMetadataUniversalIdentifiers: [
- REVERSE_INDEX_UNIVERSAL_IDENTIFIER,
- ],
- },
- },
- },
- flatFieldMetadataMaps: buildFieldMetadataMaps([
- {
- universalIdentifier: FORWARD_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- relationTargetFieldMetadataUniversalIdentifier:
- REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
- },
- {
- universalIdentifier: REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- objectMetadataUniversalIdentifier:
- OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
- },
- ]),
- flatIndexMaps: {
- byUniversalIdentifier: {
- [REVERSE_INDEX_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: REVERSE_INDEX_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- objectMetadataUniversalIdentifier:
- OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
- universalFlatIndexFieldMetadatas: [
- {
- fieldMetadataUniversalIdentifier:
- REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
- },
- ],
- },
- },
- },
- },
- }),
- );
-
- expect(result.status).toBe('success');
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- expect(
- Object.keys(result.operations.fieldMetadata?.flatEntityToDelete ?? {}),
- ).toEqual([
- FORWARD_FIELD_UNIVERSAL_IDENTIFIER,
- REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
- ]);
- expect(
- Object.keys(result.operations.index?.flatEntityToDelete ?? {}),
- ).toEqual([REVERSE_INDEX_UNIVERSAL_IDENTIFIER]);
- });
-
- it.each([false, true])(
- 'should delete a legacy reverse-field index, including the whole multi-column index (multiple fields: %s)',
- (hasMultipleFields) => {
- const result = handler.buildSideEffects(
- buildArgs({
- fieldUniversalIdentifiers: [FORWARD_FIELD_UNIVERSAL_IDENTIFIER],
- relatedFlatEntityMaps: {
- flatObjectMetadataMaps: {
- byUniversalIdentifier: {
- [OTHER_OBJECT_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
- indexMetadataUniversalIdentifiers: [
- REVERSE_INDEX_UNIVERSAL_IDENTIFIER,
- GIN_INDEX_UNIVERSAL_IDENTIFIER,
- ],
- },
- },
- },
- flatFieldMetadataMaps: buildFieldMetadataMaps([
- {
- universalIdentifier: FORWARD_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- relationTargetFieldMetadataUniversalIdentifier:
- REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
- },
- {
- universalIdentifier: REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- objectMetadataUniversalIdentifier:
- OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
- },
- ]),
- flatIndexMaps: {
- byUniversalIdentifier: {
- [REVERSE_INDEX_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: REVERSE_INDEX_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: false,
- applicationUniversalIdentifier: 'another-application',
- objectMetadataUniversalIdentifier:
- OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
- universalFlatIndexFieldMetadatas: [
- {
- fieldMetadataUniversalIdentifier:
- REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
- },
- ...(hasMultipleFields
- ? [
- {
- fieldMetadataUniversalIdentifier:
- AUTHOR_FIELD_UNIVERSAL_IDENTIFIER,
- },
- ]
- : []),
- ],
- },
- [GIN_INDEX_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: GIN_INDEX_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: false,
- objectMetadataUniversalIdentifier:
- OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
- universalFlatIndexFieldMetadatas: [
- {
- fieldMetadataUniversalIdentifier:
- AUTHOR_FIELD_UNIVERSAL_IDENTIFIER,
- },
- ],
- },
- },
- },
- },
- }),
- );
-
- expect(result.status).toBe('success');
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- expect(
- Object.keys(result.operations.index?.flatEntityToDelete ?? {}),
- ).toEqual([REVERSE_INDEX_UNIVERSAL_IDENTIFIER]);
- },
- );
-
- it('should not delete entities the object aggregators do not reference', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- relatedFlatEntityMaps: {
- flatFieldMetadataMaps: buildFieldMetadataMaps([
- {
- universalIdentifier: SYSTEM_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- objectMetadataUniversalIdentifier:
- OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
- },
- ]),
- },
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('should cascade-delete the engine-owned INDEX view and its view fields while leaving a caller-owned view untouched', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- viewUniversalIdentifiers: [
- INDEX_VIEW_UNIVERSAL_IDENTIFIER,
- CALLER_VIEW_UNIVERSAL_IDENTIFIER,
- ],
- relatedFlatEntityMaps: {
- flatViewMaps: {
- byUniversalIdentifier: Object.fromEntries(
- (
- [
- {
- universalIdentifier: INDEX_VIEW_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- viewFieldUniversalIdentifiers: [
- INDEX_VIEW_FIELD_UNIVERSAL_IDENTIFIER,
- ],
- },
- {
- universalIdentifier: CALLER_VIEW_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: false,
- viewFieldUniversalIdentifiers: [
- CALLER_VIEW_FIELD_UNIVERSAL_IDENTIFIER,
- ],
- },
- ] satisfies ViewFixture[]
- ).map((view) => [
- view.universalIdentifier,
- { viewFieldGroupUniversalIdentifiers: [], ...view },
- ]),
- ),
- },
- flatViewFieldMaps: {
- byUniversalIdentifier: {
- [INDEX_VIEW_FIELD_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: INDEX_VIEW_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- },
- [CALLER_VIEW_FIELD_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: CALLER_VIEW_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: false,
- },
- },
- },
- },
- }),
- );
-
- expect(result.status).toBe('success');
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- expect(
- Object.keys(result.operations.view?.flatEntityToDelete ?? {}),
- ).toEqual([INDEX_VIEW_UNIVERSAL_IDENTIFIER]);
- expect(
- Object.keys(result.operations.viewField?.flatEntityToDelete ?? {}),
- ).toEqual([INDEX_VIEW_FIELD_UNIVERSAL_IDENTIFIER]);
- });
-
- it('should cascade-delete a system view field of a deleted field even when it lives on another object view', () => {
- const OTHER_OBJECT_VIEW_FIELD_UNIVERSAL_IDENTIFIER =
- 'a1a2a3a4-a5a6-4000-8000-000000000006';
-
- const result = handler.buildSideEffects(
- buildArgs({
- fieldUniversalIdentifiers: [FORWARD_FIELD_UNIVERSAL_IDENTIFIER],
- relatedFlatEntityMaps: {
- flatFieldMetadataMaps: buildFieldMetadataMaps([
- {
- universalIdentifier: FORWARD_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- relationTargetFieldMetadataUniversalIdentifier:
- REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
- },
- {
- universalIdentifier: REVERSE_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- objectMetadataUniversalIdentifier:
- OTHER_OBJECT_UNIVERSAL_IDENTIFIER,
- viewFieldUniversalIdentifiers: [
- OTHER_OBJECT_VIEW_FIELD_UNIVERSAL_IDENTIFIER,
- ],
- },
- ]),
- flatViewFieldMaps: {
- byUniversalIdentifier: {
- [OTHER_OBJECT_VIEW_FIELD_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier:
- OTHER_OBJECT_VIEW_FIELD_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- },
- },
- },
- },
- }),
- );
-
- expect(result.status).toBe('success');
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- expect(result.operations.view).toBeUndefined();
- expect(
- Object.keys(result.operations.viewField?.flatEntityToDelete ?? {}),
- ).toEqual([OTHER_OBJECT_VIEW_FIELD_UNIVERSAL_IDENTIFIER]);
- });
-
- it('should cascade-delete the engine-owned navigation command from the object aggregator, whatever its identifier', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- commandMenuItemUniversalIdentifiers: [
- 'legacy-navigation-command-identifier',
- ],
- relatedFlatEntityMaps: {
- flatCommandMenuItemMaps: {
- byUniversalIdentifier: {
- 'legacy-navigation-command-identifier': {
- universalIdentifier: 'legacy-navigation-command-identifier',
- isSystemSideEffect: true,
- engineComponentKey: EngineComponentKey.NAVIGATION,
- payload: { objectMetadataItemId: OBJECT_ID },
- },
- },
- },
- },
- }),
- );
-
- expect(result.status).toBe('success');
-
- if (result.status !== 'success') {
- throw new Error('expected success');
- }
-
- expect(
- Object.keys(result.operations.commandMenuItem?.flatEntityToDelete ?? {}),
- ).toEqual(['legacy-navigation-command-identifier']);
- });
-
- it('should spare a non-system command menu item held by the object aggregator', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- commandMenuItemUniversalIdentifiers: [
- 'caller-authored-navigation-identifier',
- ],
- relatedFlatEntityMaps: {
- flatCommandMenuItemMaps: {
- byUniversalIdentifier: {
- 'caller-authored-navigation-identifier': {
- universalIdentifier: 'caller-authored-navigation-identifier',
- isSystemSideEffect: false,
- engineComponentKey: EngineComponentKey.NAVIGATION,
- payload: { objectMetadataItemId: OBJECT_ID },
- },
- },
- },
- },
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-
- it('should spare command menu items the object aggregator does not reference', () => {
- const result = handler.buildSideEffects(
- buildArgs({
- relatedFlatEntityMaps: {
- flatCommandMenuItemMaps: {
- byUniversalIdentifier: {
- 'go-to-settings-identifier': {
- universalIdentifier: 'go-to-settings-identifier',
- isSystemSideEffect: true,
- engineComponentKey: EngineComponentKey.NAVIGATION,
- payload: { path: '/settings/profile' },
- },
- 'other-object-navigation-identifier': {
- universalIdentifier: 'other-object-navigation-identifier',
- isSystemSideEffect: true,
- engineComponentKey: EngineComponentKey.NAVIGATION,
- payload: { objectMetadataItemId: OTHER_OBJECT_ID },
- },
- },
- },
- },
- }),
- );
-
- expect(result.status).toBe('noop');
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/page-layout/services/__tests__/page-layout-reset.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/page-layout/services/__tests__/page-layout-reset.service.spec.ts
deleted file mode 100644
index 16f637e4edf..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/page-layout/services/__tests__/page-layout-reset.service.spec.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import { Test } from '@nestjs/testing';
-
-import { PageLayoutType } from 'twenty-shared/types';
-
-import { ApplicationService } from 'src/engine/core-modules/application/application.service';
-import { createEmptyAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-all-flat-entity-maps.constant';
-import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
-import { addFlatEntityToFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/add-flat-entity-to-flat-entity-maps-or-throw.util';
-import { type FlatPageLayout } from 'src/engine/metadata-modules/flat-page-layout/types/flat-page-layout.type';
-import { PageLayoutResetService } from 'src/engine/metadata-modules/page-layout/services/page-layout-reset.service';
-import { ViewService } from 'src/engine/metadata-modules/view/services/view.service';
-import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';
-import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
-import { DashboardSyncService } from 'src/modules/dashboard-sync/services/dashboard-sync.service';
-
-const WORKSPACE_CUSTOM_APPLICATION_UNIVERSAL_IDENTIFIER =
- 'workspace-custom-application';
-
-describe('PageLayoutResetService', () => {
- it.each([
- {
- source: 'standard layout',
- applicationUniversalIdentifier:
- TWENTY_STANDARD_APPLICATION.universalIdentifier,
- isSystemSideEffect: false,
- },
- {
- source: 'app-provided layout',
- applicationUniversalIdentifier: 'installed-application',
- isSystemSideEffect: false,
- },
- {
- source: 'generated layout for a custom object',
- applicationUniversalIdentifier:
- WORKSPACE_CUSTOM_APPLICATION_UNIVERSAL_IDENTIFIER,
- isSystemSideEffect: true,
- },
- ])(
- 'restores the default pin state when resetting the $source',
- async ({ applicationUniversalIdentifier, isSystemSideEffect }) => {
- const layout: FlatPageLayout = {
- id: 'page-layout-id',
- universalIdentifier: 'page-layout-universal-identifier',
- applicationId: 'application-id',
- applicationUniversalIdentifier,
- workspaceId: 'workspace-id',
- name: 'Record page',
- type: PageLayoutType.RECORD_PAGE,
- objectMetadataId: null,
- objectMetadataUniversalIdentifier: null,
- defaultTabToFocusOnMobileAndSidePanelId: null,
- defaultTabToFocusOnMobileAndSidePanelUniversalIdentifier: null,
- navigationMenuItemIds: [],
- tabIds: [],
- navigationMenuItemUniversalIdentifiers: [],
- tabUniversalIdentifiers: [],
- isSystemSideEffect,
- isFirstTabPinned: false,
- createdAt: '2026-08-27T00:00:00.000Z',
- updatedAt: '2026-08-27T00:00:00.000Z',
- deletedAt: null,
- };
- const allFlatEntityMaps = createEmptyAllFlatEntityMaps();
-
- allFlatEntityMaps.flatPageLayoutMaps =
- addFlatEntityToFlatEntityMapsOrThrow({
- flatEntity: layout,
- flatEntityMaps: allFlatEntityMaps.flatPageLayoutMaps,
- });
-
- const validateBuildAndRunWorkspaceMigration = jest
- .fn()
- .mockResolvedValue({ status: 'success' });
- const module = await Test.createTestingModule({
- providers: [
- PageLayoutResetService,
- {
- provide: WorkspaceMigrationValidateBuildAndRunService,
- useValue: { validateBuildAndRunWorkspaceMigration },
- },
- {
- provide: WorkspaceManyOrAllFlatEntityMapsCacheService,
- useValue: {
- getOrRecomputeManyOrAllFlatEntityMaps: jest
- .fn()
- .mockResolvedValue(allFlatEntityMaps),
- },
- },
- {
- provide: ApplicationService,
- useValue: {
- findWorkspaceTwentyStandardAndCustomApplicationOrThrow: jest
- .fn()
- .mockResolvedValue({
- workspaceCustomFlatApplication: {
- universalIdentifier:
- WORKSPACE_CUSTOM_APPLICATION_UNIVERSAL_IDENTIFIER,
- },
- }),
- },
- },
- {
- provide: DashboardSyncService,
- useValue: {
- updateLinkedDashboardsUpdatedAtByPageLayoutId: jest.fn(),
- },
- },
- { provide: ViewService, useValue: {} },
- ],
- }).compile();
- const service = module.get(PageLayoutResetService);
-
- await service.resetPageLayoutToDefault({
- id: layout.id,
- workspaceId: layout.workspaceId,
- });
-
- expect(validateBuildAndRunWorkspaceMigration).toHaveBeenCalledWith(
- expect.objectContaining({
- allFlatEntityOperationByMetadataName: expect.objectContaining({
- pageLayout: {
- flatEntityToCreate: [],
- flatEntityToUpdate: [
- {
- ...layout,
- isFirstTabPinned: true,
- updatedAt: expect.any(String),
- },
- ],
- flatEntityToDelete: [],
- },
- }),
- }),
- );
-
- await module.close();
- },
- );
-});
diff --git a/packages/twenty-server/src/engine/subscriptions/__tests__/subscription.service.spec.ts b/packages/twenty-server/src/engine/subscriptions/__tests__/subscription.service.spec.ts
deleted file mode 100644
index adffa9a8aed..00000000000
--- a/packages/twenty-server/src/engine/subscriptions/__tests__/subscription.service.spec.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { type RedisClientService } from 'src/engine/core-modules/redis-client/redis-client.service';
-import { SubscriptionChannel } from 'src/engine/subscriptions/enums/subscription-channel.enum';
-import { SubscriptionService } from 'src/engine/subscriptions/subscription.service';
-
-const WORKSPACE_ID = 'workspace-id';
-
-const buildSubscriptionService = (publishedPayloads: number[]) => {
- const asyncIterator = jest.fn().mockReturnValue(
- (async function* () {
- yield* publishedPayloads;
- })(),
- );
-
- const subscriptionService = new SubscriptionService({
- getPubSubClient: () => ({ asyncIterator }),
- } as unknown as RedisClientService);
-
- return { asyncIterator, subscriptionService };
-};
-
-const collect = async <TValue>(iterator: AsyncIterableIterator<TValue>) => {
- const values: TValue[] = [];
-
- for await (const value of iterator) {
- values.push(value);
- }
-
- return values;
-};
-
-describe('SubscriptionService', () => {
- it('should receive every payload published on the workspace channel', async () => {
- const { asyncIterator, subscriptionService } = buildSubscriptionService([
- 1, 2, 3,
- ]);
-
- const iterator = await subscriptionService.subscribe<number>({
- channel: SubscriptionChannel.LOGIC_FUNCTION_LOGS_CHANNEL,
- workspaceId: WORKSPACE_ID,
- });
-
- expect(asyncIterator).toHaveBeenCalledWith(
- `${SubscriptionChannel.LOGIC_FUNCTION_LOGS_CHANNEL}:${WORKSPACE_ID}`,
- );
- expect(await collect(iterator)).toEqual([1, 2, 3]);
- });
-
- it('should map payloads and drop the ones mapped to undefined', async () => {
- const { subscriptionService } = buildSubscriptionService([1, 2, 3]);
-
- const iterator = await subscriptionService.subscribe<number>({
- channel: SubscriptionChannel.LOGIC_FUNCTION_LOGS_CHANNEL,
- workspaceId: WORKSPACE_ID,
- mapPayload: (payload) => (payload === 2 ? undefined : payload * 10),
- });
-
- expect(await collect(iterator)).toEqual([10, 30]);
- });
-});
diff --git a/packages/twenty-server/src/engine/workspace-cache/services/__tests__/workspace-cache.service.spec.ts b/packages/twenty-server/src/engine/workspace-cache/services/__tests__/workspace-cache.service.spec.ts
deleted file mode 100644
index 4f832a4508e..00000000000
--- a/packages/twenty-server/src/engine/workspace-cache/services/__tests__/workspace-cache.service.spec.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { type DiscoveryService, Reflector } from '@nestjs/core';
-
-import { type DataSource } from 'typeorm';
-
-import { WorkspaceCacheProvider } from 'src/engine/workspace-cache/interfaces/workspace-cache-provider.service';
-
-import { type CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
-import { type TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { WorkspaceCache } from 'src/engine/workspace-cache/decorators/workspace-cache.decorator';
-import { type WorkspaceCacheMetricsService } from 'src/engine/workspace-cache/services/workspace-cache-metrics.service';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-
-@WorkspaceCache('apiKeyRoleMap', { packingPonderation: 1 })
-class ApiKeyRoleMapTestProvider extends WorkspaceCacheProvider<
- Record<string, string>
-> {
- computeForCache(): Record<string, string> {
- return {};
- }
-}
-
-const WORKSPACE_1_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
-const WORKSPACE_2_ID = '3b8e6458-5fc1-4e63-8563-008ccddaa6db';
-
-const buildCacheKey = (workspaceId: string, suffix: 'hash' | 'data') =>
- `apiKeyRoleMap:${workspaceId}:${suffix}`;
-
-describe('WorkspaceCacheService', () => {
- const redisEntries = new Map<string, unknown>([
- [buildCacheKey(WORKSPACE_1_ID, 'hash'), 'hash-1'],
- [buildCacheKey(WORKSPACE_1_ID, 'data'), { 'api-key-1': 'role-1' }],
- [buildCacheKey(WORKSPACE_2_ID, 'hash'), 'hash-2'],
- [buildCacheKey(WORKSPACE_2_ID, 'data'), { 'api-key-2': 'role-2' }],
- ]);
-
- let cacheStorage: jest.Mocked<
- Pick<CacheStorageService, 'mget' | 'mset' | 'mdel' | 'setIfAbsent'>
- >;
- let service: WorkspaceCacheService;
-
- const countDataFetches = (workspaceId: string) =>
- cacheStorage.mget.mock.calls.filter(([keys]) =>
- keys.includes(buildCacheKey(workspaceId, 'data')),
- ).length;
-
- beforeEach(async () => {
- jest.useFakeTimers();
-
- cacheStorage = {
- mget: jest.fn(async (keys: string[]) =>
- keys.map((key) => redisEntries.get(key)),
- ),
- mset: jest.fn(),
- mdel: jest.fn(),
- setIfAbsent: jest.fn(),
- } as unknown as typeof cacheStorage;
-
- const discoveryService = {
- getProviders: () => [{ instance: new ApiKeyRoleMapTestProvider() }],
- } as unknown as DiscoveryService;
- const cacheMetricsService = {
- start: jest.fn(),
- stop: jest.fn(),
- recordRecompute: jest.fn(),
- recordRedisWrite: jest.fn(),
- recordEviction: jest.fn(),
- recordPackingRun: jest.fn(),
- recordUnpacking: jest.fn(),
- } as unknown as WorkspaceCacheMetricsService;
- const twentyConfigService = {
- get: jest.fn().mockReturnValue(3600),
- } as unknown as TwentyConfigService;
-
- service = new WorkspaceCacheService(
- cacheStorage as unknown as CacheStorageService,
- {} as DataSource,
- discoveryService,
- new Reflector(),
- cacheMetricsService,
- twentyConfigService,
- );
-
- await service.onModuleInit();
- });
-
- afterEach(() => {
- service.onModuleDestroy();
- jest.useRealTimers();
- });
-
- describe('evictWorkspaceFromLocalCache', () => {
- it('drops the local copy so the next read fetches the data again', async () => {
- await service.getOrRecompute(WORKSPACE_1_ID, ['apiKeyRoleMap']);
-
- // Past the memoizer and local TTLs, a read only re-checks the hash.
- jest.setSystemTime(Date.now() + 11_000);
-
- await service.getOrRecompute(WORKSPACE_1_ID, ['apiKeyRoleMap']);
-
- expect(countDataFetches(WORKSPACE_1_ID)).toBe(1);
-
- await service.evictWorkspaceFromLocalCache(WORKSPACE_1_ID);
-
- const { apiKeyRoleMap } = await service.getOrRecompute(WORKSPACE_1_ID, [
- 'apiKeyRoleMap',
- ]);
-
- expect(apiKeyRoleMap).toEqual({ 'api-key-1': 'role-1' });
- expect(countDataFetches(WORKSPACE_1_ID)).toBe(2);
- });
-
- it('leaves Redis and the other workspaces untouched', async () => {
- await service.getOrRecompute(WORKSPACE_1_ID, ['apiKeyRoleMap']);
- await service.getOrRecompute(WORKSPACE_2_ID, ['apiKeyRoleMap']);
-
- await service.evictWorkspaceFromLocalCache(WORKSPACE_1_ID);
-
- jest.setSystemTime(Date.now() + 11_000);
-
- await service.getOrRecompute(WORKSPACE_2_ID, ['apiKeyRoleMap']);
-
- expect(countDataFetches(WORKSPACE_2_ID)).toBe(1);
- expect(cacheStorage.mdel).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-command-menu-item-validator.service.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-command-menu-item-validator.service.spec.ts
deleted file mode 100644
index d472354a4e9..00000000000
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-command-menu-item-validator.service.spec.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { EngineComponentKey } from 'src/engine/metadata-modules/command-menu-item/enums/engine-component-key.enum';
-import { buildObjectNavigationUniversalFlatCommandMenuItem } from 'src/engine/metadata-modules/flat-command-menu-item/utils/build-object-navigation-universal-flat-command-menu-item.util';
-import { FlatCommandMenuItemValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-command-menu-item-validator.service';
-
-type CreationArgs = Parameters<
- FlatCommandMenuItemValidatorService['validateFlatCommandMenuItemCreation']
->[0];
-
-const buildCommand = (
- overrides: Partial<CreationArgs['flatEntityToValidate']> = {},
-) => ({
- ...buildObjectNavigationUniversalFlatCommandMenuItem({
- objectMetadata: {
- id: 'object-id',
- universalIdentifier: 'object-identifier',
- nameSingular: 'person',
- shortcut: null,
- isActive: true,
- },
- applicationUniversalIdentifier: '11111111-1111-4111-8111-111111111111',
- position: 0,
- now: '2026-09-16T00:00:00Z',
- }),
- engineComponentKey: EngineComponentKey.TRIGGER_WORKFLOW_VERSION,
- navigationTargetObjectMetadataUniversalIdentifier: null,
- ...overrides,
-});
-
-const buildArgs = (
- overrides: Partial<CreationArgs['flatEntityToValidate']> = {},
-) =>
- ({
- flatEntityToValidate: buildCommand(overrides),
- optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
- flatObjectMetadataMaps: { byUniversalIdentifier: {} },
- flatCommandMenuItemMaps: { byUniversalIdentifier: {} },
- },
- }) as CreationArgs;
-
-describe('workflow command menu validation', () => {
- const service = new FlatCommandMenuItemValidatorService();
-
- it.each([
- { workflowVersionId: 'workspace-version', coreWorkflowVersionId: null },
- { workflowVersionId: null, coreWorkflowVersionId: 'core-version' },
- {
- workflowVersionId: 'workspace-version',
- coreWorkflowVersionId: 'core-version',
- },
- ])('accepts legacy, core and dual-keyed triggers: %j', (identifiers) => {
- expect(
- service.validateFlatCommandMenuItemCreation(buildArgs(identifiers))
- .errors,
- ).toEqual([]);
- });
-
- it('rejects a trigger without a definition ID', () => {
- expect(
- service.validateFlatCommandMenuItemCreation(buildArgs()).errors,
- ).toHaveLength(1);
- });
-
- it('rejects workflow IDs on unrelated engine commands', () => {
- expect(
- service.validateFlatCommandMenuItemCreation(
- buildArgs({
- engineComponentKey: EngineComponentKey.DELETE_RECORDS,
- coreWorkflowVersionId: 'core-version',
- }),
- ).errors,
- ).toHaveLength(1);
- });
-
- it('allows renaming an existing core-only trigger', () => {
- const command = buildCommand({ coreWorkflowVersionId: 'core-version' });
- const args = {
- universalIdentifier: command.universalIdentifier,
- flatEntityUpdate: { label: 'Renamed' },
- optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
- flatObjectMetadataMaps: { byUniversalIdentifier: {} },
- flatCommandMenuItemMaps: {
- byUniversalIdentifier: { [command.universalIdentifier]: command },
- },
- },
- } as Parameters<
- FlatCommandMenuItemValidatorService['validateFlatCommandMenuItemUpdate']
- >[0];
- expect(service.validateFlatCommandMenuItemUpdate(args).errors).toEqual([]);
- });
-});
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-index-metadata-validator.service.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-index-metadata-validator.service.spec.ts
deleted file mode 100644
index 3596524bc77..00000000000
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-index-metadata-validator.service.spec.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { FieldMetadataType, RelationType } from 'twenty-shared/types';
-
-import { FlatIndexValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-index-metadata-validator.service';
-
-const INDEX_UNIVERSAL_IDENTIFIER = '11111111-1111-4111-8111-111111111111';
-const OBJECT_UNIVERSAL_IDENTIFIER = '22222222-2222-4222-8222-222222222222';
-const FIELD_UNIVERSAL_IDENTIFIER = '33333333-3333-4333-8333-333333333333';
-
-const buildCreationArgs = (relationType: RelationType) =>
- ({
- flatEntityToValidate: {
- universalIdentifier: INDEX_UNIVERSAL_IDENTIFIER,
- name: 'targetUniqueIndex',
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- isUnique: true,
- universalFlatIndexFieldMetadatas: [
- {
- indexMetadataUniversalIdentifier: INDEX_UNIVERSAL_IDENTIFIER,
- fieldMetadataUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
- },
- ],
- },
- optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
- flatIndexMaps: { byUniversalIdentifier: {} },
- flatObjectMetadataMaps: {
- byUniversalIdentifier: {
- [OBJECT_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- },
- },
- },
- flatFieldMetadataMaps: {
- byUniversalIdentifier: {
- [FIELD_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- name: 'targetPerson',
- type: FieldMetadataType.MORPH_RELATION,
- defaultValue: null,
- isUnique: false,
- universalSettings: { relationType },
- },
- },
- },
- },
- }) as unknown as Parameters<
- FlatIndexValidatorService['validateFlatIndexCreation']
- >[0];
-
-describe('FlatIndexValidatorService', () => {
- const service = new FlatIndexValidatorService();
-
- it('accepts a unique index on a many-to-one morph member join column', () => {
- const result = service.validateFlatIndexCreation(
- buildCreationArgs(RelationType.MANY_TO_ONE),
- );
-
- expect(result.errors).toEqual([]);
- });
-
- it('rejects a unique index on an inverse morph relation', () => {
- const result = service.validateFlatIndexCreation(
- buildCreationArgs(RelationType.ONE_TO_MANY),
- );
-
- expect(result.errors).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- message:
- 'Unique index cannot be created for field targetPerson of type MORPH_RELATION',
- }),
- ]),
- );
- });
-});
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-row-level-permission-predicate-validator.service.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-row-level-permission-predicate-validator.service.spec.ts
deleted file mode 100644
index ba9f59fce8e..00000000000
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-row-level-permission-predicate-validator.service.spec.ts
+++ /dev/null
@@ -1,420 +0,0 @@
-import {
- FieldMetadataType,
- RowLevelPermissionPredicateOperand,
-} from 'twenty-shared/types';
-
-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
-
-import { RelationType } from 'src/engine/metadata-modules/field-metadata/interfaces/relation-type.interface';
-import { FlatRowLevelPermissionPredicateValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-row-level-permission-predicate-validator.service';
-
-const PREDICATE_UNIVERSAL_IDENTIFIER = '00000000-0000-4000-8000-0000000000a1';
-const FIELD_UNIVERSAL_IDENTIFIER = '00000000-0000-4000-8000-0000000000b1';
-const OBJECT_UNIVERSAL_IDENTIFIER = '00000000-0000-4000-8000-0000000000c1';
-const ROLE_UNIVERSAL_IDENTIFIER = '00000000-0000-4000-8000-0000000000d1';
-const WORKSPACE_MEMBER_ID_FIELD_UNIVERSAL_IDENTIFIER =
- '00000000-0000-4000-8000-0000000000b2';
-const WORKSPACE_MEMBER_RELATION_FIELD_UNIVERSAL_IDENTIFIER =
- '00000000-0000-4000-8000-0000000000b3';
-const WORKSPACE_MEMBER_OTHER_RELATION_FIELD_UNIVERSAL_IDENTIFIER =
- '00000000-0000-4000-8000-0000000000b4';
-const ONE_TO_MANY_FIELD_UNIVERSAL_IDENTIFIER =
- '00000000-0000-4000-8000-0000000000b5';
-const WORKSPACE_MEMBER_MORPH_FIELD_UNIVERSAL_IDENTIFIER =
- '00000000-0000-4000-8000-0000000000b6';
-const RELATION_TARGET_OBJECT_UNIVERSAL_IDENTIFIER =
- '00000000-0000-4000-8000-0000000000c2';
-const OTHER_RELATION_TARGET_OBJECT_UNIVERSAL_IDENTIFIER =
- '00000000-0000-4000-8000-0000000000c3';
-const RECORD_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
-
-const mapsFrom = (
- entities: { universalIdentifier: string; [key: string]: unknown }[],
-) => ({
- byUniversalIdentifier: Object.fromEntries(
- entities.map((entity) => [entity.universalIdentifier, entity]),
- ),
-});
-
-const buildPredicate = ({
- operand,
- value,
- workspaceMemberFieldMetadataUniversalIdentifier = null,
- fieldMetadataUniversalIdentifier = FIELD_UNIVERSAL_IDENTIFIER,
-}: {
- operand: RowLevelPermissionPredicateOperand;
- value: unknown;
- workspaceMemberFieldMetadataUniversalIdentifier?: string | null;
- fieldMetadataUniversalIdentifier?: string;
-}) => ({
- universalIdentifier: PREDICATE_UNIVERSAL_IDENTIFIER,
- fieldMetadataUniversalIdentifier,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- roleUniversalIdentifier: ROLE_UNIVERSAL_IDENTIFIER,
- rowLevelPermissionPredicateGroupUniversalIdentifier: null,
- operand,
- value,
- subFieldName: null,
- workspaceMemberFieldMetadataUniversalIdentifier,
-});
-
-const relatedMaps = (fieldType: FieldMetadataType) => ({
- flatRowLevelPermissionPredicateGroupMaps: mapsFrom([]),
- flatFieldMetadataMaps: mapsFrom([
- {
- universalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
- type: fieldType,
- name: 'accountOwner',
- label: 'Account Owner',
- universalSettings: { relationType: RelationType.MANY_TO_ONE },
- relationTargetObjectMetadataUniversalIdentifier:
- RELATION_TARGET_OBJECT_UNIVERSAL_IDENTIFIER,
- },
- {
- universalIdentifier: ONE_TO_MANY_FIELD_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.RELATION,
- name: 'people',
- label: 'People',
- universalSettings: { relationType: RelationType.ONE_TO_MANY },
- relationTargetObjectMetadataUniversalIdentifier:
- RELATION_TARGET_OBJECT_UNIVERSAL_IDENTIFIER,
- },
- {
- universalIdentifier: WORKSPACE_MEMBER_MORPH_FIELD_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.MORPH_RELATION,
- name: 'target',
- label: 'Target',
- universalSettings: { relationType: RelationType.MANY_TO_ONE },
- relationTargetObjectMetadataUniversalIdentifier:
- RELATION_TARGET_OBJECT_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier:
- STANDARD_OBJECTS.workspaceMember.universalIdentifier,
- },
- {
- universalIdentifier: WORKSPACE_MEMBER_ID_FIELD_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.UUID,
- name: 'id',
- label: 'Id',
- objectMetadataUniversalIdentifier:
- STANDARD_OBJECTS.workspaceMember.universalIdentifier,
- },
- {
- universalIdentifier: WORKSPACE_MEMBER_RELATION_FIELD_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.RELATION,
- name: 'region',
- label: 'Region',
- universalSettings: { relationType: RelationType.MANY_TO_ONE },
- relationTargetObjectMetadataUniversalIdentifier:
- RELATION_TARGET_OBJECT_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier:
- STANDARD_OBJECTS.workspaceMember.universalIdentifier,
- },
- {
- universalIdentifier:
- WORKSPACE_MEMBER_OTHER_RELATION_FIELD_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.RELATION,
- name: 'team',
- label: 'Team',
- universalSettings: { relationType: RelationType.MANY_TO_ONE },
- relationTargetObjectMetadataUniversalIdentifier:
- OTHER_RELATION_TARGET_OBJECT_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier:
- STANDARD_OBJECTS.workspaceMember.universalIdentifier,
- },
- ]),
- flatObjectMetadataMaps: mapsFrom([
- { universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER },
- ]),
- flatRoleMaps: mapsFrom([{ universalIdentifier: ROLE_UNIVERSAL_IDENTIFIER }]),
-});
-
-const buildCreationArgs = ({
- fieldType,
- operand,
- value,
- workspaceMemberFieldMetadataUniversalIdentifier = null,
- fieldMetadataUniversalIdentifier,
-}: {
- fieldType: FieldMetadataType;
- operand: RowLevelPermissionPredicateOperand;
- value: unknown;
- workspaceMemberFieldMetadataUniversalIdentifier?: string | null;
- fieldMetadataUniversalIdentifier?: string;
-}) =>
- ({
- flatEntityToValidate: buildPredicate({
- operand,
- value,
- workspaceMemberFieldMetadataUniversalIdentifier,
- fieldMetadataUniversalIdentifier,
- }),
- optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
- flatRowLevelPermissionPredicateMaps: mapsFrom([]),
- ...relatedMaps(fieldType),
- },
- }) as unknown as Parameters<
- FlatRowLevelPermissionPredicateValidatorService['validateFlatRowLevelPermissionPredicateCreation']
- >[0];
-
-const buildUpdateArgs = ({
- fieldType,
- operand,
- value,
- flatEntityUpdate,
- workspaceMemberFieldMetadataUniversalIdentifier = null,
-}: {
- fieldType: FieldMetadataType;
- operand: RowLevelPermissionPredicateOperand;
- value: unknown;
- flatEntityUpdate: Record<string, unknown>;
- workspaceMemberFieldMetadataUniversalIdentifier?: string | null;
-}) =>
- ({
- universalIdentifier: PREDICATE_UNIVERSAL_IDENTIFIER,
- flatEntityUpdate,
- optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
- flatRowLevelPermissionPredicateMaps: mapsFrom([
- buildPredicate({
- operand,
- value,
- workspaceMemberFieldMetadataUniversalIdentifier,
- }),
- ]),
- ...relatedMaps(fieldType),
- },
- }) as unknown as Parameters<
- FlatRowLevelPermissionPredicateValidatorService['validateFlatRowLevelPermissionPredicateUpdate']
- >[0];
-
-describe('FlatRowLevelPermissionPredicateValidatorService', () => {
- let service: FlatRowLevelPermissionPredicateValidatorService;
-
- beforeEach(() => {
- service = new FlatRowLevelPermissionPredicateValidatorService();
- });
-
- describe('creation', () => {
- it('should reject a relation value that resolves to no record id', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value: { direction: 'NEXT', amount: 30, unit: 'DAY' },
- }),
- );
-
- expect(result.errors).toHaveLength(1);
- });
-
- it('should reject the object form of a relative date predicate', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.DATE,
- operand: RowLevelPermissionPredicateOperand.IS_RELATIVE,
- value: { direction: 'NEXT', amount: 30, unit: 'DAY' },
- }),
- );
-
- expect(result.errors).toHaveLength(1);
- expect(result.errors[0].message).toContain('NEXT_30_DAY');
- });
-
- it('should accept a valid predicate value', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value: { selectedRecordIds: [RECORD_ID] },
- }),
- );
-
- expect(result.errors).toEqual([]);
- });
-
- it.each([[''], ['[]'], [[]]])(
- 'should reject %p on an operand that expects a value',
- (value) => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value,
- }),
- );
-
- expect(result.errors).toHaveLength(1);
- expect(result.errors[0].message).toContain('requires a value');
- },
- );
-
- it.each([[null], [undefined]])(
- 'should accept %p, a predicate whose value is not filled in yet',
- (value) => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.TEXT,
- operand: RowLevelPermissionPredicateOperand.CONTAINS,
- value,
- }),
- );
-
- expect(result.errors).toEqual([]);
- },
- );
-
- it('should accept a value-less operand with no value', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS_NOT_EMPTY,
- value: null,
- }),
- );
-
- expect(result.errors).toEqual([]);
- });
-
- it('should skip validation when the value is resolved from the workspace member', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value: null,
- workspaceMemberFieldMetadataUniversalIdentifier:
- WORKSPACE_MEMBER_ID_FIELD_UNIVERSAL_IDENTIFIER,
- }),
- );
-
- expect(result.errors).toEqual([]);
- });
-
- it('should accept two relations pointing to the same object', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value: null,
- workspaceMemberFieldMetadataUniversalIdentifier:
- WORKSPACE_MEMBER_RELATION_FIELD_UNIVERSAL_IDENTIFIER,
- }),
- );
-
- expect(result.errors).toEqual([]);
- });
-
- it('should reject two relations pointing to different objects', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value: null,
- workspaceMemberFieldMetadataUniversalIdentifier:
- WORKSPACE_MEMBER_OTHER_RELATION_FIELD_UNIVERSAL_IDENTIFIER,
- }),
- );
-
- expect(result.errors).toHaveLength(1);
- expect(result.errors[0].message).toContain(
- 'must be relations pointing to the same object',
- );
- });
-
- it('should reject a member field that belongs to another object', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value: null,
- workspaceMemberFieldMetadataUniversalIdentifier:
- FIELD_UNIVERSAL_IDENTIFIER,
- }),
- );
-
- expect(result.errors).toHaveLength(1);
- expect(result.errors[0].message).toContain(
- 'is not a field of the workspaceMember object',
- );
- });
-
- it('should reject a morph relation on the workspace member', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value: null,
- workspaceMemberFieldMetadataUniversalIdentifier:
- WORKSPACE_MEMBER_MORPH_FIELD_UNIVERSAL_IDENTIFIER,
- }),
- );
-
- expect(result.errors).toHaveLength(1);
- expect(result.errors[0].message).toContain(
- 'is not a many-to-one relation, its value cannot be resolved',
- );
- });
-
- it('should reject a record field that is not a many-to-one relation', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value: null,
- fieldMetadataUniversalIdentifier:
- ONE_TO_MANY_FIELD_UNIVERSAL_IDENTIFIER,
- workspaceMemberFieldMetadataUniversalIdentifier:
- WORKSPACE_MEMBER_RELATION_FIELD_UNIVERSAL_IDENTIFIER,
- }),
- );
-
- expect(result.errors).toHaveLength(1);
- expect(result.errors[0].message).toContain('has no join column');
- });
-
- it('should reject an operand the relation query filter cannot express', () => {
- const result = service.validateFlatRowLevelPermissionPredicateCreation(
- buildCreationArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.CONTAINS,
- value: null,
- workspaceMemberFieldMetadataUniversalIdentifier:
- WORKSPACE_MEMBER_RELATION_FIELD_UNIVERSAL_IDENTIFIER,
- }),
- );
-
- expect(result.errors).toHaveLength(1);
- expect(result.errors[0].message).toContain('use IS or IS_NOT');
- });
- });
-
- describe('update', () => {
- it('should validate the retained value when workspace member resolution is cleared', () => {
- const result = service.validateFlatRowLevelPermissionPredicateUpdate(
- buildUpdateArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value: { direction: 'NEXT', amount: 30, unit: 'DAY' },
- workspaceMemberFieldMetadataUniversalIdentifier:
- FIELD_UNIVERSAL_IDENTIFIER,
- flatEntityUpdate: {
- workspaceMemberFieldMetadataUniversalIdentifier: null,
- },
- }),
- );
-
- expect(result.errors).toHaveLength(1);
- });
-
- it('should not validate the value when it is not part of the update', () => {
- const result = service.validateFlatRowLevelPermissionPredicateUpdate(
- buildUpdateArgs({
- fieldType: FieldMetadataType.RELATION,
- operand: RowLevelPermissionPredicateOperand.IS,
- value: { direction: 'NEXT', amount: 30, unit: 'DAY' },
- flatEntityUpdate: { positionInRowLevelPermissionPredicateGroup: 2 },
- }),
- );
-
- expect(result.errors).toEqual([]);
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-settings-menu-item-validator.service.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-settings-menu-item-validator.service.spec.ts
deleted file mode 100644
index 7613e24a8a4..00000000000
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-settings-menu-item-validator.service.spec.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import { SettingsMenuItemExceptionCode } from 'src/engine/metadata-modules/settings-menu-item/settings-menu-item.exception';
-import { FlatSettingsMenuItemValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-settings-menu-item-validator.service';
-
-type CreationArgs = Parameters<
- FlatSettingsMenuItemValidatorService['validateFlatSettingsMenuItemCreation']
->[0];
-
-const APPLICATION_UNIVERSAL_IDENTIFIER = '11111111-1111-4111-8111-111111111111';
-const FRONT_COMPONENT_UNIVERSAL_IDENTIFIER =
- '22222222-2222-4222-8222-222222222222';
-
-const buildSettingsMenuItem = ({
- universalIdentifier,
- position,
- scope = 'WORKSPACE',
-}: {
- universalIdentifier: string;
- position: number;
- scope?: string;
-}) => ({
- universalIdentifier,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- frontComponentUniversalIdentifier: FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
- title: `Item ${universalIdentifier}`,
- icon: 'IconRefresh',
- position,
- scope,
-});
-
-const buildMaps = (items: ReturnType<typeof buildSettingsMenuItem>[]) => ({
- byUniversalIdentifier: Object.fromEntries(
- items.map((item) => [item.universalIdentifier, item]),
- ),
-});
-
-const buildArgs = ({
- itemToCreate,
- optimisticItems,
- finalItems,
- remainingItems = [],
-}: {
- itemToCreate: ReturnType<typeof buildSettingsMenuItem>;
- optimisticItems: ReturnType<typeof buildSettingsMenuItem>[];
- finalItems: ReturnType<typeof buildSettingsMenuItem>[];
- remainingItems?: ReturnType<typeof buildSettingsMenuItem>[];
-}) =>
- ({
- flatEntityToValidate: itemToCreate,
- remainingFlatEntityMapsToValidate: buildMaps(remainingItems),
- optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
- flatSettingsMenuItemMaps: buildMaps(optimisticItems),
- flatFrontComponentMaps: {
- byUniversalIdentifier: {
- [FRONT_COMPONENT_UNIVERSAL_IDENTIFIER]: {
- universalIdentifier: FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- },
- },
- },
- },
- finalFlatEntityMaps: buildMaps(finalItems),
- }) as unknown as CreationArgs;
-
-describe('settings menu item position collision on creation', () => {
- const service = new FlatSettingsMenuItemValidatorService();
-
- // The positions to compare against are the ones the migration ends on, not the
- // ones it started from: an item moved out of the way in the same sync has already
- // freed its position by the time the migration runs.
- it('should accept a position freed by another item moved in the same migration', () => {
- const itemBeforeMove = buildSettingsMenuItem({
- universalIdentifier: 'item-moved',
- position: 1,
- });
- const itemAfterMove = buildSettingsMenuItem({
- universalIdentifier: 'item-moved',
- position: 2,
- });
- const itemToCreate = buildSettingsMenuItem({
- universalIdentifier: 'item-new',
- position: 1,
- });
-
- const { errors } = service.validateFlatSettingsMenuItemCreation(
- buildArgs({
- itemToCreate,
- optimisticItems: [itemBeforeMove],
- finalItems: [itemAfterMove, itemToCreate],
- }),
- );
-
- expect(errors).toEqual([]);
- });
-
- it('should reject a position another item still holds in the final state', () => {
- const stayingItem = buildSettingsMenuItem({
- universalIdentifier: 'item-staying',
- position: 1,
- });
- const itemToCreate = buildSettingsMenuItem({
- universalIdentifier: 'item-new',
- position: 1,
- });
-
- const { errors } = service.validateFlatSettingsMenuItemCreation(
- buildArgs({
- itemToCreate,
- optimisticItems: [stayingItem],
- finalItems: [stayingItem, itemToCreate],
- }),
- );
-
- expect(errors).toHaveLength(1);
- expect(errors[0].code).toBe(
- SettingsMenuItemExceptionCode.SETTINGS_MENU_ITEM_POSITION_ALREADY_TAKEN,
- );
- });
-
- // Both items are in the final state from the start, so comparing against it
- // naively reports the clash twice; the sync must surface it once.
- it('should report a position shared by two new items once, on the later one', () => {
- const firstItem = buildSettingsMenuItem({
- universalIdentifier: 'item-first',
- position: 1,
- });
- const secondItem = buildSettingsMenuItem({
- universalIdentifier: 'item-second',
- position: 1,
- });
- const finalItems = [firstItem, secondItem];
-
- const firstResult = service.validateFlatSettingsMenuItemCreation(
- buildArgs({
- itemToCreate: firstItem,
- optimisticItems: [],
- finalItems,
- remainingItems: [secondItem],
- }),
- );
- const secondResult = service.validateFlatSettingsMenuItemCreation(
- buildArgs({
- itemToCreate: secondItem,
- optimisticItems: [firstItem],
- finalItems,
- remainingItems: [],
- }),
- );
-
- expect(firstResult.errors).toEqual([]);
- expect(secondResult.errors).toHaveLength(1);
- expect(secondResult.errors[0].code).toBe(
- SettingsMenuItemExceptionCode.SETTINGS_MENU_ITEM_POSITION_ALREADY_TAKEN,
- );
- });
-});
-
-describe('settings menu item input validation on creation', () => {
- const service = new FlatSettingsMenuItemValidatorService();
-
- it('should accept an item whose scope and position are both usable', () => {
- const itemToCreate = buildSettingsMenuItem({
- universalIdentifier: 'item-new',
- position: 1,
- });
-
- const { errors } = service.validateFlatSettingsMenuItemCreation(
- buildArgs({
- itemToCreate,
- optimisticItems: [],
- finalItems: [itemToCreate],
- }),
- );
-
- expect(errors).toEqual([]);
- });
-
- it('should reject a scope the database enum does not accept', () => {
- const itemToCreate = buildSettingsMenuItem({
- universalIdentifier: 'item-new',
- position: 1,
- scope: 'GLOBAL',
- });
-
- const { errors } = service.validateFlatSettingsMenuItemCreation(
- buildArgs({
- itemToCreate,
- optimisticItems: [],
- finalItems: [itemToCreate],
- }),
- );
-
- expect(errors).toHaveLength(1);
- expect(errors[0].code).toBe(
- SettingsMenuItemExceptionCode.INVALID_SETTINGS_MENU_ITEM_INPUT,
- );
- expect(errors[0].message).toContain('scope');
- });
-
- it('should reject a position that is not a number', () => {
- const itemToCreate = {
- ...buildSettingsMenuItem({
- universalIdentifier: 'item-new',
- position: 1,
- }),
- position: '1' as unknown as number,
- };
-
- const { errors } = service.validateFlatSettingsMenuItemCreation(
- buildArgs({
- itemToCreate,
- optimisticItems: [],
- finalItems: [itemToCreate],
- }),
- );
-
- expect(errors).toHaveLength(1);
- expect(errors[0].code).toBe(
- SettingsMenuItemExceptionCode.INVALID_SETTINGS_MENU_ITEM_INPUT,
- );
- expect(errors[0].message).toContain('position must be a number');
- });
-});
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-timeline-activity-type-validator.service.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-timeline-activity-type-validator.service.spec.ts
deleted file mode 100644
index f6acf643799..00000000000
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-timeline-activity-type-validator.service.spec.ts
+++ /dev/null
@@ -1,272 +0,0 @@
-import { STANDARD_TIMELINE_ACTIVITY_RENDERER_UNIVERSAL_IDENTIFIERS } from 'twenty-shared/timeline';
-import { FieldMetadataType, RelationType } from 'twenty-shared/types';
-
-import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';
-import { FlatTimelineActivityTypeValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-timeline-activity-type-validator.service';
-
-const APPLICATION_UNIVERSAL_IDENTIFIER = '11111111-1111-4111-8111-111111111111';
-const TYPE_UNIVERSAL_IDENTIFIER = '22222222-2222-4222-8222-222222222222';
-const OBJECT_UNIVERSAL_IDENTIFIER = '33333333-3333-4333-8333-333333333333';
-const RELATION_UNIVERSAL_IDENTIFIER = '44444444-4444-4444-8444-444444444444';
-const HAPPENS_AT_UNIVERSAL_IDENTIFIER = '55555555-5555-4555-8555-555555555555';
-
-const emptyMaps = () => ({ byUniversalIdentifier: {} });
-
-const buildCreationArgs = (
- applicationUniversalIdentifier: string,
- overrides: Partial<{
- action: 'created' | 'linked';
- objectUniversalIdentifier: string | null;
- frontComponentUniversalIdentifier: string | null;
- targetRelationFieldUniversalIdentifier: string | null;
- happensAtFieldUniversalIdentifier: string | null;
- }> = {},
-) =>
- ({
- flatEntityToValidate: {
- universalIdentifier: TYPE_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier,
- name: 'recordCreated',
- label: 'was created by',
- action: 'created',
- icon: null,
- frontComponentUniversalIdentifier: null,
- objectUniversalIdentifier: null,
- targetRelationFieldUniversalIdentifier: null,
- triggerFieldUniversalIdentifiers: null,
- happensAtFieldUniversalIdentifier: null,
- replacesTimelineActivityTypeUniversalIdentifier: null,
- isActive: true,
- overrides: null,
- createdAt: '2026-08-22T00:00:00.000Z',
- updatedAt: '2026-08-22T00:00:00.000Z',
- ...overrides,
- },
- optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
- flatTimelineActivityTypeMaps: emptyMaps(),
- flatFrontComponentMaps: emptyMaps(),
- flatObjectMetadataMaps: emptyMaps(),
- flatFieldMetadataMaps: emptyMaps(),
- },
- }) as unknown as Parameters<
- FlatTimelineActivityTypeValidatorService['validateFlatTimelineActivityTypeCreation']
- >[0];
-
-describe('FlatTimelineActivityTypeValidatorService', () => {
- const service = new FlatTimelineActivityTypeValidatorService();
-
- it('rejects a workspace-global emitter declared by an application', () => {
- const result = service.validateFlatTimelineActivityTypeCreation(
- buildCreationArgs(APPLICATION_UNIVERSAL_IDENTIFIER),
- );
-
- expect(result.errors).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- message:
- 'An application timeline activity emitter must target one of its objects',
- }),
- ]),
- );
- });
-
- it('keeps platform fallback emitters valid', () => {
- const result = service.validateFlatTimelineActivityTypeCreation(
- buildCreationArgs(TWENTY_STANDARD_APPLICATION.universalIdentifier),
- );
-
- expect(result.errors).toEqual([]);
- });
-
- it('rejects linked emitters without through routing', () => {
- const result = service.validateFlatTimelineActivityTypeCreation(
- buildCreationArgs(APPLICATION_UNIVERSAL_IDENTIFIER, {
- action: 'linked',
- objectUniversalIdentifier: '33333333-3333-4333-8333-333333333333',
- }),
- );
-
- expect(result.errors).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- message:
- 'Linked and unlinked timeline activity emitters require a target relation',
- }),
- ]),
- );
- });
-
- it('allows a standard renderer owned by the standard application', () => {
- const result = service.validateFlatTimelineActivityTypeCreation(
- buildCreationArgs(TWENTY_STANDARD_APPLICATION.universalIdentifier, {
- frontComponentUniversalIdentifier:
- STANDARD_TIMELINE_ACTIVITY_RENDERER_UNIVERSAL_IDENTIFIERS.message,
- }),
- );
-
- expect(result.errors).toEqual([]);
- });
-
- it('accepts a direct many-to-one relation as through routing', () => {
- const creationArgs = buildCreationArgs(APPLICATION_UNIVERSAL_IDENTIFIER, {
- action: 'linked',
- objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- targetRelationFieldUniversalIdentifier: RELATION_UNIVERSAL_IDENTIFIER,
- });
- const validationMaps =
- creationArgs.optimisticFlatEntityMapsAndRelatedFlatEntityMaps;
-
- validationMaps.flatObjectMetadataMaps.byUniversalIdentifier[
- OBJECT_UNIVERSAL_IDENTIFIER
- ] = {
- universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- } as never;
- validationMaps.flatFieldMetadataMaps.byUniversalIdentifier[
- RELATION_UNIVERSAL_IDENTIFIER
- ] = {
- universalIdentifier: RELATION_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.MORPH_RELATION,
- universalSettings: { relationType: RelationType.MANY_TO_ONE },
- } as never;
-
- const result =
- service.validateFlatTimelineActivityTypeCreation(creationArgs);
-
- expect(result.errors).toEqual([]);
- });
-
- it('accepts a date field on the source object as happensAt field', () => {
- const creationArgs = buildCreationArgs(APPLICATION_UNIVERSAL_IDENTIFIER, {
- action: 'linked',
- objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- targetRelationFieldUniversalIdentifier: RELATION_UNIVERSAL_IDENTIFIER,
- happensAtFieldUniversalIdentifier: HAPPENS_AT_UNIVERSAL_IDENTIFIER,
- });
- const validationMaps =
- creationArgs.optimisticFlatEntityMapsAndRelatedFlatEntityMaps;
-
- validationMaps.flatObjectMetadataMaps.byUniversalIdentifier[
- OBJECT_UNIVERSAL_IDENTIFIER
- ] = {
- universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- } as never;
- validationMaps.flatFieldMetadataMaps.byUniversalIdentifier[
- RELATION_UNIVERSAL_IDENTIFIER
- ] = {
- universalIdentifier: RELATION_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.MORPH_RELATION,
- universalSettings: { relationType: RelationType.MANY_TO_ONE },
- } as never;
- validationMaps.flatFieldMetadataMaps.byUniversalIdentifier[
- HAPPENS_AT_UNIVERSAL_IDENTIFIER
- ] = {
- universalIdentifier: HAPPENS_AT_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.DATE_TIME,
- } as never;
-
- const result =
- service.validateFlatTimelineActivityTypeCreation(creationArgs);
-
- expect(result.errors).toEqual([]);
- });
-
- it('rejects a happensAt field that is not a date field on the source object', () => {
- const creationArgs = buildCreationArgs(APPLICATION_UNIVERSAL_IDENTIFIER, {
- action: 'linked',
- objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- targetRelationFieldUniversalIdentifier: RELATION_UNIVERSAL_IDENTIFIER,
- happensAtFieldUniversalIdentifier: HAPPENS_AT_UNIVERSAL_IDENTIFIER,
- });
- const validationMaps =
- creationArgs.optimisticFlatEntityMapsAndRelatedFlatEntityMaps;
-
- validationMaps.flatObjectMetadataMaps.byUniversalIdentifier[
- OBJECT_UNIVERSAL_IDENTIFIER
- ] = {
- universalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- } as never;
- validationMaps.flatFieldMetadataMaps.byUniversalIdentifier[
- RELATION_UNIVERSAL_IDENTIFIER
- ] = {
- universalIdentifier: RELATION_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.MORPH_RELATION,
- universalSettings: { relationType: RelationType.MANY_TO_ONE },
- } as never;
- validationMaps.flatFieldMetadataMaps.byUniversalIdentifier[
- HAPPENS_AT_UNIVERSAL_IDENTIFIER
- ] = {
- universalIdentifier: HAPPENS_AT_UNIVERSAL_IDENTIFIER,
- objectMetadataUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
- type: FieldMetadataType.TEXT,
- } as never;
-
- const result =
- service.validateFlatTimelineActivityTypeCreation(creationArgs);
-
- expect(result.errors).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- message:
- 'Timeline activity type happensAt field must be a date field on the source object of a linked relation event',
- }),
- ]),
- );
- });
-
- it('rejects a happensAt field on an emitter without a linked action', () => {
- const creationArgs = buildCreationArgs(
- TWENTY_STANDARD_APPLICATION.universalIdentifier,
- {
- action: 'created',
- happensAtFieldUniversalIdentifier: HAPPENS_AT_UNIVERSAL_IDENTIFIER,
- },
- );
-
- const result =
- service.validateFlatTimelineActivityTypeCreation(creationArgs);
-
- expect(result.errors).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- message:
- 'Timeline activity type happensAt field must be a date field on the source object of a linked relation event',
- }),
- ]),
- );
- });
-
- it('does not expose standard renderers to installed applications', () => {
- const creationArgs = buildCreationArgs(APPLICATION_UNIVERSAL_IDENTIFIER, {
- objectUniversalIdentifier: '33333333-3333-4333-8333-333333333333',
- frontComponentUniversalIdentifier:
- STANDARD_TIMELINE_ACTIVITY_RENDERER_UNIVERSAL_IDENTIFIERS.message,
- });
-
- creationArgs.optimisticFlatEntityMapsAndRelatedFlatEntityMaps.flatFrontComponentMaps.byUniversalIdentifier[
- STANDARD_TIMELINE_ACTIVITY_RENDERER_UNIVERSAL_IDENTIFIERS.message
- ] = {
- universalIdentifier:
- STANDARD_TIMELINE_ACTIVITY_RENDERER_UNIVERSAL_IDENTIFIERS.message,
- applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
- } as never;
-
- const result =
- service.validateFlatTimelineActivityTypeCreation(creationArgs);
-
- expect(result.errors).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- message:
- 'Timeline activity type references a front component that does not belong to its application',
- }),
- ]),
- );
- });
-});
diff --git a/packages/twenty-server/src/modules/dashboard/services/__tests__/dashboard-duplication.service.spec.ts b/packages/twenty-server/src/modules/dashboard/services/__tests__/dashboard-duplication.service.spec.ts
deleted file mode 100644
index 6f7d68c085d..00000000000
--- a/packages/twenty-server/src/modules/dashboard/services/__tests__/dashboard-duplication.service.spec.ts
+++ /dev/null
@@ -1,267 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { ActorFromAuthContextService } from 'src/engine/core-modules/actor/services/actor-from-auth-context.service';
-import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
-import { addFlatEntityToFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/add-flat-entity-to-flat-entity-maps-or-throw.util';
-import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/get-flat-object-metadata.mock';
-import { PageLayoutDuplicationService } from 'src/engine/metadata-modules/page-layout/services/page-layout-duplication.service';
-import { PageLayoutService } from 'src/engine/metadata-modules/page-layout/services/page-layout.service';
-import {
- PermissionsException,
- PermissionsExceptionCode,
-} from 'src/engine/metadata-modules/permissions/permissions.exception';
-import {
- type ORMWorkspaceContext,
- withWorkspaceContext,
-} from 'src/engine/twenty-orm/storage/orm-workspace-context.storage';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import {
- DashboardException,
- DashboardExceptionCode,
-} from 'src/modules/dashboard/exceptions/dashboard.exception';
-import { DashboardDuplicationService } from 'src/modules/dashboard/services/dashboard-duplication.service';
-
-const WORKSPACE_ID = 'workspace-id';
-const USER_WORKSPACE_ID = 'user-workspace-id';
-const ROLE_ID = 'role-id';
-const DASHBOARD_OBJECT_METADATA_ID = 'dashboard-object-id';
-const DASHBOARD_ID = 'dashboard-id';
-const PAGE_LAYOUT_ID = 'page-layout-id';
-
-const authContext = {
- type: 'user',
- workspace: { id: WORKSPACE_ID },
- userWorkspaceId: USER_WORKSPACE_ID,
- user: { id: 'user-id' },
- workspaceMember: { id: 'workspace-member-id' },
-} as unknown as WorkspaceAuthContext;
-
-const originalDashboard = {
- id: DASHBOARD_ID,
- title: 'Sales',
- pageLayoutId: PAGE_LAYOUT_ID,
- position: 1,
- createdAt: '2024-01-01T00:00:00.000Z',
- updatedAt: '2024-01-01T00:00:00.000Z',
-};
-
-const buildWorkspaceContext = ({
- canUpdateObjectRecords = true,
- userWorkspaceRoleMap = { [USER_WORKSPACE_ID]: ROLE_ID },
-}: {
- canUpdateObjectRecords?: boolean;
- userWorkspaceRoleMap?: Record<string, string>;
-} = {}): ORMWorkspaceContext =>
- ({
- authContext,
- userWorkspaceRoleMap,
- apiKeyRoleMap: {},
- objectIdByNameSingular: { dashboard: DASHBOARD_OBJECT_METADATA_ID },
- flatObjectMetadataMaps: addFlatEntityToFlatEntityMapsOrThrow({
- flatEntity: getFlatObjectMetadataMock({
- id: DASHBOARD_OBJECT_METADATA_ID,
- universalIdentifier: DASHBOARD_OBJECT_METADATA_ID,
- nameSingular: 'dashboard',
- namePlural: 'dashboards',
- isSystem: false,
- }),
- flatEntityMaps: createEmptyFlatEntityMaps(),
- }),
- permissionsPerRoleId: {
- [ROLE_ID]: {
- [DASHBOARD_OBJECT_METADATA_ID]: {
- canReadObjectRecords: true,
- canUpdateObjectRecords,
- canSoftDeleteObjectRecords: false,
- canDestroyObjectRecords: false,
- restrictedFields: {},
- rowLevelPermissionPredicates: [],
- rowLevelPermissionPredicateGroups: [],
- },
- },
- },
- }) as unknown as ORMWorkspaceContext;
-
-describe('DashboardDuplicationService', () => {
- let service: DashboardDuplicationService;
- let workspaceContext: ORMWorkspaceContext;
- let dashboardRepository: { findOne: jest.Mock; insert: jest.Mock };
- let workspaceOrmManager: {
- getRepository: jest.Mock;
- executeInWorkspaceContext: jest.Mock;
- };
- let pageLayoutDuplicationService: { duplicate: jest.Mock };
- let pageLayoutService: { destroy: jest.Mock };
-
- beforeEach(async () => {
- workspaceContext = buildWorkspaceContext();
- dashboardRepository = {
- findOne: jest
- .fn()
- .mockImplementation(async ({ where }: { where: { id: string } }) =>
- where.id === DASHBOARD_ID
- ? originalDashboard
- : { ...originalDashboard, id: where.id, title: 'Sales (Copy)' },
- ),
- insert: jest
- .fn()
- .mockResolvedValue({ identifiers: [{ id: 'new-dashboard-id' }] }),
- };
- workspaceOrmManager = {
- getRepository: jest.fn().mockReturnValue(dashboardRepository),
- executeInWorkspaceContext: jest
- .fn()
- .mockImplementation((fn: () => unknown) =>
- withWorkspaceContext(workspaceContext, fn),
- ),
- };
- pageLayoutDuplicationService = {
- duplicate: jest.fn().mockResolvedValue({ id: 'new-page-layout-id' }),
- };
- pageLayoutService = { destroy: jest.fn().mockResolvedValue(true) };
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- DashboardDuplicationService,
- {
- provide: PageLayoutDuplicationService,
- useValue: pageLayoutDuplicationService,
- },
- { provide: PageLayoutService, useValue: pageLayoutService },
- { provide: WorkspaceOrmManager, useValue: workspaceOrmManager },
- {
- provide: ActorFromAuthContextService,
- useValue: {
- injectActorFieldsOnCreate: jest
- .fn()
- .mockImplementation(
- async ({ records }: { records: object[] }) => records,
- ),
- },
- },
- ],
- }).compile();
-
- service = module.get(DashboardDuplicationService);
- });
-
- it('should read the source and create the copy under the caller role', async () => {
- const duplicatedDashboard = await service.duplicateDashboard(
- DASHBOARD_ID,
- authContext,
- );
-
- expect(workspaceOrmManager.getRepository).toHaveBeenCalledWith(
- 'dashboard',
- { intersectionOf: [ROLE_ID] },
- );
- expect(pageLayoutDuplicationService.duplicate).toHaveBeenCalledWith({
- pageLayoutId: PAGE_LAYOUT_ID,
- workspaceId: WORKSPACE_ID,
- });
- expect(dashboardRepository.insert).toHaveBeenCalledWith({
- title: 'Sales (Copy)',
- pageLayoutId: 'new-page-layout-id',
- position: 1,
- });
- expect(duplicatedDashboard).toMatchObject({
- id: 'new-dashboard-id',
- title: 'Sales (Copy)',
- });
- });
-
- it('should only read the columns the duplication copies', async () => {
- await service.duplicateDashboard(DASHBOARD_ID, authContext);
-
- expect(dashboardRepository.findOne).toHaveBeenNthCalledWith(1, {
- where: { id: DASHBOARD_ID },
- select: ['id', 'title', 'pageLayoutId', 'position'],
- });
- expect(dashboardRepository.findOne).toHaveBeenNthCalledWith(2, {
- where: { id: 'new-dashboard-id' },
- select: [
- 'id',
- 'title',
- 'pageLayoutId',
- 'position',
- 'createdAt',
- 'updatedAt',
- ],
- });
- });
-
- it('should refuse the caller before copying the layout when the role cannot create dashboards', async () => {
- workspaceContext = buildWorkspaceContext({
- canUpdateObjectRecords: false,
- });
-
- await expect(
- service.duplicateDashboard(DASHBOARD_ID, authContext),
- ).rejects.toMatchObject({
- constructor: PermissionsException,
- code: PermissionsExceptionCode.PERMISSION_DENIED,
- });
- expect(pageLayoutDuplicationService.duplicate).not.toHaveBeenCalled();
- expect(dashboardRepository.insert).not.toHaveBeenCalled();
- });
-
- it('should refuse a caller without a role before reading the source', async () => {
- workspaceContext = buildWorkspaceContext({ userWorkspaceRoleMap: {} });
-
- await expect(
- service.duplicateDashboard(DASHBOARD_ID, authContext),
- ).rejects.toMatchObject({
- constructor: PermissionsException,
- code: PermissionsExceptionCode.PERMISSION_DENIED,
- });
- expect(dashboardRepository.findOne).not.toHaveBeenCalled();
- expect(pageLayoutDuplicationService.duplicate).not.toHaveBeenCalled();
- });
-
- it('should destroy the duplicated layout when the dashboard insert is refused', async () => {
- const permissionDenied = new PermissionsException(
- 'Entity performing the request does not have permission',
- PermissionsExceptionCode.PERMISSION_DENIED,
- );
-
- dashboardRepository.insert.mockRejectedValue(permissionDenied);
-
- await expect(
- service.duplicateDashboard(DASHBOARD_ID, authContext),
- ).rejects.toBe(permissionDenied);
- expect(pageLayoutService.destroy).toHaveBeenCalledWith({
- id: 'new-page-layout-id',
- workspaceId: WORKSPACE_ID,
- });
- });
-
- it('should surface the insert failure even when the layout cannot be destroyed', async () => {
- const insertError = new Error('insert failed');
-
- dashboardRepository.insert.mockRejectedValue(insertError);
- pageLayoutService.destroy.mockRejectedValue(new Error('destroy failed'));
-
- await expect(
- service.duplicateDashboard(DASHBOARD_ID, authContext),
- ).rejects.toBe(insertError);
- });
-
- it('should keep the duplicated layout when the dashboard is created', async () => {
- await service.duplicateDashboard(DASHBOARD_ID, authContext);
-
- expect(pageLayoutService.destroy).not.toHaveBeenCalled();
- });
-
- it('should report a missing dashboard when the source is out of the caller reach', async () => {
- dashboardRepository.findOne.mockResolvedValue(null);
-
- await expect(
- service.duplicateDashboard(DASHBOARD_ID, authContext),
- ).rejects.toMatchObject({
- constructor: DashboardException,
- code: DashboardExceptionCode.DASHBOARD_NOT_FOUND,
- });
- expect(pageLayoutDuplicationService.duplicate).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/modules/match-participant/__tests__/match-participant.service.spec.ts b/packages/twenty-server/src/modules/match-participant/__tests__/match-participant.service.spec.ts
deleted file mode 100644
index cbdc214eb5d..00000000000
--- a/packages/twenty-server/src/modules/match-participant/__tests__/match-participant.service.spec.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { MatchParticipantService } from 'src/modules/match-participant/match-participant.service';
-import { ParticipantTargetReconciliationService } from 'src/modules/match-participant/participant-target-reconciliation.service';
-import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
-
-const MESSAGE_ID = '77777777-7777-4777-8777-777777777777';
-
-describe('MatchParticipantService', () => {
- let service: MatchParticipantService<MessageParticipantWorkspaceEntity>;
- let participantTargetReconciliationService: {
- reconcileParticipantTargets: jest.Mock;
- };
- let participantRepository: { find: jest.Mock; updateMany: jest.Mock };
-
- beforeEach(async () => {
- participantTargetReconciliationService = {
- reconcileParticipantTargets: jest.fn(),
- };
- participantRepository = {
- find: jest.fn().mockResolvedValue([]),
- updateMany: jest.fn().mockResolvedValue(undefined),
- };
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- MatchParticipantService,
- {
- provide: WorkspaceOrmManager,
- useValue: { getRepository: () => participantRepository },
- },
- {
- provide: ParticipantTargetReconciliationService,
- useValue: participantTargetReconciliationService,
- },
- ],
- }).compile();
-
- service = module.get(MatchParticipantService);
- });
-
- const aParticipant = () =>
- ({
- id: '88888888-8888-4888-8888-888888888888',
- messageId: MESSAGE_ID,
- handle: 'urn:li:person:abc',
- personId: '66666666-6666-4666-8666-666666666666',
- }) as unknown as MessageParticipantWorkspaceEntity;
-
- // The whole point of the mode: a handle that is not an email address would
- // resolve to nobody, and the matcher writes personId back to null when it
- // finds nobody — discarding an identity the caller had already supplied.
- it('reconciles targets without looking any handle up as an email', async () => {
- await service.matchParticipants({
- participants: [aParticipant()],
- sourceRecordIds: [MESSAGE_ID],
- objectMetadataName: 'messageParticipant',
- matchWith: 'targetsOnly',
- });
-
- expect(
- participantTargetReconciliationService.reconcileParticipantTargets,
- ).toHaveBeenCalledWith({
- sourceRecordIds: [MESSAGE_ID],
- objectMetadataName: 'messageParticipant',
- transactionScope: undefined,
- });
- expect(participantRepository.find).not.toHaveBeenCalled();
- expect(participantRepository.updateMany).not.toHaveBeenCalled();
- });
-
- // The mode returns early; falling through would reconcile a second time at
- // the end of the match path, for no benefit and twice the queries.
- it('reconciles exactly once', async () => {
- await service.matchParticipants({
- participants: [aParticipant()],
- sourceRecordIds: [MESSAGE_ID],
- objectMetadataName: 'messageParticipant',
- matchWith: 'targetsOnly',
- });
-
- expect(
- participantTargetReconciliationService.reconcileParticipantTargets,
- ).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/__tests__/apply-messages-visibility-restrictions.service.spec.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/__tests__/apply-messages-visibility-restrictions.service.spec.ts
deleted file mode 100644
index 5774c80083d..00000000000
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/__tests__/apply-messages-visibility-restrictions.service.spec.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-import { getRepositoryToken } from '@nestjs/typeorm';
-
-import { FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED } from 'twenty-shared/constants';
-import { MessageChannelVisibility } from 'twenty-shared/types';
-
-import { 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 { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { ApplyMessagesVisibilityRestrictionsService } from 'src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service';
-import { type MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
-
-const WORKSPACE_ID = '33333333-3333-4333-8333-333333333333';
-const APPLICATION_ID = '44444444-4444-4444-8444-444444444444';
-const MESSAGE_ID = '77777777-7777-4777-8777-777777777777';
-const MESSAGE_CHANNEL_ID = '55555555-5555-4555-8555-555555555555';
-
-describe('ApplyMessagesVisibilityRestrictionsService', () => {
- let service: ApplyMessagesVisibilityRestrictionsService;
- let connectedAccountRepository: { find: jest.Mock };
- let messageChannelRepository: { find: jest.Mock };
-
- const aMessage = (): MessageWorkspaceEntity =>
- ({
- id: MESSAGE_ID,
- subject: 'Coffee tomorrow?',
- text: 'Are you free at 3?',
- }) as unknown as MessageWorkspaceEntity;
-
- beforeEach(async () => {
- connectedAccountRepository = { find: jest.fn().mockResolvedValue([]) };
- messageChannelRepository = {
- find: jest.fn().mockResolvedValue([
- {
- id: MESSAGE_CHANNEL_ID,
- visibility: MessageChannelVisibility.METADATA,
- },
- ]),
- };
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- ApplyMessagesVisibilityRestrictionsService,
- {
- provide: WorkspaceOrmManager,
- useValue: {
- executeInWorkspaceContext: (callback: () => unknown) => callback(),
- getRepository: () => ({
- find: jest.fn().mockResolvedValue([
- {
- messageId: MESSAGE_ID,
- messageChannelId: MESSAGE_CHANNEL_ID,
- },
- ]),
- }),
- },
- },
- {
- provide: getRepositoryToken(ConnectedAccountEntity),
- useValue: connectedAccountRepository,
- },
- {
- provide: getRepositoryToken(UserWorkspaceEntity),
- useValue: { findOne: jest.fn() },
- },
- {
- provide: getRepositoryToken(MessageChannelEntity),
- useValue: messageChannelRepository,
- },
- ],
- }).compile();
-
- service = module.get(ApplyMessagesVisibilityRestrictionsService);
- });
-
- // An application has no user behind it, so before this bypass existed it fell
- // straight through to the redaction branches and read back placeholders
- // instead of the messages it had just written.
- it('does not redact a channel owned by the calling application', async () => {
- connectedAccountRepository.find.mockResolvedValue([
- { id: 'connected-account-id', applicationId: APPLICATION_ID },
- ]);
-
- const [message] = await service.applyMessagesVisibilityRestrictions(
- [aMessage()],
- WORKSPACE_ID,
- undefined,
- APPLICATION_ID,
- );
-
- expect(message.subject).toBe('Coffee tomorrow?');
- expect(message.text).toBe('Are you free at 3?');
- expect(connectedAccountRepository.find).toHaveBeenCalledWith(
- expect.objectContaining({
- where: expect.objectContaining({
- applicationId: APPLICATION_ID,
- workspaceId: WORKSPACE_ID,
- }),
- }),
- );
- });
-
- // The bypass keys on the connection carrying this application's id, so a
- // channel belonging to someone else stays redacted.
- it('still redacts a channel the calling application does not own', async () => {
- connectedAccountRepository.find.mockResolvedValue([]);
-
- const [message] = await service.applyMessagesVisibilityRestrictions(
- [aMessage()],
- WORKSPACE_ID,
- undefined,
- APPLICATION_ID,
- );
-
- expect(message.subject).toBe(
- FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED,
- );
- expect(message.text).toBe(FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED);
- });
-
- it('leaves the email path alone when no application is calling', async () => {
- const [message] = await service.applyMessagesVisibilityRestrictions(
- [aMessage()],
- WORKSPACE_ID,
- );
-
- expect(connectedAccountRepository.find).not.toHaveBeenCalled();
- expect(message.subject).toBe(
- FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED,
- );
- });
-});
diff --git a/packages/twenty-server/src/modules/messaging/message-participant-manager/services/__tests__/messaging-message-participant.service.spec.ts b/packages/twenty-server/src/modules/messaging/message-participant-manager/services/__tests__/messaging-message-participant.service.spec.ts
deleted file mode 100644
index 8516b2cff28..00000000000
--- a/packages/twenty-server/src/modules/messaging/message-participant-manager/services/__tests__/messaging-message-participant.service.spec.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-import { Test, type TestingModule } from '@nestjs/testing';
-
-import { QUERY_MAX_RECORDS } from 'twenty-shared/constants';
-import { MessageParticipantRole } from 'twenty-shared/types';
-
-import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/types/workspace-transaction-scope.type';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { MatchParticipantService } from 'src/modules/match-participant/match-participant.service';
-import { ParticipantTargetReconciliationService } from 'src/modules/match-participant/participant-target-reconciliation.service';
-import { type ParticipantWithMessageId } from 'src/modules/messaging/message-import-manager/drivers/gmail/types/gmail-message.type';
-import { MessagingMessageParticipantService } from 'src/modules/messaging/message-participant-manager/services/messaging-message-participant.service';
-
-const WORKSPACE_ID = '33333333-3333-4333-8333-333333333333';
-const MESSAGE_ID = '77777777-7777-4777-8777-777777777777';
-const PARTICIPANT_ID = '88888888-8888-4888-8888-888888888888';
-const PERSON_ID = '66666666-6666-4666-8666-666666666666';
-
-describe('MessagingMessageParticipantService', () => {
- let service: MessagingMessageParticipantService;
- let participantRepository: {
- find: jest.Mock;
- insert: jest.Mock;
- updateMany: jest.Mock;
- };
- let transactionScope: WorkspaceTransactionScope;
- let matchParticipantService: { matchParticipants: jest.Mock };
-
- const anEmailParticipant = (): ParticipantWithMessageId => ({
- messageId: MESSAGE_ID,
- handle: '[email protected]',
- displayName: 'Ada',
- role: MessageParticipantRole.FROM,
- });
-
- beforeEach(async () => {
- matchParticipantService = { matchParticipants: jest.fn() };
- participantRepository = {
- find: jest.fn().mockResolvedValue([]),
- insert: jest.fn().mockResolvedValue({ identifiers: [] }),
- updateMany: jest.fn().mockResolvedValue(undefined),
- };
-
- transactionScope = {
- getRepository: () => participantRepository,
- } as unknown as WorkspaceTransactionScope;
-
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- MessagingMessageParticipantService,
- {
- provide: WorkspaceOrmManager,
- useValue: {
- executeInWorkspaceContext: (callback: () => unknown) => callback(),
- },
- },
- {
- provide: MatchParticipantService,
- useValue: matchParticipantService,
- },
- {
- provide: ParticipantTargetReconciliationService,
- useValue: { reconcileParticipantTargets: jest.fn() },
- },
- ],
- }).compile();
-
- service = module.get(MessagingMessageParticipantService);
- });
-
- const givenAnExistingParticipant = (personId: string | null) => {
- participantRepository.find.mockResolvedValueOnce([
- {
- id: PARTICIPANT_ID,
- messageId: MESSAGE_ID,
- handle: '[email protected]',
- displayName: 'Ada',
- role: MessageParticipantRole.FROM,
- personId,
- workspaceMemberId: null,
- },
- ]);
- };
-
- it('inserts a new participant with a null identity when none is supplied', async () => {
- await service.saveMessageParticipants(
- [anEmailParticipant()],
- WORKSPACE_ID,
- transactionScope,
- );
-
- expect(participantRepository.insert).toHaveBeenCalledWith([
- expect.objectContaining({
- handle: '[email protected]',
- personId: null,
- workspaceMemberId: null,
- }),
- ]);
- expect(participantRepository.updateMany).not.toHaveBeenCalled();
- });
-
- it('links an existing participant when the caller now knows the person', async () => {
- givenAnExistingParticipant(null);
-
- await service.saveMessageParticipants(
- [{ ...anEmailParticipant(), personId: PERSON_ID }],
- WORKSPACE_ID,
- transactionScope,
- );
-
- expect(participantRepository.updateMany).toHaveBeenCalledWith([
- {
- criteria: PARTICIPANT_ID,
- partialEntity: {
- personId: PERSON_ID,
- workspaceMemberId: null,
- displayName: 'Ada',
- },
- },
- ]);
- });
-
- it('leaves an existing participant alone when the caller supplies no identity', async () => {
- givenAnExistingParticipant(PERSON_ID);
-
- await service.saveMessageParticipants(
- [anEmailParticipant()],
- WORKSPACE_ID,
- transactionScope,
- );
-
- expect(participantRepository.updateMany).not.toHaveBeenCalled();
- expect(participantRepository.insert).toHaveBeenCalledWith([]);
- });
-
- it('does not rewrite an identity that already matches', async () => {
- givenAnExistingParticipant(PERSON_ID);
-
- await service.saveMessageParticipants(
- [{ ...anEmailParticipant(), personId: PERSON_ID }],
- WORKSPACE_ID,
- transactionScope,
- );
-
- expect(participantRepository.updateMany).not.toHaveBeenCalled();
- });
- // The enrichment promise: ingest first, resolve the contact later. A
- // provider that renames someone between deliveries, or omits the name,
- // must not split the participant in two.
- it('links the existing participant when the display name changed too', async () => {
- givenAnExistingParticipant(null);
-
- await service.saveMessageParticipants(
- [{ ...anEmailParticipant(), displayName: 'Ada L.', personId: PERSON_ID }],
- WORKSPACE_ID,
- transactionScope,
- );
-
- expect(participantRepository.insert).toHaveBeenCalledWith([]);
- expect(participantRepository.updateMany).toHaveBeenCalledWith([
- {
- criteria: PARTICIPANT_ID,
- partialEntity: {
- personId: PERSON_ID,
- workspaceMemberId: null,
- displayName: 'Ada L.',
- },
- },
- ]);
- });
-
- // An omitted name reaches the service as an empty string, and this is the
- // only branch that writes the column, so the stored one has to survive: an
- // app adding a person link should not have to resend the name to keep it.
- it('keeps the stored display name when the caller omits it', async () => {
- givenAnExistingParticipant(null);
-
- await service.saveMessageParticipants(
- [{ ...anEmailParticipant(), displayName: '', personId: PERSON_ID }],
- WORKSPACE_ID,
- transactionScope,
- );
-
- expect(participantRepository.insert).toHaveBeenCalledWith([]);
- expect(participantRepository.updateMany).toHaveBeenCalledWith([
- {
- criteria: PARTICIPANT_ID,
- partialEntity: {
- personId: PERSON_ID,
- workspaceMemberId: null,
- displayName: 'Ada',
- },
- },
- ]);
- });
-
- // A batch is capped by messages, not participants, so one conversation with
- // many people in it can produce more updates than updateMany accepts.
- it('chunks identity updates past the single-call limit', async () => {
- const participantCount = QUERY_MAX_RECORDS + 50;
- const existingParticipants = Array.from(
- { length: participantCount },
- (_unused, index) => ({
- id: `participant-${index}`,
- messageId: MESSAGE_ID,
- handle: `member-${index}`,
- displayName: 'Ada',
- role: MessageParticipantRole.FROM,
- personId: null,
- workspaceMemberId: null,
- }),
- );
-
- participantRepository.find.mockResolvedValueOnce(existingParticipants);
-
- await service.saveMessageParticipants(
- existingParticipants.map(({ handle }) => ({
- ...anEmailParticipant(),
- handle,
- personId: PERSON_ID,
- })),
- WORKSPACE_ID,
- transactionScope,
- );
-
- expect(participantRepository.updateMany).toHaveBeenCalledTimes(2);
-
- const updatedCount = participantRepository.updateMany.mock.calls.reduce(
- (total, [updates]) => total + updates.length,
- 0,
- );
-
- expect(updatedCount).toBe(participantCount);
- participantRepository.updateMany.mock.calls.forEach(([updates]) => {
- expect(updates.length).toBeLessThanOrEqual(QUERY_MAX_RECORDS);
- });
- });
-
- it('corrects a wrong person link without leaving the old one behind', async () => {
- const OTHER_PERSON_ID = '55555555-5555-4555-8555-555555555555';
-
- givenAnExistingParticipant(OTHER_PERSON_ID);
-
- await service.saveMessageParticipants(
- [{ ...anEmailParticipant(), displayName: 'Ada L.', personId: PERSON_ID }],
- WORKSPACE_ID,
- transactionScope,
- );
-
- expect(participantRepository.insert).toHaveBeenCalledWith([]);
- expect(participantRepository.updateMany).toHaveBeenCalledWith([
- expect.objectContaining({
- partialEntity: expect.objectContaining({ personId: PERSON_ID }),
- }),
- ]);
- });
-
- // Email relies on the exact match: the matcher, not the caller, sets the
- // identity, so a renamed sender is a different participant row as before.
- it('still inserts a new row when a caller with no identity renames a sender', async () => {
- givenAnExistingParticipant(null);
-
- await service.saveMessageParticipants(
- [{ ...anEmailParticipant(), displayName: 'Ada L.' }],
- WORKSPACE_ID,
- transactionScope,
- );
-
- expect(participantRepository.insert).toHaveBeenCalledWith([
- expect.objectContaining({ displayName: 'Ada L.', personId: null }),
- ]);
- expect(participantRepository.updateMany).not.toHaveBeenCalled();
- });
-
- it('matches with people and workspace members by default', async () => {
- await service.matchMessageParticipants({
- participants: [],
- messageIds: [MESSAGE_ID],
- workspaceId: WORKSPACE_ID,
- });
-
- expect(matchParticipantService.matchParticipants).toHaveBeenCalledWith(
- expect.objectContaining({ matchWith: 'workspaceMemberAndPerson' }),
- );
- });
-
- // An app channel's handles are not email addresses, so running the matcher
- // would null out the identities the caller supplied at save time.
- it('forwards targetsOnly so a non-email channel never runs the email matcher', async () => {
- await service.matchMessageParticipants({
- participants: [],
- messageIds: [MESSAGE_ID],
- workspaceId: WORKSPACE_ID,
- matchWith: 'targetsOnly',
- });
-
- expect(matchParticipantService.matchParticipants).toHaveBeenCalledWith(
- expect.objectContaining({
- matchWith: 'targetsOnly',
- sourceRecordIds: [MESSAGE_ID],
- objectMetadataName: 'messageParticipant',
- }),
- );
- });
-});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/__tests__/workflow-executor.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/__tests__/workflow-executor.workspace-service.spec.ts
deleted file mode 100644
index 30f0bf29f43..00000000000
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/__tests__/workflow-executor.workspace-service.spec.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-import {
- StepStatus,
- type WorkflowRunStepInfos,
- type WorkflowRunStepLog,
-} from 'twenty-shared/workflow';
-
-import { type WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';
-import { type BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
-import { type ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
-import { type FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
-import { type MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
-import { type MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
-import { type UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
-import { type UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
-import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
-import { type WorkflowActionFactory } from 'src/modules/workflow/workflow-executor/factories/workflow-action.factory';
-import { WorkflowExecutorWorkspaceService } from 'src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service';
-import { type WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-
-const WORKSPACE_ID = 'workspace-id';
-const WORKFLOW_RUN_ID = 'workflow-run-id';
-const AGENT_STEP_ID = 'agent-step-id';
-
-describe('WorkflowExecutorWorkspaceService', () => {
- const workflowRunWorkspaceService = {
- getWorkflowRunOrFail: jest.fn(),
- updateWorkflowRunStepInfo: jest.fn(),
- endWorkflowRun: jest.fn(),
- };
-
- const workflowAction = { execute: jest.fn() };
-
- const billingUsageService = { assertUsageAllowed: jest.fn() };
- const usageLimitQuotaService = { consumeQuota: jest.fn() };
- const usageRecorderService = { record: jest.fn() };
-
- const service = new WorkflowExecutorWorkspaceService(
- {
- findCoreWorkflowById: jest.fn().mockResolvedValue({
- id: 'workflow-id',
- workspaceWorkflowId: 'workflow-id',
- applicationId: 'application-id',
- }),
- } as unknown as WorkflowCoreSyncService,
- {
- get: jest.fn().mockReturnValue(workflowAction),
- } as unknown as WorkflowActionFactory,
- usageRecorderService as unknown as UsageRecorderService,
- workflowRunWorkspaceService as unknown as WorkflowRunWorkspaceService,
- billingUsageService as unknown as BillingUsageService,
- usageLimitQuotaService as unknown as UsageLimitQuotaService,
- {
- isFeatureEnabled: jest.fn().mockResolvedValue(true),
- } as unknown as FeatureFlagService,
- {} as ExceptionHandlerService,
- {} as MetricsService,
- {} as MessageQueueService,
- );
-
- const previousStepLog = {
- status: 'SUCCESS',
- details: { type: 'AI_AGENT' },
- } as unknown as WorkflowRunStepLog;
-
- const mockWorkflowRun = (stepInfos: WorkflowRunStepInfos) =>
- workflowRunWorkspaceService.getWorkflowRunOrFail.mockResolvedValue({
- id: WORKFLOW_RUN_ID,
- status: WorkflowRunStatus.RUNNING,
- coreWorkflowId: 'workflow-id',
- stepLogs: { [AGENT_STEP_ID]: previousStepLog },
- state: {
- flow: {
- steps: [
- {
- id: AGENT_STEP_ID,
- type: 'AI_AGENT',
- nextStepIds: [],
- settings: {},
- },
- ],
- },
- stepInfos: {
- trigger: { status: StepStatus.SUCCESS, result: {} },
- ...stepInfos,
- },
- },
- });
-
- beforeEach(() => {
- jest.clearAllMocks();
- workflowAction.execute.mockResolvedValue({ result: { response: 'done' } });
- });
-
- describe('executeFromSteps', () => {
- it('runs a resumed step without charging it or checking the quota again', async () => {
- mockWorkflowRun({
- [AGENT_STEP_ID]: { status: StepStatus.RUNNING, threadId: 'thread' },
- });
-
- await service.executeFromSteps({
- stepIds: [AGENT_STEP_ID],
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- resumedThreadId: 'thread',
- });
-
- expect(workflowAction.execute).toHaveBeenCalledTimes(1);
- expect(workflowAction.execute).toHaveBeenCalledWith(
- expect.objectContaining({
- currentStepId: AGENT_STEP_ID,
- resumedThreadId: 'thread',
- previousStepLog,
- }),
- );
- expect(
- workflowRunWorkspaceService.updateWorkflowRunStepInfo,
- ).toHaveBeenLastCalledWith({
- stepId: AGENT_STEP_ID,
- stepInfo: { status: StepStatus.SUCCESS, result: { response: 'done' } },
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- });
- expect(billingUsageService.assertUsageAllowed).not.toHaveBeenCalled();
- expect(usageLimitQuotaService.consumeQuota).not.toHaveBeenCalled();
- expect(usageRecorderService.record).not.toHaveBeenCalled();
- });
-
- it('charges a step it runs, whatever conversation it holds', async () => {
- mockWorkflowRun({
- [AGENT_STEP_ID]: { status: StepStatus.NOT_STARTED, threadId: 'thread' },
- });
-
- await service.executeFromSteps({
- stepIds: [AGENT_STEP_ID],
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- });
-
- expect(workflowAction.execute).toHaveBeenCalledTimes(1);
- expect(workflowAction.execute).toHaveBeenCalledWith(
- expect.objectContaining({
- resumedThreadId: undefined,
- previousStepLog: undefined,
- }),
- );
- expect(billingUsageService.assertUsageAllowed).toHaveBeenCalledTimes(1);
- expect(usageLimitQuotaService.consumeQuota).toHaveBeenCalledTimes(1);
- expect(usageRecorderService.record).toHaveBeenCalledTimes(1);
- });
-
- it('leaves a step waiting for its answer to the resume', async () => {
- mockWorkflowRun({
- [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: 'thread' },
- });
-
- await service.executeFromSteps({
- stepIds: [AGENT_STEP_ID],
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- });
-
- expect(workflowAction.execute).not.toHaveBeenCalled();
- expect(
- workflowRunWorkspaceService.updateWorkflowRunStepInfo,
- ).not.toHaveBeenCalled();
- expect(workflowRunWorkspaceService.endWorkflowRun).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
deleted file mode 100644
index 2bf07f68c10..00000000000
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-import { WorkflowActionType } from 'twenty-shared/workflow';
-
-import { type MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
-import { type WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';
-import { type WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';
-import {
- type WorkflowAction,
- type WorkflowFormAction,
-} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
-import { RUN_WORKFLOW_JOB_NAME } from 'src/modules/workflow/workflow-runner/constants/run-workflow-job-name';
-import { type CoreWorkflowRunnerService } from 'src/modules/workflow/workflow-runner/services/core-workflow-runner.service';
-import { type WorkflowThrottlingWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run-queue/workspace-services/workflow-throttling.workspace-service';
-import { type WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';
-
-const WORKSPACE_ID = 'workspace-id';
-const WORKFLOW_RUN_ID = 'workflow-run-id';
-const THREAD_ID = 'thread-id';
-
-const AGENT_STEP = {
- id: 'agent-step-id',
- type: WorkflowActionType.AI_AGENT,
-} as WorkflowAction;
-
-const FORM_STEP: WorkflowFormAction = {
- id: 'form-step-id',
- name: 'Form',
- valid: true,
- type: WorkflowActionType.FORM,
- settings: {
- input: [],
- outputSchema: {},
- errorHandlingOptions: {
- retryOnFailure: { value: 0 },
- continueOnFailure: { value: false },
- },
- },
-};
-
-describe('WorkflowRunnerWorkspaceService', () => {
- const messageQueueService = { add: jest.fn() };
- const workflowRunWorkspaceService = {
- updateStepInfoIfPending: jest.fn().mockResolvedValue(true),
- };
- const workflowVersionStepOperationsWorkspaceService = {
- enrichFormStepResponse: jest
- .fn()
- .mockImplementation(async ({ response }) => ({
- ...response,
- enriched: true,
- })),
- };
-
- const service = new WorkflowRunnerWorkspaceService(
- workflowRunWorkspaceService as unknown as WorkflowRunWorkspaceService,
- messageQueueService as unknown as MessageQueueService,
- workflowVersionStepOperationsWorkspaceService as unknown as WorkflowVersionStepOperationsWorkspaceService,
- {} as WorkflowThrottlingWorkspaceService,
- {} as CoreWorkflowRunnerService,
- {} as WorkflowVersionCoreSyncService,
- );
-
- const resumeAnsweredStep = (step: WorkflowAction) =>
- service.resumeAnsweredStep({
- workspaceId: WORKSPACE_ID,
- workflowRunId: WORKFLOW_RUN_ID,
- step,
- threadId: THREAD_ID,
- response: { discount: 15 },
- });
-
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('records the enriched result of a form without a conversation before scheduling its continuation', async () => {
- const completed = await service.completeFormStep({
- workspaceId: WORKSPACE_ID,
- workflowRunId: WORKFLOW_RUN_ID,
- step: FORM_STEP,
- expectedThreadId: null,
- response: { discount: 15 },
- });
-
- expect(completed).toBe(true);
- expect(
- workflowRunWorkspaceService.updateStepInfoIfPending,
- ).toHaveBeenCalledWith(
- expect.objectContaining({
- expectedThreadId: null,
- stepInfo: {
- status: 'SUCCESS',
- result: { discount: 15, enriched: true },
- },
- }),
- );
- expect(messageQueueService.add).not.toHaveBeenCalled();
- });
-
- describe('resumeAnsweredStep', () => {
- it('schedules an explicit resume of an agent step in its conversation', async () => {
- await resumeAnsweredStep(AGENT_STEP);
-
- expect(messageQueueService.add).toHaveBeenCalledWith(
- RUN_WORKFLOW_JOB_NAME,
- {
- workspaceId: WORKSPACE_ID,
- workflowRunId: WORKFLOW_RUN_ID,
- stepToResume: { stepId: 'agent-step-id', threadId: THREAD_ID },
- },
- expect.objectContaining({ id: WORKFLOW_RUN_ID }),
- );
- expect(
- workflowRunWorkspaceService.updateStepInfoIfPending,
- ).not.toHaveBeenCalled();
- });
-
- it('completes a form step with its enriched answer, then resumes the run after it', async () => {
- await resumeAnsweredStep(FORM_STEP);
-
- expect(
- workflowRunWorkspaceService.updateStepInfoIfPending,
- ).toHaveBeenCalledWith({
- stepId: 'form-step-id',
- stepInfo: {
- status: 'SUCCESS',
- result: { discount: 15, enriched: true },
- },
- expectedThreadId: THREAD_ID,
- workspaceId: WORKSPACE_ID,
- workflowRunId: WORKFLOW_RUN_ID,
- });
- expect(messageQueueService.add).toHaveBeenCalledWith(
- RUN_WORKFLOW_JOB_NAME,
- {
- workspaceId: WORKSPACE_ID,
- workflowRunId: WORKFLOW_RUN_ID,
- lastExecutedStepId: 'form-step-id',
- },
- expect.objectContaining({ id: WORKFLOW_RUN_ID }),
- );
- });
-
- it('resumes nothing when the form step no longer waits on this conversation', async () => {
- workflowRunWorkspaceService.updateStepInfoIfPending.mockResolvedValueOnce(
- false,
- );
-
- await resumeAnsweredStep(FORM_STEP);
-
- expect(messageQueueService.add).not.toHaveBeenCalled();
- });
- });
-});