Files
twenty/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-creation.integration-spec.ts
T
Félix Malfait 8cb88cabee fix(role): rebind API keys + agents before deleting their role (#20935)
## Customer-reported bug

A customer hit this when using the AI chat:

```json
{
  "message": "API key 760d4822-da40-4b3f-9031-40563d7ed6c9 has no role assigned",
  "extensions": {
    "code": "INTERNAL_SERVER_ERROR",
    "userFriendlyMessage": "This API key has no role assigned."
  }
}
```

Their integration authenticates via API key. Somewhere along the way,
the role bound to that API key was deleted, leaving the API key
authenticated but role-less. Any request that hits a permission check
(`getRoleIdForApiKeyId`) blows up.

## Root cause

In `RoleService.deleteManyRoles`, the pre-deletion cleanup
(`assignDefaultRoleToMembersWithRoleToDelete`) only rebinds **user
workspaces** to the workspace default role. API keys and agents pointing
at the role are ignored. Because `RoleTargetEntity.role` declares
`onDelete: 'CASCADE'`, the FK then drops the role_target rows for those
API keys / agents — but the API keys themselves stay in `api_key`, now
orphaned in `apiKeyRoleMap`.

A previous read-side workaround
([2767ddac44](https://github.com/twentyhq/twenty/commit/2767ddac44) —
make the `role` ResolveField nullable) handled the API-key-details page,
but did not address the write paths (`getRoleIdForApiKeyId`).

## Fix

- Rename `assignDefaultRoleToMembersWithRoleToDelete` →
`rebindTargetsOfRoleToDeleteToDefaultRole` and extend it to rebind API
keys (via `ApiKeyRoleService.assignRoleToApiKey`) and agents (via
`AiAgentRoleService.assignRoleToAgent`) in the same step, before the
role is deleted.
- If the workspace default role doesn't satisfy `canBeAssignedToApiKeys`
/ `canBeAssignedToAgents`, the inner `assignRoleTo*` validation throws.
We catch that and rethrow as a `PermissionsException` with a
role-deletion-context message and two new codes —
`ROLE_CANNOT_BE_ASSIGNED_TO_API_KEYS` /
`ROLE_CANNOT_BE_ASSIGNED_TO_AGENTS` — so the admin sees a clear
"reassign these first" prompt rather than a confusing inner error.

## Scope / non-goals

- **Already-orphaned API keys are not auto-healed.** The customer still
needs to reassign a role to their existing orphan API key via the UI
(Settings > API Keys > [the key] > role). A separate cleanup command for
existing orphans is a follow-up.
- I did not investigate *why* the customer's session was authenticated
via API key in the AI chat — that may be their integration setup. Worth
confirming with them separately.

## Test plan

- [ ] Workspace with default role `Admin` (which has
`canBeAssignedToApiKeys: true`): create an API key with a custom role,
delete the custom role → API key is rebound to Admin, requests keep
working.
- [ ] Workspace with default role `Member` (default, has
`canBeAssignedToApiKeys: false`): create an API key with a custom role,
delete the custom role → role deletion fails with the new
`ROLE_CANNOT_BE_ASSIGNED_TO_API_KEYS` error explaining the admin must
reassign first. API key + custom role are both unchanged.
- [ ] Same two scenarios for agents (`canBeAssignedToAgents`).
- [ ] Existing user-workspace rebind behavior is unchanged.
- [ ] Role deletion with no dependent API keys / agents still works.
2026-05-27 10:54:02 +02:00

226 lines
6.4 KiB
TypeScript

import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';
import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';
import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';
import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';
import { type CreateAgentInput } from 'src/engine/metadata-modules/ai/ai-agent/dtos/create-agent.input';
describe('Agent creation should succeed', () => {
let createdAgentId: string;
afterEach(async () => {
if (createdAgentId) {
await deleteOneAgent({
expectToFail: false,
input: { id: createdAgentId },
});
}
});
it('should create a basic custom agent with minimal input', async () => {
const { data } = await createOneAgent({
expectToFail: false,
input: {
label: 'Test Agent',
prompt: 'You are a helpful test assistant',
modelId: 'openai/gpt-4.1',
},
});
createdAgentId = data?.createOneAgent?.id;
expect(data.createOneAgent).toMatchObject({
id: expect.any(String),
name: 'testAgent',
label: 'Test Agent',
icon: null,
description: null,
prompt: 'You are a helpful test assistant',
modelId: 'openai/gpt-4.1',
responseFormat: { type: 'text' },
roleId: null,
isCustom: true,
modelConfiguration: null,
evaluationInputs: [],
});
});
it('should create agent with all optional fields', async () => {
const input = {
name: 'customAgentName',
label: 'Custom Agent Label',
icon: 'IconRobot',
description: 'A custom agent with all fields specified',
prompt: 'You are a specialized assistant for testing',
modelId: 'openai/gpt-5.2',
responseFormat: { type: 'text' },
modelConfiguration: {
webSearch: {
enabled: true,
configuration: {
maxTokens: 1000,
temperature: 0.7,
},
},
twitterSearch: {
enabled: true,
configuration: {},
},
},
evaluationInputs: ['test input 1', 'test input 2'],
} as const satisfies CreateAgentInput;
const { data } = await createOneAgent({
expectToFail: false,
input,
});
createdAgentId = data?.createOneAgent?.id;
expect(data.createOneAgent).toMatchObject({
id: expect.any(String),
...input,
});
});
it('should create agent with JSON response format', async () => {
const { data } = await createOneAgent({
expectToFail: false,
input: {
label: 'JSON Response Agent',
prompt: 'Return structured JSON data',
modelId: 'openai/gpt-4.1',
responseFormat: {
type: 'json',
schema: {
type: 'object',
properties: {
result: { type: 'string' },
confidence: { type: 'number' },
},
},
},
},
});
createdAgentId = data?.createOneAgent?.id;
expect(data.createOneAgent).toMatchObject({
id: expect.any(String),
label: 'JSON Response Agent',
prompt: 'Return structured JSON data',
responseFormat: {
type: 'json',
schema: {
type: 'object',
properties: {
result: { type: 'string' },
confidence: { type: 'number' },
},
},
},
});
});
it('should create agent and automatically compute name from label', async () => {
const { data } = await createOneAgent({
expectToFail: false,
input: {
label: 'My Test Agent With Spaces',
prompt: 'Testing name computation',
modelId: 'openai/gpt-4.1',
},
});
createdAgentId = data?.createOneAgent?.id;
expect(data.createOneAgent).toMatchObject({
id: expect.any(String),
name: 'myTestAgentWithSpaces',
label: 'My Test Agent With Spaces',
});
});
it('should sanitize input by trimming whitespace', async () => {
const { data } = await createOneAgent({
expectToFail: false,
input: {
name: ' agentWithSpaces ',
label: ' Agent With Spaces ',
icon: ' IconRobot ',
description: ' Description with spaces ',
prompt: ' Prompt with spaces ',
modelId: 'openai/gpt-4.1',
},
});
createdAgentId = data?.createOneAgent?.id;
expect(data.createOneAgent).toMatchObject({
id: expect.any(String),
name: 'agentWithSpaces',
label: 'Agent With Spaces',
icon: 'IconRobot',
description: 'Description with spaces',
prompt: 'Prompt with spaces',
});
});
it('should create agent with role assignment', async () => {
// First, create a role that can be assigned to agents
const { data: roleData } = await createOneRole({
expectToFail: false,
input: {
label: 'Test Agent Role',
description: 'A role for agent testing',
canUpdateAllSettings: false,
canAccessAllTools: true,
canReadAllObjectRecords: true,
canUpdateAllObjectRecords: false,
canSoftDeleteAllObjectRecords: false,
canDestroyAllObjectRecords: false,
canBeAssignedToUsers: false,
canBeAssignedToAgents: true,
canBeAssignedToApiKeys: false,
},
});
const createdRoleId = roleData?.createOneRole?.id;
// Create agent with role assignment
const { data } = await createOneAgent({
expectToFail: false,
input: {
label: 'Agent With Role',
prompt: 'Agent with role assignment',
modelId: 'openai/gpt-4.1',
roleId: createdRoleId,
},
});
createdAgentId = data?.createOneAgent?.id;
expect(data.createOneAgent).toMatchObject({
id: expect.any(String),
label: 'Agent With Role',
prompt: 'Agent with role assignment',
modelId: 'openai/gpt-4.1',
roleId: createdRoleId,
isCustom: true,
});
// Delete the agent first so its role_target is removed; otherwise
// deleting the role would refuse to orphan the agent (the workspace
// default role isn't agent-assignable).
await deleteOneAgent({
expectToFail: false,
input: { id: createdAgentId },
});
createdAgentId = '';
await deleteOneRole({
expectToFail: false,
input: { idToDelete: createdRoleId },
});
});
});