Skip to content

The open alternative to Salesforce, designed for AI.

Align agent execution with caller context (#27394)

Paul Rastoin5410e53b6086
diff --git a/packages/twenty-server/src/engine/core-modules/auth/token/services/application-token.service.ts b/packages/twenty-server/src/engine/core-modules/auth/token/services/application-token.service.ts
index d460c27e34d..97a62cc8d8c 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/token/services/application-token.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/token/services/application-token.service.ts
@@ -47,25 +47,25 @@ export class ApplicationTokenService {
applicationId,
userWorkspaceId,
userId,
+ expiresIn,
}: {
workspaceId: string;
applicationId: string;
userWorkspaceId?: string;
userId?: string;
+ expiresIn?: string;
}): Promise<AuthToken> {
await this.validateWorkspaceAndApplication(workspaceId, applicationId);
- const expiresIn = this.twentyConfigService.get(
- 'APPLICATION_ACCESS_TOKEN_EXPIRES_IN',
- );
-
return this.signApplicationToken({
workspaceId,
applicationId,
userWorkspaceId,
userId,
tokenType: JwtTokenTypeEnum.APPLICATION_ACCESS,
- expiresIn,
+ expiresIn:
+ expiresIn ??
+ this.twentyConfigService.get('APPLICATION_ACCESS_TOKEN_EXPIRES_IN'),
});
}
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tool.module.ts b/packages/twenty-server/src/engine/core-modules/tool/tool.module.ts
index cfe7f3182d1..9c6bc52e2f5 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tool.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/tool.module.ts
@@ -2,10 +2,10 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
+import { TokenModule } from 'src/engine/core-modules/auth/token/token.module';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { FileModule } from 'src/engine/core-modules/file/file.module';
-import { JwtModule } from 'src/engine/core-modules/jwt/jwt.module';
import { RecordShareModule } from 'src/engine/core-modules/record-share/record-share.module';
import { SecureHttpClientModule } from 'src/engine/core-modules/secure-http-client/secure-http-client.module';
import { CreateCalendarEventTool } from 'src/engine/core-modules/tool/tools/calendar-tool/create-calendar-event-tool';
@@ -37,7 +37,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
ApplicationModule,
FeatureFlagModule,
FileModule,
- JwtModule,
+ TokenModule,
RecordShareModule,
SecureHttpClientModule,
WorkspaceCacheModule,
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/code-interpreter-tool/__tests__/code-interpreter-tool.sender.spec.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/code-interpreter-tool/__tests__/code-interpreter-tool.sender.spec.ts
index 4b7ce89c1d8..efe9d665e36 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/code-interpreter-tool/__tests__/code-interpreter-tool.sender.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/code-interpreter-tool/__tests__/code-interpreter-tool.sender.spec.ts
@@ -1,74 +1,237 @@
+import { Test } from '@nestjs/testing';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { withWorkspaceAuthContext } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
-import { CodeInterpreterTool } from 'src/engine/core-modules/tool/tools/code-interpreter-tool/code-interpreter-tool';
+import { ApplicationTokenService } from 'src/engine/core-modules/auth/token/services/application-token.service';
import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { CodeInterpreterService } from 'src/engine/core-modules/code-interpreter/code-interpreter.service';
+import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
+import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';
+import { FileService } from 'src/engine/core-modules/file/services/file.service';
+import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
+import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';
+import { CodeInterpreterTool } from 'src/engine/core-modules/tool/tools/code-interpreter-tool/code-interpreter-tool';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-describe('Code interpreter sender credentials', () => {
- it.each([undefined, 'application'])(
- 'preserves application scope %s in the sandbox token and session identity',
- async (applicationId) => {
- const interpreter = {
- execute: jest.fn().mockResolvedValue({
- exitCode: 0,
- stdout: '',
- stderr: '',
- files: [],
- }),
- };
- const jwt = {
- signAsyncOrThrow: jest.fn().mockResolvedValue('scoped-token'),
- };
- const tool = new CodeInterpreterTool(
- interpreter as never,
- {} as never,
- {} as never,
- {} as never,
- {} as never,
- {} as never,
- { get: () => 'http://localhost:3000' } as never,
- jwt as never,
- );
- await withWorkspaceAuthContext(
+const SERVER_URL = 'http://localhost:3000';
+const WORKSPACE_ID = 'workspace-id';
+const USER_ID = 'user-id';
+const USER_WORKSPACE_ID = 'user-workspace-id';
+const CALLING_APPLICATION_ID = 'calling-application-id';
+const WORKSPACE_CUSTOM_APPLICATION_ID = 'workspace-custom-application-id';
+
+const SESSION_TOKEN_TYPES = [
+ JwtTokenTypeEnum.ACCESS,
+ JwtTokenTypeEnum.PLAYGROUND,
+ JwtTokenTypeEnum.WORKSPACE_AGNOSTIC,
+];
+
+const buildUserContext = (
+ applicationFields: Record<string, unknown> = {},
+): WorkspaceAuthContext =>
+ ({
+ type: 'user',
+ workspace: { id: WORKSPACE_ID },
+ user: { id: USER_ID },
+ userWorkspaceId: USER_WORKSPACE_ID,
+ workspaceMemberId: 'workspace-member-id',
+ ...applicationFields,
+ }) as WorkspaceAuthContext;
+
+const runInterpreter = async (authContext?: WorkspaceAuthContext) => {
+ const codeInterpreterService = {
+ execute: jest.fn().mockResolvedValue({
+ exitCode: 0,
+ stdout: '',
+ stderr: '',
+ files: [],
+ }),
+ };
+ const jwtWrapperService = {
+ signAsyncOrThrow: jest.fn().mockResolvedValue('sandbox-token'),
+ };
+
+ const module = await Test.createTestingModule({
+ providers: [
+ CodeInterpreterTool,
+ { provide: CodeInterpreterService, useValue: codeInterpreterService },
+ { provide: FileStorageService, useValue: {} },
+ { provide: FileService, useValue: {} },
+ { provide: FileUrlService, useValue: {} },
+ { provide: SecureHttpClientService, useValue: {} },
+ { provide: TwentyConfigService, useValue: { get: () => SERVER_URL } },
+ { provide: JwtWrapperService, useValue: jwtWrapperService },
+ {
+ provide: ApplicationService,
+ useValue: {
+ findWorkspaceTwentyStandardAndCustomApplicationOrThrow: jest
+ .fn()
+ .mockResolvedValue({
+ workspaceCustomFlatApplication: {
+ id: WORKSPACE_CUSTOM_APPLICATION_ID,
+ },
+ }),
+ },
+ },
+ {
+ provide: ApplicationTokenService,
+ useValue: new ApplicationTokenService(
+ jwtWrapperService as never,
+ {
+ findOne: jest.fn().mockResolvedValue({ id: WORKSPACE_ID }),
+ } as never,
+ {
+ findOne: jest.fn(
+ async (
+ _workspaceId: string,
+ { where }: { where: { id: string } },
+ ) => ({ id: where.id }),
+ ),
+ } as never,
+ { get: jest.fn().mockReturnValue('30m') } as never,
+ ),
+ },
+ ],
+ }).compile();
+
+ const tool = module.get(CodeInterpreterTool);
+
+ const execute = () =>
+ tool.execute(
+ { code: "print('hello')" },
+ {
+ workspaceId: WORKSPACE_ID,
+ userId: USER_ID,
+ userWorkspaceId: USER_WORKSPACE_ID,
+ threadId: 'thread',
+ },
+ );
+
+ const output = isDefined(authContext)
+ ? await withWorkspaceAuthContext(authContext, execute)
+ : await execute();
+
+ expect(output.success).toBe(true);
+
+ const signedPayloads = jwtWrapperService.signAsyncOrThrow.mock.calls.map(
+ ([payload]) => payload,
+ );
+
+ for (const payload of signedPayloads) {
+ expect(SESSION_TOKEN_TYPES).not.toContain(payload.type);
+ }
+
+ return {
+ signAsyncOrThrow: jwtWrapperService.signAsyncOrThrow,
+ sandboxContext: codeInterpreterService.execute.mock.calls[0][2],
+ };
+};
+
+describe('Code interpreter sandbox token', () => {
+ it.each([
+ [
+ 'an application driving the chat for the person',
+ buildUserContext({ application: { id: CALLING_APPLICATION_ID } }),
+ CALLING_APPLICATION_ID,
+ ],
+ [
+ 'an application running its agent as the person',
+ buildUserContext({ viaApplication: { id: CALLING_APPLICATION_ID } }),
+ CALLING_APPLICATION_ID,
+ ],
+ [
+ 'the person with no application, through the workspace custom application',
+ buildUserContext(),
+ WORKSPACE_CUSTOM_APPLICATION_ID,
+ ],
+ ])(
+ 'signs a 5-minute application token bound to the person for %s',
+ async (_, authContext, expectedApplicationId) => {
+ const { signAsyncOrThrow, sandboxContext } =
+ await runInterpreter(authContext);
+
+ expect(signAsyncOrThrow).toHaveBeenCalledTimes(1);
+ expect(signAsyncOrThrow).toHaveBeenCalledWith(
{
- type: 'user',
- workspace: { id: 'workspace' },
- userWorkspaceId: 'sender',
- application: applicationId ? { id: applicationId } : undefined,
- } as never,
- () =>
- tool.execute(
- { code: "print('hello')" },
- {
- workspaceId: 'workspace',
- userId: 'user',
- userWorkspaceId: 'sender',
- threadId: 'thread',
- },
- ),
- );
- expect(jwt.signAsyncOrThrow).toHaveBeenCalledWith(
- expect.objectContaining({
- type: applicationId
- ? JwtTokenTypeEnum.APPLICATION_ACCESS
- : JwtTokenTypeEnum.ACCESS,
- userWorkspaceId: 'sender',
- userId: 'user',
- workspaceId: 'workspace',
- ...(applicationId
- ? { applicationId, sub: applicationId }
- : { sub: 'user' }),
- }),
+ sub: expectedApplicationId,
+ type: JwtTokenTypeEnum.APPLICATION_ACCESS,
+ workspaceId: WORKSPACE_ID,
+ applicationId: expectedApplicationId,
+ userId: USER_ID,
+ userWorkspaceId: USER_WORKSPACE_ID,
+ },
{ expiresIn: '5m' },
);
- expect(interpreter.execute).toHaveBeenCalledWith(
- expect.any(String),
- [],
- expect.objectContaining({
- sessionId: 'workspace:thread',
- actorKey: `sender:${applicationId ?? 'direct'}`,
- env: expect.objectContaining({ TWENTY_API_TOKEN: 'scoped-token' }),
- }),
- expect.any(Object),
- );
+ expect(sandboxContext).toEqual({
+ sessionId: `${WORKSPACE_ID}:thread`,
+ actorKey: `${USER_WORKSPACE_ID}:${expectedApplicationId}`,
+ env: {
+ TWENTY_SERVER_URL: SERVER_URL,
+ TWENTY_API_TOKEN: 'sandbox-token',
+ },
+ });
},
);
+
+ it('signs a 5-minute application token bound to nobody for an application running on its own', async () => {
+ const { signAsyncOrThrow, sandboxContext } = await runInterpreter({
+ type: 'application',
+ workspace: { id: WORKSPACE_ID },
+ application: { id: CALLING_APPLICATION_ID },
+ } as WorkspaceAuthContext);
+
+ expect(signAsyncOrThrow).toHaveBeenCalledTimes(1);
+ expect(signAsyncOrThrow).toHaveBeenCalledWith(
+ {
+ sub: CALLING_APPLICATION_ID,
+ type: JwtTokenTypeEnum.APPLICATION_ACCESS,
+ workspaceId: WORKSPACE_ID,
+ applicationId: CALLING_APPLICATION_ID,
+ },
+ { expiresIn: '5m' },
+ );
+ expect(sandboxContext.env).toEqual({
+ TWENTY_SERVER_URL: SERVER_URL,
+ TWENTY_API_TOKEN: 'sandbox-token',
+ });
+ });
+
+ it.each([
+ [
+ 'an API key',
+ {
+ type: 'apiKey',
+ workspace: { id: WORKSPACE_ID },
+ apiKey: { id: 'api-key-id' },
+ } as WorkspaceAuthContext,
+ ],
+ [
+ 'the system',
+ {
+ type: 'system',
+ workspace: { id: WORKSPACE_ID },
+ } as WorkspaceAuthContext,
+ ],
+ ['no auth context', undefined],
+ ])('hands the sandbox no token for %s', async (_, authContext) => {
+ const { signAsyncOrThrow, sandboxContext } =
+ await runInterpreter(authContext);
+
+ expect(signAsyncOrThrow).not.toHaveBeenCalled();
+ expect(sandboxContext.env).toEqual({ TWENTY_SERVER_URL: SERVER_URL });
+ });
+
+ it('never shares a sandbox between the person running it directly and an application acting for them', async () => {
+ const { sandboxContext: directRun } =
+ await runInterpreter(buildUserContext());
+ const { sandboxContext: applicationRun } = await runInterpreter(
+ buildUserContext({ viaApplication: { id: CALLING_APPLICATION_ID } }),
+ );
+
+ expect(directRun.sessionId).toBe(applicationRun.sessionId);
+ expect(directRun.actorKey).not.toBe(applicationRun.actorKey);
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/code-interpreter-tool/code-interpreter-tool.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/code-interpreter-tool/code-interpreter-tool.ts
index ad2d427b912..ab9af20b59b 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/code-interpreter-tool/code-interpreter-tool.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/code-interpreter-tool/code-interpreter-tool.ts
@@ -1,7 +1,8 @@
import { isDefined } from 'twenty-shared/utils';
+import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
import { workspaceAuthContextStorage } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
-import { type ApplicationAccessTokenJwtPayload } from 'src/engine/core-modules/auth/types/application-access-token-jwt-payload.type';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { Injectable, Logger } from '@nestjs/common';
import path from 'path';
@@ -20,13 +21,11 @@ import {
} from 'src/engine/core-modules/code-interpreter/drivers/interfaces/code-interpreter-driver.interface';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
-import { type AccessTokenJwtPayload } from 'src/engine/core-modules/auth/types/access-token-jwt-payload.type';
-import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
+import { ApplicationTokenService } from 'src/engine/core-modules/auth/token/services/application-token.service';
import { CodeInterpreterService } from 'src/engine/core-modules/code-interpreter/code-interpreter.service';
import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';
import { FileService } from 'src/engine/core-modules/file/services/file.service';
-import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';
import { CodeInterpreterInputZodSchema } from 'src/engine/core-modules/tool/tools/code-interpreter-tool/code-interpreter-tool.schema';
import { TWENTY_MCP_HELPER } from 'src/engine/core-modules/tool/tools/code-interpreter-tool/twenty-mcp-helper.const';
@@ -39,7 +38,13 @@ import { type ToolInput } from 'src/engine/core-modules/tool/types/tool-input.ty
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
import { type Tool } from 'src/engine/core-modules/tool/types/tool.type';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
+
+type SandboxPrincipal = {
+ workspaceId: string;
+ applicationId: string;
+ userId?: string;
+ userWorkspaceId?: string;
+};
@Injectable()
export class CodeInterpreterTool implements Tool {
@@ -58,7 +63,7 @@ export class CodeInterpreterTool implements Tool {
private readonly applicationService: ApplicationService,
private readonly secureHttpClientService: SecureHttpClientService,
private readonly twentyConfigService: TwentyConfigService,
- private readonly jwtWrapperService: JwtWrapperService,
+ private readonly applicationTokenService: ApplicationTokenService,
) {}
private buildExecutionState(
@@ -86,13 +91,7 @@ export class CodeInterpreterTool implements Tool {
parameters: ToolInput,
context: ToolExecutionContext,
): Promise<ToolOutput> {
- const {
- workspaceId,
- userId,
- userWorkspaceId,
- threadId,
- onCodeExecutionUpdate,
- } = context;
+ const { workspaceId, threadId, onCodeExecutionUpdate } = context;
const { code, files } = parameters as CodeInterpreterInput;
const executionId = v4();
const startTime = Date.now();
@@ -117,20 +116,15 @@ export class CodeInterpreterTool implements Tool {
);
const serverUrl = this.twentyConfigService.get('SERVER_URL');
- const authContext = workspaceAuthContextStorage.getStore();
- const applicationId =
- isDefined(authContext) && isUserAuthContext(authContext)
- ? authContext.application?.id
- : undefined;
- const sessionToken = await this.generateSessionToken({
- workspaceId,
- userId,
- userWorkspaceId,
- applicationId,
- });
+ const sandboxPrincipal = await this.resolveSandboxPrincipal(
+ workspaceAuthContextStorage.getStore(),
+ );
+ const sandboxToken = isDefined(sandboxPrincipal)
+ ? await this.generateSandboxToken(sandboxPrincipal)
+ : undefined;
this.logger.debug(
- `MCP session: workspaceId=${workspaceId}, userId=${userId}, userWorkspaceId=${userWorkspaceId}, serverUrl=${serverUrl}`,
+ `MCP session: workspaceId=${workspaceId}, applicationId=${sandboxPrincipal?.applicationId}, userWorkspaceId=${sandboxPrincipal?.userWorkspaceId}, serverUrl=${serverUrl}`,
);
const codeWithHelper = TWENTY_MCP_HELPER + '\n\n' + code;
@@ -141,10 +135,12 @@ export class CodeInterpreterTool implements Tool {
{
env: {
TWENTY_SERVER_URL: serverUrl,
- TWENTY_API_TOKEN: sessionToken,
+ ...(isDefined(sandboxToken)
+ ? { TWENTY_API_TOKEN: sandboxToken }
+ : {}),
},
sessionId: threadId ? `${workspaceId}:${threadId}` : undefined,
- actorKey: `${userWorkspaceId ?? 'anonymous'}:${applicationId ?? 'direct'}`,
+ actorKey: `${sandboxPrincipal?.userWorkspaceId ?? 'anonymous'}:${sandboxPrincipal?.applicationId ?? 'none'}`,
},
{
onStdout: (line) => {
@@ -315,39 +311,57 @@ export class CodeInterpreterTool implements Tool {
return inputFiles;
}
- private async generateSessionToken({
- workspaceId,
- userId,
- userWorkspaceId,
- applicationId,
- }: {
- workspaceId: string;
- userId?: string;
- userWorkspaceId?: string;
- applicationId?: string;
- }): Promise<string> {
- const payload: AccessTokenJwtPayload | ApplicationAccessTokenJwtPayload =
- isDefined(applicationId)
- ? {
- sub: applicationId,
- type: JwtTokenTypeEnum.APPLICATION_ACCESS,
- workspaceId,
- applicationId,
- userId,
- userWorkspaceId,
- }
- : {
- sub: userId ?? workspaceId,
- type: JwtTokenTypeEnum.ACCESS,
- workspaceId,
- userId: userId ?? workspaceId,
- userWorkspaceId: userWorkspaceId ?? workspaceId,
- authProvider: AuthProviderEnum.Password,
- };
-
- return this.jwtWrapperService.signAsyncOrThrow(payload, {
- expiresIn: '5m',
- });
+ private async resolveSandboxPrincipal(
+ authContext: WorkspaceAuthContext | undefined,
+ ): Promise<SandboxPrincipal | undefined> {
+ if (!isDefined(authContext)) {
+ return undefined;
+ }
+
+ const workspaceId = authContext.workspace.id;
+
+ if (isApplicationAuthContext(authContext)) {
+ return { workspaceId, applicationId: authContext.application.id };
+ }
+
+ if (!isUserAuthContext(authContext)) {
+ return undefined;
+ }
+
+ const applicationId =
+ authContext.application?.id ??
+ authContext.viaApplication?.id ??
+ (await this.findWorkspaceCustomApplicationId(workspaceId));
+
+ return {
+ workspaceId,
+ applicationId,
+ userId: authContext.user.id,
+ userWorkspaceId: authContext.userWorkspaceId,
+ };
+ }
+
+ private async findWorkspaceCustomApplicationId(
+ workspaceId: string,
+ ): Promise<string> {
+ const { workspaceCustomFlatApplication } =
+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId },
+ );
+
+ return workspaceCustomFlatApplication.id;
+ }
+
+ private async generateSandboxToken(
+ sandboxPrincipal: SandboxPrincipal,
+ ): Promise<string> {
+ const { token } =
+ await this.applicationTokenService.generateApplicationAccessToken({
+ ...sandboxPrincipal,
+ expiresIn: '5m',
+ });
+
+ return token;
}
private async uploadSingleFile(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts
index 1bceddd77e5..8595cea8100 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module.ts
@@ -1,6 +1,7 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
+import { ApiKeyModule } from 'src/engine/core-modules/api-key/api-key.module';
import { ApplicationLookupModule } from 'src/engine/core-modules/application/application-lookup/application-lookup.module';
import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
@@ -44,6 +45,7 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
AiBillingModule,
AiAgentModule,
AiAgentRoleModule,
+ ApiKeyModule,
ApplicationLookupModule,
CacheLockModule,
FileUrlModule,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts
index 7f7e2d70f71..1067996fe96 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts
@@ -4,10 +4,12 @@ import { Args, Mutation } from '@nestjs/graphql';
import { PermissionFlagType } from 'twenty-shared/constants';
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
+import { type FlatApiKey } from 'src/engine/core-modules/api-key/types/flat-api-key.type';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { BillingGraphqlApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-graphql-api-exception.filter';
import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
+import { AuthApiKey } from 'src/engine/decorators/auth/auth-api-key.decorator';
import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';
import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
import { AuthWorkspaceMemberId } from 'src/engine/decorators/auth/auth-workspace-member-id.decorator';
@@ -55,6 +57,7 @@ export class AgentRunResolver {
userWorkspaceId: string | undefined,
@AuthApplication({ allowUndefined: true })
callerApplication: FlatApplication | undefined,
+ @AuthApiKey() callerApiKey: FlatApiKey | undefined,
@AuthWorkspaceMemberId()
workspaceMemberId: string | undefined,
): Promise<RunAgentResultDTO> {
@@ -63,6 +66,7 @@ export class AgentRunResolver {
requestUserWorkspaceId: userWorkspaceId ?? null,
requestWorkspaceMemberId: workspaceMemberId ?? null,
callerApplication,
+ callerApiKey,
input,
});
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts
index ce4180ba6aa..296eeffc2a8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-run.service.spec.ts
@@ -1,8 +1,15 @@
import { Logger } from '@nestjs/common';
+import {
+ ApiKeyException,
+ ApiKeyExceptionCode,
+} from 'src/engine/core-modules/api-key/exceptions/api-key.exception';
import { AgentRunService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service';
import { buildAgentRunThreadId } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-run-thread-id.util';
-import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
const WORKSPACE = { id: 'workspace-id' } as never;
const APPLICATION = { id: 'application-id' };
@@ -33,6 +40,7 @@ const buildService = () => {
buildRunAsWorkspaceMemberContext: jest.fn().mockResolvedValue({
actorContext: RUN_AS_ACTOR,
authContext: {
+ type: 'user',
userWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
workspaceMemberId: RUN_AS_ACTOR.workspaceMemberId,
},
@@ -40,20 +48,46 @@ const buildService = () => {
}),
buildApplicationAgentContext: jest.fn().mockResolvedValue({
application: APPLICATION,
- authContext: { type: 'application' },
+ authContext: {
+ type: 'application',
+ workspace: WORKSPACE,
+ application: APPLICATION,
+ },
agentRoleId: 'agent-role-id',
}),
};
+ const apiKeyRoleService = {
+ getRoleIdForApiKeyId: jest.fn().mockResolvedValue('api-key-role-id'),
+ };
+ const apiKeyService = {
+ validateApiKey: jest.fn().mockResolvedValue({
+ id: 'api-key-id',
+ workspaceId: 'workspace-id',
+ name: 'Agent integration',
+ expiresAt: new Date('2099-01-01'),
+ createdAt: new Date('2026-01-01'),
+ updatedAt: new Date('2026-01-01'),
+ revokedAt: null,
+ }),
+ };
const service = new AgentRunService(
agentActorContextService as never,
agentRunnerService as never,
{} as never,
+ apiKeyRoleService as never,
+ apiKeyService as never,
{ findById: jest.fn().mockResolvedValue(APPLICATION) } as never,
{ findOne: jest.fn().mockResolvedValue(AGENT) } as never,
);
- return { service, agentRunnerService };
+ return {
+ service,
+ agentRunnerService,
+ agentActorContextService,
+ apiKeyRoleService,
+ apiKeyService,
+ };
};
const runInput = (agentRunnerService: { run: jest.Mock }) =>
@@ -65,15 +99,17 @@ const run = (
{
isCalledByApplication = true,
requestUserWorkspaceId = null,
+ requestWorkspaceMemberId = null,
}: {
isCalledByApplication?: boolean;
requestUserWorkspaceId?: string | null;
+ requestWorkspaceMemberId?: string | null;
} = {},
) =>
service.run({
workspace: WORKSPACE,
requestUserWorkspaceId,
- requestWorkspaceMemberId: null,
+ requestWorkspaceMemberId,
callerApplication: isCalledByApplication
? (APPLICATION as never)
: undefined,
@@ -186,8 +222,8 @@ describe('AgentRunService', () => {
actorContext: RUN_AS_ACTOR,
turnCreatedBy: RUN_AS_ACTOR,
userWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
- runAsRoleId: 'role-id',
- rolePermissionConfig: { intersectionOf: ['role-id'] },
+ additionalRoleRestrictionIds: ['role-id'],
+ rolePermissionConfig: { intersectionOf: ['agent-role-id', 'role-id'] },
conversationActor: {
type: 'user',
workspaceMemberId: RUN_AS_ACTOR.workspaceMemberId,
@@ -224,16 +260,193 @@ describe('AgentRunService', () => {
{ input: userInput('Who is our biggest customer?') },
{
isCalledByApplication: false,
- requestUserWorkspaceId: 'caller-user-workspace-id',
+ requestUserWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
+ requestWorkspaceMemberId: RUN_AS_ACTOR.workspaceMemberId,
},
);
expect(runInput(agentRunnerService).prompt).toMatchObject({
- senderUserWorkspaceId: 'caller-user-workspace-id',
+ senderUserWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
senderApplicationId: null,
});
});
+ it.each([false, true])(
+ 'keeps the member identity when an implicit member run resumes (application caller: %s)',
+ async (isCalledByApplication) => {
+ const { service, agentRunnerService, agentActorContextService } =
+ buildService();
+
+ await run(
+ service,
+ { prompt: 'Hello' },
+ {
+ isCalledByApplication,
+ requestUserWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
+ requestWorkspaceMemberId: RUN_AS_ACTOR.workspaceMemberId,
+ },
+ );
+
+ const { caller, executionContext } = runInput(agentRunnerService);
+
+ expect(executionContext).toMatchObject({
+ authContext: {
+ type: 'user',
+ userWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
+ },
+ rolePermissionConfig: {
+ intersectionOf: ['agent-role-id', 'role-id'],
+ },
+ turnCreatedBy: RUN_AS_ACTOR,
+ });
+
+ agentActorContextService.buildRunAsWorkspaceMemberContext.mockResolvedValue(
+ {
+ actorContext: RUN_AS_ACTOR,
+ authContext: {
+ type: 'user',
+ userWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
+ workspaceMemberId: RUN_AS_ACTOR.workspaceMemberId,
+ },
+ roleId: 'updated-member-role-id',
+ },
+ );
+
+ const resumedContext = await service.buildExecutionContext({
+ workspaceId: 'workspace-id',
+ caller: JSON.parse(JSON.stringify(caller)),
+ });
+
+ expect(resumedContext).toMatchObject({
+ authContext: executionContext.authContext,
+ conversationActor: {
+ type: 'user',
+ workspaceMemberId: RUN_AS_ACTOR.workspaceMemberId,
+ },
+ rolePermissionConfig: {
+ intersectionOf: ['agent-role-id', 'updated-member-role-id'],
+ },
+ });
+ },
+ );
+
+ it('releases an implicit member run when the member leaves', async () => {
+ const { service, agentRunnerService, agentActorContextService } =
+ buildService();
+
+ await run(
+ service,
+ { prompt: 'Hello' },
+ {
+ isCalledByApplication: false,
+ requestUserWorkspaceId: RUN_AS_USER_WORKSPACE_ID,
+ requestWorkspaceMemberId: RUN_AS_ACTOR.workspaceMemberId,
+ },
+ );
+
+ agentActorContextService.buildRunAsWorkspaceMemberContext.mockRejectedValue(
+ new AiException(
+ 'Member left',
+ AiExceptionCode.RUN_AS_WORKSPACE_MEMBER_NOT_FOUND,
+ ),
+ );
+
+ await expect(
+ service.getWaitingState({
+ workspaceId: 'workspace-id',
+ caller: runInput(agentRunnerService).caller,
+ }),
+ ).resolves.toBe('GONE');
+ });
+
+ it('keeps the API key and reloads its role when a run resumes', async () => {
+ const { service, agentRunnerService, apiKeyRoleService } = buildService();
+
+ await service.run({
+ workspace: WORKSPACE,
+ requestUserWorkspaceId: null,
+ requestWorkspaceMemberId: null,
+ callerApiKey: { id: 'api-key-id' } as never,
+ input: {
+ agentUniversalIdentifier: AGENT.universalIdentifier,
+ prompt: 'Hello',
+ },
+ });
+
+ const { caller, executionContext } = runInput(agentRunnerService);
+
+ expect(executionContext).toMatchObject({
+ authContext: { type: 'apiKey', apiKey: { id: 'api-key-id' } },
+ rolePermissionConfig: {
+ intersectionOf: ['agent-role-id', 'api-key-role-id'],
+ },
+ });
+
+ apiKeyRoleService.getRoleIdForApiKeyId.mockResolvedValue(
+ 'updated-key-role-id',
+ );
+
+ await expect(
+ service.buildExecutionContext({
+ workspaceId: 'workspace-id',
+ caller: JSON.parse(JSON.stringify(caller)),
+ }),
+ ).resolves.toMatchObject({
+ authContext: { type: 'apiKey', apiKey: { id: 'api-key-id' } },
+ rolePermissionConfig: {
+ intersectionOf: ['agent-role-id', 'updated-key-role-id'],
+ },
+ });
+ });
+
+ it.each([
+ ApiKeyExceptionCode.API_KEY_REVOKED,
+ ApiKeyExceptionCode.API_KEY_EXPIRED,
+ ApiKeyExceptionCode.API_KEY_NOT_FOUND,
+ ])(
+ 'releases a waiting run when its API key is unavailable: %s',
+ async (code) => {
+ const { service, agentRunnerService, apiKeyService } = buildService();
+
+ await service.run({
+ workspace: WORKSPACE,
+ requestUserWorkspaceId: null,
+ requestWorkspaceMemberId: null,
+ callerApiKey: { id: 'api-key-id' } as never,
+ input: {
+ agentUniversalIdentifier: AGENT.universalIdentifier,
+ prompt: 'Hello',
+ },
+ });
+
+ apiKeyService.validateApiKey.mockRejectedValue(
+ new ApiKeyException('Key unavailable', code),
+ );
+
+ await expect(
+ service.getWaitingState({
+ workspaceId: 'workspace-id',
+ caller: runInput(agentRunnerService).caller,
+ }),
+ ).resolves.toBe('GONE');
+ await expect(
+ service.buildExecutionContext({
+ workspaceId: 'workspace-id',
+ caller: runInput(agentRunnerService).caller,
+ }),
+ ).rejects.toMatchObject({ code });
+ },
+ );
+
+ it('refuses a caller without a member, application or API key', async () => {
+ const { service, agentRunnerService } = buildService();
+
+ await expect(
+ run(service, { prompt: 'Hello' }, { isCalledByApplication: false }),
+ ).rejects.toMatchObject({ code: AiExceptionCode.RUN_AGENT_NOT_ALLOWED });
+ expect(agentRunnerService.run).not.toHaveBeenCalled();
+ });
+
it('reports a run that ran out of credits', async () => {
const { service, agentRunnerService } = buildService();
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
index 659ae744159..8822a9e2a8f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
@@ -161,18 +161,15 @@ export class AgentAsyncExecutorService {
// preloading the few granted object schemas saves the model a learn_tools round trip
private async buildPreloadedRegistryTools({
toolContext,
- runAsRoleId,
additionalRoleRestrictionIds,
additionalExcludedToolNames = [],
}: {
toolContext: RegistryToolContext;
- runAsRoleId?: string;
additionalRoleRestrictionIds?: string[];
additionalExcludedToolNames?: readonly string[];
}): Promise<{ tools: ToolSet; proposableTools: ProposableTools }> {
const rolePermissionConfig = buildAgentRolePermissionConfig({
agentRoleId: toolContext.roleId,
- runAsRoleId,
additionalRoleRestrictionIds,
});
const preloadedToolContext = { ...toolContext, rolePermissionConfig };
@@ -210,12 +207,10 @@ export class AgentAsyncExecutorService {
// learn_tools / execute_tool instead, scoped by composed role permissions rather than explicit grants only
private async buildLazyRegistryTools({
toolContext: baseToolContext,
- runAsRoleId,
additionalRoleRestrictionIds,
additionalExcludedToolNames = [],
}: {
toolContext: RegistryToolContext;
- runAsRoleId?: string;
additionalRoleRestrictionIds?: string[];
additionalExcludedToolNames?: readonly string[];
}): Promise<{
@@ -223,17 +218,17 @@ export class AgentAsyncExecutorService {
catalogSection: string;
proposableTools: ProposableTools;
}> {
- const toolContext: ToolContext =
- isDefined(runAsRoleId) || isNonEmptyArray(additionalRoleRestrictionIds)
- ? {
- ...baseToolContext,
- rolePermissionConfig: buildAgentRolePermissionConfig({
- agentRoleId: baseToolContext.roleId,
- runAsRoleId,
- additionalRoleRestrictionIds,
- }),
- }
- : baseToolContext;
+ const toolContext: ToolContext = isNonEmptyArray(
+ additionalRoleRestrictionIds,
+ )
+ ? {
+ ...baseToolContext,
+ rolePermissionConfig: buildAgentRolePermissionConfig({
+ agentRoleId: baseToolContext.roleId,
+ additionalRoleRestrictionIds,
+ }),
+ }
+ : baseToolContext;
const {
workspaceId,
roleId,
@@ -327,7 +322,6 @@ export class AgentAsyncExecutorService {
actorContext,
authContext,
userWorkspaceId,
- runAsRoleId,
additionalRoleRestrictionIds,
usageOperationType,
},
@@ -425,14 +419,12 @@ export class AgentAsyncExecutorService {
toolLoadingStrategy === 'lazy'
? await this.buildLazyRegistryTools({
toolContext,
- runAsRoleId,
additionalRoleRestrictionIds,
additionalExcludedToolNames,
})
: {
...(await this.buildPreloadedRegistryTools({
toolContext,
- runAsRoleId,
additionalRoleRestrictionIds,
additionalExcludedToolNames,
})),
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts
index 47e9bcfb3a3..fb27b67c298 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run.service.ts
@@ -14,19 +14,28 @@ import {
type RunAgentThread,
} from 'twenty-shared/application';
import { type ActorMetadata } from 'twenty-shared/types';
-import { isDefined, isPlainObject } from 'twenty-shared/utils';
+import { isDefined, isNonEmptyArray, isPlainObject } from 'twenty-shared/utils';
import { z } from 'zod';
import { buildActorMetadataFromAuthContext } from 'src/engine/core-modules/actor/utils/build-actor-metadata-from-auth-context.util';
import { buildCreatedByFromApplication } from 'src/engine/core-modules/actor/utils/build-created-by-from-application.util';
+import { ApiKeyException } from 'src/engine/core-modules/api-key/exceptions/api-key.exception';
+import { ApiKeyRoleService } from 'src/engine/core-modules/api-key/services/api-key-role.service';
+import { ApiKeyService } from 'src/engine/core-modules/api-key/services/api-key.service';
+import { type FlatApiKey } from 'src/engine/core-modules/api-key/types/flat-api-key.type';
+import { fromApiKeyEntityToFlat } from 'src/engine/core-modules/api-key/utils/from-api-key-entity-to-flat.util';
import { ApplicationLookupService } from 'src/engine/core-modules/application/application-lookup/application-lookup.service';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
import { workspaceAuthContextStorage } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
+import { type ApplicationWorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { buildApiKeyAuthContext } from 'src/engine/core-modules/auth/utils/build-api-key-auth-context.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
import { AgentRunCallerHandlerRegistryService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-caller-handler-registry.service';
import { AgentRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service';
+import { type AgentRunCallerContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-context.type';
import { type AgentRunCaller } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller.type';
import { type AgentRunCallerInput } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-input.type';
import { type AgentRunCallerHandler } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-handler.type';
@@ -58,11 +67,19 @@ type RunAgentServiceInput = {
const agentApiRunCallerRefSchema = z.object({
agentId: z.string(),
runAsWorkspaceMemberId: z.string().nullable(),
+ // who a run that names no member acts as, when it is not the agent's application
+ callerWorkspaceMemberId: z.string().optional(),
+ callerApiKeyId: z.string().optional(),
requestUserWorkspaceId: z.string().nullable(),
// the request's own actor cannot be read back once it is over
createdBy: z.custom<ActorMetadata>(isPlainObject),
});
+type AgentApiRunCallerRef = Omit<
+ z.infer<typeof agentApiRunCallerRefSchema>,
+ 'createdBy'
+>;
+
// Runs an agent for the runAgent API. A run that waits goes on later with the API call as its
// caller, and its reply lands in its conversation
@Injectable()
@@ -73,6 +90,8 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
private readonly agentActorContextService: AgentActorContextService,
private readonly agentRunnerService: AgentRunnerService,
private readonly callerHandlerRegistry: AgentRunCallerHandlerRegistryService,
+ private readonly apiKeyRoleService: ApiKeyRoleService,
+ private readonly apiKeyService: ApiKeyService,
private readonly applicationLookupService: ApplicationLookupService,
@InjectWorkspaceScopedRepository(AgentEntity)
private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,
@@ -87,12 +106,14 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
requestUserWorkspaceId,
requestWorkspaceMemberId,
callerApplication,
+ callerApiKey,
input,
}: {
workspace: FlatWorkspace;
requestUserWorkspaceId: string | null;
requestWorkspaceMemberId: string | null;
callerApplication?: FlatApplication;
+ callerApiKey?: FlatApiKey;
input: RunAgentServiceInput;
}): Promise<RunAgentResult> {
const messages = resolveRunAgentMessagesOrThrow({
@@ -177,16 +198,38 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
})
: randomUUID();
+ const callerRef: AgentApiRunCallerRef = {
+ agentId: agent.id,
+ runAsWorkspaceMemberId: input.runAsWorkspaceMemberId ?? null,
+ ...(isDefined(runAsContext)
+ ? {}
+ : this.resolveCallerRef({
+ callerApplication,
+ callerApiKey,
+ requestUserWorkspaceId,
+ requestWorkspaceMemberId,
+ })),
+ requestUserWorkspaceId,
+ };
+
+ const executionContext = await this.buildRunExecutionContext({
+ workspaceId: workspace.id,
+ ref: callerRef,
+ });
+
+ const memberUserWorkspaceId = isUserAuthContext(
+ executionContext.authContext,
+ )
+ ? executionContext.authContext.userWorkspaceId
+ : null;
+
+ const createdBy =
+ executionContext.actorContext ??
+ this.buildRunCreator({ callerApplication, application });
+
const caller: AgentRunCaller = {
type: 'AGENT_API_RUN',
- ref: {
- agentId: agent.id,
- runAsWorkspaceMemberId: input.runAsWorkspaceMemberId ?? null,
- requestUserWorkspaceId,
- createdBy:
- runAsContext?.actorContext ??
- this.buildRunCreator({ callerApplication, application }),
- },
+ ref: { ...callerRef, createdBy },
};
try {
@@ -209,16 +252,10 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
agent,
prompt: {
messages,
- // a member calling without runAs still sent the input, while an app's call has no member behind it
- senderUserWorkspaceId:
- runAsContext?.authContext.userWorkspaceId ??
- (isDefined(callerApplication) ? null : requestUserWorkspaceId),
+ senderUserWorkspaceId: memberUserWorkspaceId,
senderApplicationId: callerApplication?.id ?? null,
},
- executionContext: await this.buildExecutionContext({
- workspaceId: workspace.id,
- caller,
- }),
+ executionContext: { ...executionContext, turnCreatedBy: createdBy },
});
return {
@@ -258,6 +295,21 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
caller,
}: AgentRunCallerInput): Promise<AgentRunExecutionContext> {
const ref = agentApiRunCallerRefSchema.parse(caller.ref);
+
+ return {
+ ...(await this.buildRunExecutionContext({ workspaceId, ref })),
+ turnCreatedBy: ref.createdBy,
+ };
+ }
+
+ // run() builds the context before its caller, whose turn author depends on it
+ private async buildRunExecutionContext({
+ workspaceId,
+ ref,
+ }: {
+ workspaceId: string;
+ ref: AgentApiRunCallerRef;
+ }): Promise<Omit<AgentRunExecutionContext, 'turnCreatedBy'>> {
const agent = await this.agentRepository.findOne(workspaceId, {
where: { id: ref.agentId },
});
@@ -283,22 +335,45 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
})
: undefined;
+ const { authContext, actorContext, callerRoleId }: AgentRunCallerContext =
+ isDefined(runAsContext)
+ ? {
+ authContext: runAsContext.authContext,
+ actorContext: runAsContext.actorContext,
+ callerRoleId: runAsContext.roleId,
+ }
+ : await this.resolveCallerContext({
+ workspaceId,
+ ref,
+ agentAuthContext: agentContext.authContext,
+ });
+
+ const memberWorkspaceMemberId = isUserAuthContext(authContext)
+ ? authContext.workspaceMemberId
+ : null;
+
+ // a run never exceeds the agent's application, whoever calls it
+ const roleRestrictionIds = [
+ callerRoleId,
+ agentContext.application.defaultRoleId,
+ ].filter(isDefined);
+
+ const additionalRoleRestrictionIds = isNonEmptyArray(roleRestrictionIds)
+ ? roleRestrictionIds
+ : undefined;
+
return {
- authContext: runAsContext?.authContext ?? agentContext.authContext,
- actorContext: runAsContext?.actorContext,
- turnCreatedBy: ref.createdBy,
+ authContext,
+ actorContext,
userWorkspaceId:
runAsContext?.authContext.userWorkspaceId ?? ref.requestUserWorkspaceId,
rolePermissionConfig: buildAgentRolePermissionConfig({
agentRoleId: agentContext.agentRoleId,
- runAsRoleId: runAsContext?.roleId,
+ additionalRoleRestrictionIds,
}),
- runAsRoleId: runAsContext?.roleId,
- conversationActor: isDefined(runAsContext)
- ? {
- type: 'user',
- workspaceMemberId: runAsContext.authContext.workspaceMemberId,
- }
+ additionalRoleRestrictionIds,
+ conversationActor: isDefined(memberWorkspaceMemberId)
+ ? { type: 'user', workspaceMemberId: memberWorkspaceMemberId }
: { type: 'application', applicationId: agentContext.application.id },
usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,
};
@@ -308,8 +383,12 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
workspaceId,
caller,
}: AgentRunCallerInput): Promise<OwnerWaitingState> {
- const { agentId, runAsWorkspaceMemberId } =
- agentApiRunCallerRefSchema.parse(caller.ref);
+ const {
+ agentId,
+ runAsWorkspaceMemberId,
+ callerWorkspaceMemberId,
+ callerApiKeyId,
+ } = agentApiRunCallerRefSchema.parse(caller.ref);
const agent = await this.agentRepository.findOne(workspaceId, {
where: { id: agentId },
select: ['id'],
@@ -319,14 +398,30 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
return 'GONE';
}
- if (!isDefined(runAsWorkspaceMemberId)) {
+ if (isDefined(callerApiKeyId)) {
+ try {
+ await this.apiKeyService.validateApiKey(callerApiKeyId, workspaceId);
+
+ return 'WAITING';
+ } catch (error) {
+ if (error instanceof ApiKeyException) {
+ return 'GONE';
+ }
+
+ throw error;
+ }
+ }
+
+ const workspaceMemberId = runAsWorkspaceMemberId ?? callerWorkspaceMemberId;
+
+ if (!isDefined(workspaceMemberId)) {
return 'WAITING';
}
// a run acting as a member who left can never continue, so it must release its thread
try {
await this.agentActorContextService.buildRunAsWorkspaceMemberContext({
- workspaceMemberId: runAsWorkspaceMemberId,
+ workspaceMemberId,
workspaceId,
});
@@ -343,6 +438,76 @@ export class AgentRunService implements AgentRunCallerHandler, OnModuleInit {
}
}
+ private resolveCallerRef({
+ callerApplication,
+ callerApiKey,
+ requestUserWorkspaceId,
+ requestWorkspaceMemberId,
+ }: {
+ callerApplication?: FlatApplication;
+ callerApiKey?: FlatApiKey;
+ requestUserWorkspaceId: string | null;
+ requestWorkspaceMemberId: string | null;
+ }): Pick<AgentApiRunCallerRef, 'callerWorkspaceMemberId' | 'callerApiKeyId'> {
+ if (isDefined(requestWorkspaceMemberId)) {
+ return { callerWorkspaceMemberId: requestWorkspaceMemberId };
+ }
+
+ if (isDefined(callerApplication) && !isDefined(requestUserWorkspaceId)) {
+ return {};
+ }
+
+ if (isDefined(callerApiKey)) {
+ return { callerApiKeyId: callerApiKey.id };
+ }
+
+ throw new AiException(
+ 'Running an agent requires a workspace member, an API key or the agent application',
+ AiExceptionCode.RUN_AGENT_NOT_ALLOWED,
+ );
+ }
+
+ private async resolveCallerContext({
+ workspaceId,
+ ref,
+ agentAuthContext,
+ }: {
+ workspaceId: string;
+ ref: AgentApiRunCallerRef;
+ agentAuthContext: ApplicationWorkspaceAuthContext;
+ }): Promise<AgentRunCallerContext> {
+ if (isDefined(ref.callerWorkspaceMemberId)) {
+ const { authContext, actorContext, roleId } =
+ await this.agentActorContextService.buildRunAsWorkspaceMemberContext({
+ workspaceMemberId: ref.callerWorkspaceMemberId,
+ workspaceId,
+ viaApplication: agentAuthContext.application,
+ });
+
+ return { authContext, actorContext, callerRoleId: roleId };
+ }
+
+ if (isDefined(ref.callerApiKeyId)) {
+ const apiKey = await this.apiKeyService.validateApiKey(
+ ref.callerApiKeyId,
+ workspaceId,
+ );
+
+ return {
+ authContext: buildApiKeyAuthContext({
+ workspace: agentAuthContext.workspace,
+ apiKey: fromApiKeyEntityToFlat(apiKey),
+ }),
+ callerRoleId: await this.apiKeyRoleService.getRoleIdForApiKeyId(
+ apiKey.id,
+ workspaceId,
+ ),
+ };
+ }
+
+ return { authContext: agentAuthContext };
+ }
+
private buildRunCreator({
callerApplication,
application,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-context.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-context.type.ts
new file mode 100644
index 00000000000..7e253746ff0
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-caller-context.type.ts
@@ -0,0 +1,9 @@
+import { type ActorMetadata } from 'twenty-shared/types';
+
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+
+export type AgentRunCallerContext = {
+ authContext: WorkspaceAuthContext;
+ actorContext?: ActorMetadata;
+ callerRoleId?: string;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts
index 6a8bc2c6924..8b92593abf7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-execution-context.type.ts
@@ -15,8 +15,6 @@ export type AgentRunExecutionContext = {
userWorkspaceId: string | null;
// what the run itself can read, such as the record an awaited event is about
rolePermissionConfig: RolePermissionConfig;
- // replaces the agent's own role, for a run acting as a member
- runAsRoleId?: string;
// narrows the agent's own role, such as to the application a run belongs to
additionalRoleRestrictionIds?: string[];
// who the continued conversation is read for, so turns others acted on read as theirs
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.ts
index f3c7aae351c..056532d1bb9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/build-agent-role-permission-config.util.spec.ts
@@ -1,30 +1,12 @@
import { buildAgentRolePermissionConfig } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util';
describe('buildAgentRolePermissionConfig', () => {
- it('keeps the agent role alone when there is no run-as role', () => {
+ it('keeps the agent role alone without restrictions', () => {
expect(
buildAgentRolePermissionConfig({ agentRoleId: 'agent-role-id' }),
).toEqual({ intersectionOf: ['agent-role-id'] });
});
- it('uses the member role alone in run-as mode', () => {
- expect(
- buildAgentRolePermissionConfig({
- agentRoleId: 'agent-role-id',
- runAsRoleId: 'run-as-role-id',
- }),
- ).toEqual({ intersectionOf: ['run-as-role-id'] });
- });
-
- it('does not involve the agent role even when the member holds it', () => {
- expect(
- buildAgentRolePermissionConfig({
- agentRoleId: 'agent-role-id',
- runAsRoleId: 'agent-role-id',
- }),
- ).toEqual({ intersectionOf: ['agent-role-id'] });
- });
-
it('bounds the agent role by the roles of the run that executes it', () => {
expect(
buildAgentRolePermissionConfig({
@@ -40,16 +22,6 @@ describe('buildAgentRolePermissionConfig', () => {
});
});
- it('narrows the run-as role instead of replacing it with the additional restrictions', () => {
- expect(
- buildAgentRolePermissionConfig({
- agentRoleId: 'agent-role-id',
- runAsRoleId: 'member-role-id',
- additionalRoleRestrictionIds: ['application-role-id'],
- }),
- ).toEqual({ intersectionOf: ['member-role-id', 'application-role-id'] });
- });
-
it('does not repeat a role shared by the agent and the run', () => {
expect(
buildAgentRolePermissionConfig({
@@ -63,7 +35,7 @@ describe('buildAgentRolePermissionConfig', () => {
expect(
buildAgentRolePermissionConfig({
agentRoleId: undefined,
- additionalRoleRestrictionIds: ['application-role-id'],
+ additionalRoleRestrictionIds: ['member-role-id'],
}),
).toEqual({ intersectionOf: [] });
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.ts
index a36d07b2627..7e3add1656d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/build-agent-role-permission-config.util.ts
@@ -4,21 +4,19 @@ import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-perm
export const buildAgentRolePermissionConfig = ({
agentRoleId,
- runAsRoleId,
additionalRoleRestrictionIds = [],
}: {
agentRoleId: string | undefined;
- runAsRoleId?: string;
additionalRoleRestrictionIds?: string[];
}): RolePermissionConfig => {
- const baseRoleId = isDefined(runAsRoleId) ? runAsRoleId : agentRoleId;
-
// without a role the agent reads nothing, however its restrictions narrow it
- if (!isDefined(baseRoleId)) {
+ if (!isDefined(agentRoleId)) {
return { intersectionOf: [] };
}
return {
- intersectionOf: [...new Set([baseRoleId, ...additionalRoleRestrictionIds])],
+ intersectionOf: [
+ ...new Set([agentRoleId, ...additionalRoleRestrictionIds]),
+ ],
};
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/__tests__/agent-trigger-runner.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/__tests__/agent-trigger-runner.service.spec.ts
index 7b7f48d48cf..e7484fbc299 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/__tests__/agent-trigger-runner.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/__tests__/agent-trigger-runner.service.spec.ts
@@ -130,6 +130,27 @@ describe('AgentTriggerRunnerService', () => {
);
});
+ it("should restrict the agent's role to its application's default role", async () => {
+ findApplication.mockResolvedValue({
+ id: 'application-id',
+ name: 'App',
+ defaultRoleId: 'application-role-id',
+ });
+
+ await service.run(JOB_DATA);
+
+ expect(runAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ executionContext: expect.objectContaining({
+ rolePermissionConfig: {
+ intersectionOf: [AGENT_ROLE_ID, 'application-role-id'],
+ },
+ additionalRoleRestrictionIds: ['application-role-id'],
+ }),
+ }),
+ );
+ });
+
it.each([
['the agent was deleted', () => findAgent.mockResolvedValue(null)],
[
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts
index 0a9ae6f3fca..8fabdcc4113 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service.ts
@@ -181,6 +181,11 @@ export class AgentTriggerRunnerService
return null;
}
+ // the agent never exceeds its application, as in its runAgent runs
+ const additionalRoleRestrictionIds = isDefined(application.defaultRoleId)
+ ? [application.defaultRoleId]
+ : undefined;
+
const actingAgent = { id: agent.id, label: agent.label };
const createdBy = buildCreatedByFromAgent({
agent: actingAgent,
@@ -195,7 +200,11 @@ export class AgentTriggerRunnerService
actorContext: createdBy,
turnCreatedBy: createdBy,
userWorkspaceId: null,
- rolePermissionConfig: buildAgentRolePermissionConfig({ agentRoleId }),
+ rolePermissionConfig: buildAgentRolePermissionConfig({
+ agentRoleId,
+ additionalRoleRestrictionIds,
+ }),
+ additionalRoleRestrictionIds,
usageOperationType: UsageOperationType.AI_WORKFLOW_TOKEN,
},
};
diff --git a/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts
index e189a21596f..8673e77175b 100644
--- a/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts
+++ b/packages/twenty-server/test/integration/ai/suites/agent-run-wait.integration-spec.ts
@@ -22,6 +22,8 @@ import { type AgentChatStreamingService } from 'src/engine/metadata-modules/ai/a
import { type AgentTriggerRunnerService } from 'src/engine/metadata-modules/ai/ai-agent-trigger/services/agent-trigger-runner.service';
import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+import { API_KEY_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/api-key-data-seeds.constant';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
const workspaceId = SEED_APPLE_WORKSPACE_ID;
@@ -118,6 +120,16 @@ const findWaitCallStatus = async (threadId: string) => {
return part?.status;
};
+const findCallerRoleId = async (roleTargetId: string): Promise<string> => {
+ const [{ roleId }] = await global.testDataSource.query(
+ `SELECT "roleId" FROM core."roleTarget"
+ WHERE $1 IN ("userWorkspaceId", "apiKeyId") AND "workspaceId" = $2`,
+ [roleTargetId, workspaceId],
+ );
+
+ return roleId;
+};
+
const findTurnStatuses = async (threadId: string) =>
(
await global.testDataSource.query(
@@ -352,6 +364,82 @@ describe('agent runs that wait (integration)', () => {
expect(executeAgent).toHaveBeenCalledTimes(2);
});
+ it.each([
+ {
+ title: 'the member whose session made it',
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ authContext: {
+ type: 'user',
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ },
+ roleTargetId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ },
+ {
+ title: 'the API key that made it',
+ token: API_KEY_ACCESS_TOKEN,
+ authContext: {
+ type: 'apiKey',
+ apiKey: expect.objectContaining({ id: API_KEY_DATA_SEED_IDS.ID_1 }),
+ },
+ roleTargetId: API_KEY_DATA_SEED_IDS.ID_1,
+ },
+ ])(
+ 'goes on with a waiting runAgent call as $title',
+ async ({ token, authContext, roleTargetId }) => {
+ const executeAgent = mockAgent(waitingResult(), replyingResult);
+
+ const response = await makeMetadataApiRequest(
+ {
+ query: gql`
+ mutation RunAgent($input: RunAgentInput!) {
+ runAgent(input: $input) {
+ threadId
+ status
+ }
+ }
+ `,
+ variables: {
+ input: {
+ agentUniversalIdentifier,
+ input: [{ role: 'user', content: 'Follow up tomorrow' }],
+ },
+ },
+ },
+ token,
+ );
+
+ const { threadId, status } = response.body.data.runAgent;
+
+ expect(status).toBe('SUSPENDED');
+
+ await expectEventually(async () => {
+ expect(await findTurnStatuses(threadId)).toEqual([
+ 'completed',
+ 'completed',
+ ]);
+ });
+
+ expect(await findSuspensions('AGENT_API_RUN', agentId)).toEqual([]);
+ expect(
+ executeAgent.mock.calls.map(
+ ([execution]) => execution.executionContext.authContext,
+ ),
+ ).toEqual([
+ expect.objectContaining(authContext),
+ expect.objectContaining(authContext),
+ ]);
+
+ const roleRestrictionIds = [await findCallerRoleId(roleTargetId)];
+
+ expect(
+ executeAgent.mock.calls.map(
+ ([execution]) =>
+ execution.executionContext.additionalRoleRestrictionIds,
+ ),
+ ).toEqual([roleRestrictionIds, roleRestrictionIds]);
+ },
+ );
+
it('refuses a message to a thread whose run waits, and takes it once the run finished', async () => {
const executeAgent = mockAgent(
waitingResult(),
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/__snapshots__/failing-code-interpreter-token-on-account-operations.integration-spec.ts.snap b/packages/twenty-server/test/integration/graphql/suites/user-session/__snapshots__/failing-code-interpreter-token-on-account-operations.integration-spec.ts.snap
new file mode 100644
index 00000000000..01fefdbb86d
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/__snapshots__/failing-code-interpreter-token-on-account-operations.integration-spec.ts.snap
@@ -0,0 +1,105 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Account operations with a code interpreter sandbox token should fail for Jane running the interpreter directly should refuse currentUser selecting availableWorkspaces 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "FORBIDDEN_EXCEPTION",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint requires a user session",
+ "name": "ForbiddenError",
+}
+`;
+
+exports[`Account operations with a code interpreter sandbox token should fail for Jane running the interpreter directly should refuse to consent to an OAuth client, minting no authorization code 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`Account operations with a code interpreter sandbox token should fail for Jane running the interpreter directly should refuse to list the application authorizations 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`Account operations with a code interpreter sandbox token should fail for Jane running the interpreter directly should refuse to mint a playground token 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`Account operations with a code interpreter sandbox token should fail for Jane running the interpreter directly should refuse to revoke an application authorization, which stays live 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`Account operations with a code interpreter sandbox token should fail for an agent an application runs as Jane should refuse currentUser selecting availableWorkspaces 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "subCode": "FORBIDDEN_EXCEPTION",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint requires a user session",
+ "name": "ForbiddenError",
+}
+`;
+
+exports[`Account operations with a code interpreter sandbox token should fail for an agent an application runs as Jane should refuse to consent to an OAuth client, minting no authorization code 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`Account operations with a code interpreter sandbox token should fail for an agent an application runs as Jane should refuse to list the application authorizations 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`Account operations with a code interpreter sandbox token should fail for an agent an application runs as Jane should refuse to mint a playground token 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`Account operations with a code interpreter sandbox token should fail for an agent an application runs as Jane should refuse to revoke an application authorization, which stays live 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/__snapshots__/failing-code-interpreter-token-on-administration-operations.integration-spec.ts.snap b/packages/twenty-server/test/integration/graphql/suites/user-session/__snapshots__/failing-code-interpreter-token-on-administration-operations.integration-spec.ts.snap
new file mode 100644
index 00000000000..4ff2d679cc5
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/__snapshots__/failing-code-interpreter-token-on-administration-operations.integration-spec.ts.snap
@@ -0,0 +1,41 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Administration operations with a code interpreter sandbox token should fail for Jane running the interpreter directly should refuse to delete the workspace, which still exists 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`Administration operations with a code interpreter sandbox token should fail for Jane running the interpreter directly should refuse to raise the Member role, which stays unchanged 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`Administration operations with a code interpreter sandbox token should fail for an agent an application runs as Jane should refuse to delete the workspace, which still exists 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
+
+exports[`Administration operations with a code interpreter sandbox token should fail for an agent an application runs as Jane should refuse to raise the Member role, which stays unchanged 1`] = `
+{
+ "extensions": {
+ "code": "FORBIDDEN",
+ "userFriendlyMessage": "You do not have permission to perform this action.",
+ },
+ "message": "This endpoint is not available to this caller",
+}
+`;
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/failing-code-interpreter-token-on-account-operations.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/failing-code-interpreter-token-on-account-operations.integration-spec.ts
new file mode 100644
index 00000000000..3410cb363f6
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/failing-code-interpreter-token-on-account-operations.integration-spec.ts
@@ -0,0 +1,189 @@
+import { authorizeApp } from 'test/integration/graphql/suites/user-session/utils/authorize-app.util';
+import { currentUserApplicationAuthorizations } from 'test/integration/graphql/suites/user-session/utils/current-user-application-authorizations.util';
+import { currentUser } from 'test/integration/graphql/suites/user-session/utils/current-user.util';
+import { generatePlaygroundToken } from 'test/integration/graphql/suites/user-session/utils/generate-playground-token.util';
+import { revokeApplicationAuthorization } from 'test/integration/graphql/suites/user-session/utils/revoke-application-authorization.util';
+import {
+ type CodeInterpreterSandboxTokens,
+ captureCodeInterpreterSandboxTokens,
+} from 'test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-tokens.util';
+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithVariable,
+ setupApplicationWithVariable,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-variable.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import {
+ type EachTestingContext,
+ eachTestingContextFilter,
+} from 'twenty-shared/testing';
+import { isDefined } from 'twenty-shared/utils';
+import { v4 as uuidv4 } from 'uuid';
+
+import {
+ AppTokenEntity,
+ AppTokenType,
+} from 'src/engine/core-modules/app-token/app-token.entity';
+import { ApplicationAuthorizationEntity } from 'src/engine/core-modules/application/application-authorization/application-authorization.entity';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
+
+type GlobalTestContext = CodeInterpreterSandboxTokens & {
+ janeApplicationAuthorizationId: string;
+};
+
+type TestContext = {
+ token: (globalContext: GlobalTestContext) => string;
+};
+
+const sandboxTokenTestCases: EachTestingContext<TestContext>[] = [
+ {
+ title: 'for an agent an application runs as Jane',
+ context: {
+ token: (globalContext) => globalContext.applicationRunAsJaneToken,
+ },
+ },
+ {
+ title: 'for Jane running the interpreter directly',
+ context: { token: (globalContext) => globalContext.janeDirectRunToken },
+ },
+];
+
+const countAuthorizationCodes = () =>
+ getCoreRepository<AppTokenEntity>(AppTokenEntity).count({
+ where: {
+ userId: USER_DATA_SEED_IDS.JANE,
+ type: AppTokenType.AuthorizationCode,
+ },
+ });
+
+const findApplicationAuthorization = (id: string) =>
+ getCoreRepository<ApplicationAuthorizationEntity>(
+ ApplicationAuthorizationEntity,
+ ).findOne({ where: { id } });
+
+describe('Account operations with a code interpreter sandbox token should fail', () => {
+ let application: ApplicationWithVariable;
+ let globalTestContext: GlobalTestContext;
+
+ beforeAll(async () => {
+ application = await setupApplicationWithVariable({
+ name: 'Code Interpreter Account Probe',
+ variableKey: 'CODE_INTERPRETER_ACCOUNT_PROBE',
+ });
+
+ const sandboxTokens = await captureCodeInterpreterSandboxTokens({
+ applicationId: application.id,
+ });
+
+ const janeApplicationAuthorization =
+ await getCoreRepository<ApplicationAuthorizationEntity>(
+ ApplicationAuthorizationEntity,
+ ).save({
+ userId: USER_DATA_SEED_IDS.JANE,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ applicationId: application.id,
+ scopes: [],
+ lastAuthorizedAt: new Date(),
+ lastUsedAt: new Date(),
+ revokedAt: null,
+ });
+
+ globalTestContext = {
+ ...sandboxTokens,
+ janeApplicationAuthorizationId: janeApplicationAuthorization.id,
+ };
+ }, 120000);
+
+ afterAll(async () => {
+ if (!isDefined(application)) {
+ return;
+ }
+
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ });
+
+ describe.each(eachTestingContextFilter(sandboxTokenTestCases))(
+ '$title',
+ ({ context }) => {
+ it('should refuse to consent to an OAuth client, minting no authorization code', async () => {
+ const authorizationCodesBefore = await countAuthorizationCodes();
+
+ const { errors } = await authorizeApp({
+ input: {
+ clientId: uuidv4(),
+ redirectUrl: 'https://app.twenty.test/callback',
+ codeChallenge: 'a'.repeat(43),
+ },
+ token: context.token(globalTestContext),
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+
+ expect(await countAuthorizationCodes()).toBe(authorizationCodesBefore);
+ });
+
+ it('should refuse to list the application authorizations', async () => {
+ const { errors } = await currentUserApplicationAuthorizations({
+ token: context.token(globalTestContext),
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+
+ it('should refuse to revoke an application authorization, which stays live', async () => {
+ const { errors } = await revokeApplicationAuthorization({
+ input: {
+ applicationAuthorizationId:
+ globalTestContext.janeApplicationAuthorizationId,
+ },
+ token: context.token(globalTestContext),
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+
+ const applicationAuthorization = await findApplicationAuthorization(
+ globalTestContext.janeApplicationAuthorizationId,
+ );
+
+ expect(applicationAuthorization?.revokedAt).toBeNull();
+ });
+
+ it('should refuse to mint a playground token', async () => {
+ const { data, errors } = await generatePlaygroundToken({
+ token: context.token(globalTestContext),
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+
+ expect(data?.generatePlaygroundToken).toBeFalsy();
+ });
+
+ it('should refuse currentUser selecting availableWorkspaces', async () => {
+ const { errors } = await currentUser({
+ gqlFields: `
+ id
+ availableWorkspaces {
+ availableWorkspacesForSignIn {
+ id
+ }
+ }
+ `,
+ token: context.token(globalTestContext),
+ expectToFail: true,
+ });
+
+ expectOneNotInternalServerErrorSnapshot({ errors });
+ });
+ },
+ );
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/failing-code-interpreter-token-on-administration-operations.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/failing-code-interpreter-token-on-administration-operations.integration-spec.ts
new file mode 100644
index 00000000000..7e1fe409d77
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/failing-code-interpreter-token-on-administration-operations.integration-spec.ts
@@ -0,0 +1,130 @@
+import {
+ type CodeInterpreterSandboxTokens,
+ captureCodeInterpreterSandboxTokens,
+} from 'test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-tokens.util';
+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';
+import { ADMINISTRATION_OPERATION_QUERY_FACTORIES } from 'test/integration/metadata/suites/application/utils/administration-operation-query-factories.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithVariable,
+ setupApplicationWithVariable,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-variable.util';
+import { updateOneRoleQueryFactory } from 'test/integration/metadata/suites/role/utils/update-one-role-query-factory.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { SystemPermissionFlag } from 'twenty-shared/constants';
+import {
+ type EachTestingContext,
+ eachTestingContextFilter,
+} from 'twenty-shared/testing';
+import { isDefined } from 'twenty-shared/utils';
+
+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { MEMBER_ROLE_LABEL } from 'src/engine/metadata-modules/permissions/constants/member-role-label.constants';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+type TestContext = {
+ token: (globalContext: CodeInterpreterSandboxTokens) => string;
+};
+
+const sandboxTokenTestCases: EachTestingContext<TestContext>[] = [
+ {
+ title: 'for an agent an application runs as Jane',
+ context: {
+ token: (globalContext) => globalContext.applicationRunAsJaneToken,
+ },
+ },
+ {
+ title: 'for Jane running the interpreter directly',
+ context: { token: (globalContext) => globalContext.janeDirectRunToken },
+ },
+];
+
+const findMemberRole = async (): Promise<{
+ id: string;
+ canUpdateAllSettings: boolean;
+}> => {
+ const [role] = await globalThis.testDataSource.query(
+ `SELECT id, "canUpdateAllSettings" FROM core."role"
+ WHERE label = $1 AND "workspaceId" = $2`,
+ [MEMBER_ROLE_LABEL, SEED_APPLE_WORKSPACE_ID],
+ );
+
+ return role;
+};
+
+describe('Administration operations with a code interpreter sandbox token should fail', () => {
+ let application: ApplicationWithVariable;
+ let globalTestContext: CodeInterpreterSandboxTokens;
+
+ beforeAll(async () => {
+ application = await setupApplicationWithVariable({
+ name: 'Code Interpreter Administration Probe',
+ variableKey: 'CODE_INTERPRETER_ADMINISTRATION_PROBE',
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag.APPLICATIONS,
+ SystemPermissionFlag.ROLES,
+ SystemPermissionFlag.WORKSPACE,
+ ],
+ });
+
+ globalTestContext = await captureCodeInterpreterSandboxTokens({
+ applicationId: application.id,
+ });
+ }, 120000);
+
+ afterAll(async () => {
+ if (!isDefined(application)) {
+ return;
+ }
+
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ });
+
+ describe.each(eachTestingContextFilter(sandboxTokenTestCases))(
+ '$title',
+ ({ context }) => {
+ it('should refuse to raise the Member role, which stays unchanged', async () => {
+ const memberRoleBeforeAttempt = await findMemberRole();
+
+ const response = await makeMetadataApiRequest(
+ updateOneRoleQueryFactory({
+ input: {
+ idToUpdate: memberRoleBeforeAttempt.id,
+ updatePayload: { canUpdateAllSettings: true },
+ },
+ }),
+ context.token(globalTestContext),
+ );
+
+ expectOneNotInternalServerErrorSnapshot({
+ errors: response.body.errors,
+ });
+
+ expect(await findMemberRole()).toEqual(memberRoleBeforeAttempt);
+ });
+
+ it('should refuse to delete the workspace, which still exists', async () => {
+ const response = await makeMetadataApiRequest(
+ ADMINISTRATION_OPERATION_QUERY_FACTORIES.deleteCurrentWorkspace(),
+ context.token(globalTestContext),
+ );
+
+ expectOneNotInternalServerErrorSnapshot({
+ errors: response.body.errors,
+ });
+
+ const workspace = await getCoreRepository<WorkspaceEntity>(
+ WorkspaceEntity,
+ ).findOne({
+ where: { id: SEED_APPLE_WORKSPACE_ID },
+ withDeleted: true,
+ });
+
+ expect(workspace?.deletedAt).toBeNull();
+ });
+ },
+ );
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/successful-agent-run-conversation-for-caller.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/successful-agent-run-conversation-for-caller.integration-spec.ts
new file mode 100644
index 00000000000..0015ee00513
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/successful-agent-run-conversation-for-caller.integration-spec.ts
@@ -0,0 +1,256 @@
+import { type StepResult, type ToolSet } from 'ai';
+import { randomUUID } from 'node:crypto';
+import {
+ type AgentRunExecution,
+ captureAgentRunExecution,
+} from 'test/integration/graphql/suites/user-session/utils/capture-agent-run-execution.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithResources,
+ setupApplicationWithResources,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-resources.util';
+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+import {
+ type EachTestingContext,
+ eachTestingContextFilter,
+} from 'twenty-shared/testing';
+import { isDefined } from 'twenty-shared/utils';
+
+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+
+const WORKSPACE_SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+// history keeps a turn's tool calls only for the member who sent it
+const TOOL_CALL_STEPS = [
+ {
+ content: [
+ {
+ type: 'tool-call',
+ toolCallId: 'probe-call',
+ toolName: 'probe',
+ input: {},
+ },
+ {
+ type: 'tool-result',
+ toolCallId: 'probe-call',
+ toolName: 'probe',
+ input: {},
+ output: { isProbed: true },
+ },
+ ],
+ },
+] as unknown as StepResult<ToolSet>[];
+
+type GlobalTestContext = {
+ agentUniversalIdentifier: string;
+ applicationId: string;
+ applicationToken: string;
+ janeApplicationToken: string;
+ jonyApplicationToken: string;
+};
+
+type TestContext = {
+ token: (globalContext: GlobalTestContext) => string;
+ senderWorkspaceMemberId: string | null;
+ isSentThroughApplication: boolean;
+ creatorWorkspaceMemberId: string | null;
+};
+
+const recordedTurnTestCases: EachTestingContext<TestContext>[] = [
+ {
+ title: 'an application token issued for a member runs the agent',
+ context: {
+ token: (globalContext) => globalContext.janeApplicationToken,
+ senderWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ isSentThroughApplication: true,
+ creatorWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ },
+ },
+ {
+ title: 'a member session runs the agent',
+ context: {
+ token: () => APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ senderWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ isSentThroughApplication: false,
+ creatorWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ },
+ },
+ {
+ title: 'the application runs its own agent with no user',
+ context: {
+ token: (globalContext) => globalContext.applicationToken,
+ senderWorkspaceMemberId: null,
+ isSentThroughApplication: true,
+ creatorWorkspaceMemberId: null,
+ },
+ },
+];
+
+const findRecordedTurn = async (threadId: string) => {
+ const [[message], [turn]] = await Promise.all([
+ globalThis.testDataSource.query(
+ `SELECT "senderWorkspaceMemberId", "senderApplicationId"
+ FROM "${WORKSPACE_SCHEMA}"."agentMessage"
+ WHERE "threadId" = $1 AND role = $2`,
+ [threadId, AgentMessageRole.USER],
+ ),
+ globalThis.testDataSource.query(
+ `SELECT "createdByWorkspaceMemberId"
+ FROM "${WORKSPACE_SCHEMA}"."agentTurn"
+ WHERE "threadId" = $1`,
+ [threadId],
+ ),
+ ]);
+
+ return { ...message, ...turn };
+};
+
+const findPriorMessagePartTypes = ({ priorMessages }: AgentRunExecution) =>
+ (priorMessages ?? []).flatMap(({ parts }) => parts.map(({ type }) => type));
+
+describe('Agent run conversation should be recorded for the caller', () => {
+ let application: ApplicationWithResources;
+ let globalTestContext: GlobalTestContext;
+ const threadIds: string[] = [];
+
+ const runAgent = async ({
+ token,
+ threadKey,
+ steps,
+ }: {
+ token: string;
+ threadKey?: string;
+ steps?: StepResult<ToolSet>[];
+ }) => {
+ const execution = await captureAgentRunExecution({
+ agentUniversalIdentifier: globalTestContext.agentUniversalIdentifier,
+ token,
+ thread: isDefined(threadKey) ? { key: threadKey } : undefined,
+ steps,
+ });
+
+ if (!threadIds.includes(execution.threadId)) {
+ threadIds.push(execution.threadId);
+ }
+
+ return execution;
+ };
+
+ beforeAll(async () => {
+ application = await setupApplicationWithResources({
+ name: 'Agent Run Conversation Probe',
+ });
+
+ const [{ universalIdentifier: agentUniversalIdentifier }] =
+ await globalThis.testDataSource.query(
+ `SELECT "universalIdentifier" FROM core."agent" WHERE id = $1`,
+ [application.agentId],
+ );
+
+ const [applicationTokenPair, janeTokenPair, jonyTokenPair] =
+ await Promise.all([
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ }),
+ generateAppleAdminApplicationTokenPair({
+ applicationId: application.id,
+ }),
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ userId: USER_DATA_SEED_IDS.JONY,
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ }),
+ ]);
+
+ globalTestContext = {
+ agentUniversalIdentifier,
+ applicationId: application.id,
+ applicationToken: applicationTokenPair.applicationAccessToken.token,
+ janeApplicationToken: janeTokenPair.applicationAccessToken.token,
+ jonyApplicationToken: jonyTokenPair.applicationAccessToken.token,
+ };
+ }, 120000);
+
+ afterAll(async () => {
+ // no member is granted the threads runAgent creates, so the API cannot destroy them
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."agentChatThread" WHERE id = ANY($1)`,
+ [threadIds],
+ );
+
+ if (!isDefined(application)) {
+ return;
+ }
+
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ });
+
+ it.each(eachTestingContextFilter(recordedTurnTestCases))(
+ 'should record who sent the turn when $title',
+ async ({ context }) => {
+ const { threadId } = await runAgent({
+ token: context.token(globalTestContext),
+ });
+
+ expect(await findRecordedTurn(threadId)).toEqual({
+ senderWorkspaceMemberId: context.senderWorkspaceMemberId,
+ senderApplicationId: context.isSentThroughApplication
+ ? globalTestContext.applicationId
+ : null,
+ createdByWorkspaceMemberId: context.creatorWorkspaceMemberId,
+ });
+ },
+ );
+
+ it('should keep the full history for a member continuing their own thread', async () => {
+ const threadKey = randomUUID();
+
+ await runAgent({
+ token: globalTestContext.janeApplicationToken,
+ threadKey,
+ steps: TOOL_CALL_STEPS,
+ });
+
+ const execution = await runAgent({
+ token: globalTestContext.janeApplicationToken,
+ threadKey,
+ });
+
+ expect(findPriorMessagePartTypes(execution)).toContain('tool-probe');
+ });
+
+ it('should show a member only the text of a turn another member sent in the same thread', async () => {
+ const threadKey = randomUUID();
+
+ await runAgent({
+ token: globalTestContext.janeApplicationToken,
+ threadKey,
+ steps: TOOL_CALL_STEPS,
+ });
+
+ const execution = await runAgent({
+ token: globalTestContext.jonyApplicationToken,
+ threadKey,
+ });
+
+ expect(execution.executionContext.authContext).toMatchObject({
+ type: 'user',
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ });
+
+ const partTypes = findPriorMessagePartTypes(execution);
+
+ expect(partTypes).toContain('text');
+ expect(partTypes).not.toContain('tool-probe');
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/successful-agent-run-tool-role-for-caller.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/successful-agent-run-tool-role-for-caller.integration-spec.ts
new file mode 100644
index 00000000000..2565957ae4c
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/successful-agent-run-tool-role-for-caller.integration-spec.ts
@@ -0,0 +1,151 @@
+import { captureAgentRunExecution } from 'test/integration/graphql/suites/user-session/utils/capture-agent-run-execution.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithResources,
+ setupApplicationWithResources,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-resources.util';
+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+import {
+ type EachTestingContext,
+ eachTestingContextFilter,
+} from 'twenty-shared/testing';
+import { isDefined } from 'twenty-shared/utils';
+
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+import { API_KEY_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/api-key-data-seeds.constant';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+
+type GlobalTestContext = {
+ agentUniversalIdentifier: string;
+ applicationRoleId: string;
+ applicationToken: string;
+ janeApplicationToken: string;
+};
+
+type TestContext = {
+ token: (globalContext: GlobalTestContext) => string;
+ runAsWorkspaceMemberId?: string;
+ roleTargetId: string;
+};
+
+const callerRunTestCases: EachTestingContext<TestContext>[] = [
+ {
+ title: 'a member session runs another application agent',
+ context: {
+ token: () => APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ roleTargetId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ },
+ },
+ {
+ title: 'an application token issued for a member runs its own agent',
+ context: {
+ token: (globalContext) => globalContext.janeApplicationToken,
+ roleTargetId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ },
+ },
+ {
+ title: 'the application runs its agent as a member',
+ context: {
+ token: (globalContext) => globalContext.applicationToken,
+ runAsWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ roleTargetId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ },
+ },
+ {
+ title: 'an API key runs an application agent',
+ context: {
+ token: () => API_KEY_ACCESS_TOKEN,
+ roleTargetId: API_KEY_DATA_SEED_IDS.ID_1,
+ },
+ },
+];
+
+const findCallerRoleId = async (roleTargetId: string): Promise<string> => {
+ const [{ roleId }] = await globalThis.testDataSource.query(
+ `SELECT "roleId" FROM core."roleTarget"
+ WHERE $1 IN ("userWorkspaceId", "apiKeyId") AND "workspaceId" = $2`,
+ [roleTargetId, SEED_APPLE_WORKSPACE_ID],
+ );
+
+ return roleId;
+};
+
+describe('Agent run tools should be limited to the caller role', () => {
+ let application: ApplicationWithResources;
+ let globalTestContext: GlobalTestContext;
+
+ beforeAll(async () => {
+ application = await setupApplicationWithResources({
+ name: 'Agent Run Tool Role Probe',
+ });
+
+ const [{ universalIdentifier: agentUniversalIdentifier }] =
+ await globalThis.testDataSource.query(
+ `SELECT "universalIdentifier" FROM core."agent" WHERE id = $1`,
+ [application.agentId],
+ );
+
+ const [{ defaultRoleId: applicationRoleId }] =
+ await globalThis.testDataSource.query(
+ `SELECT "defaultRoleId" FROM core."application" WHERE id = $1`,
+ [application.id],
+ );
+
+ const [applicationTokenPair, janeApplicationTokenPair] = await Promise.all([
+ generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ }),
+ generateAppleAdminApplicationTokenPair({
+ applicationId: application.id,
+ }),
+ ]);
+
+ globalTestContext = {
+ agentUniversalIdentifier,
+ applicationRoleId,
+ applicationToken: applicationTokenPair.applicationAccessToken.token,
+ janeApplicationToken:
+ janeApplicationTokenPair.applicationAccessToken.token,
+ };
+ }, 120000);
+
+ afterAll(async () => {
+ if (!isDefined(application)) {
+ return;
+ }
+
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ });
+
+ it.each(eachTestingContextFilter(callerRunTestCases))(
+ 'should restrict the agent role to the caller and application roles when $title',
+ async ({ context }) => {
+ const { executionContext } = await captureAgentRunExecution({
+ agentUniversalIdentifier: globalTestContext.agentUniversalIdentifier,
+ token: context.token(globalTestContext),
+ runAsWorkspaceMemberId: context.runAsWorkspaceMemberId,
+ });
+
+ expect(executionContext.additionalRoleRestrictionIds).toEqual([
+ await findCallerRoleId(context.roleTargetId),
+ globalTestContext.applicationRoleId,
+ ]);
+ },
+ );
+
+ it('should restrict the agent role to the application role when the application runs its own agent', async () => {
+ const { executionContext } = await captureAgentRunExecution({
+ agentUniversalIdentifier: globalTestContext.agentUniversalIdentifier,
+ token: globalTestContext.applicationToken,
+ });
+
+ expect(executionContext.additionalRoleRestrictionIds).toEqual([
+ globalTestContext.applicationRoleId,
+ ]);
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/successful-code-interpreter-token-for-agent-run-caller.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/successful-code-interpreter-token-for-agent-run-caller.integration-spec.ts
new file mode 100644
index 00000000000..7dd94ecd0ea
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/successful-code-interpreter-token-for-agent-run-caller.integration-spec.ts
@@ -0,0 +1,125 @@
+import { captureAgentRunExecution } from 'test/integration/graphql/suites/user-session/utils/capture-agent-run-execution.util';
+import { captureCodeInterpreterSandboxToken } from 'test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-token.util';
+import { currentUser } from 'test/integration/graphql/suites/user-session/utils/current-user.util';
+import { pingMcp } from 'test/integration/graphql/suites/user-session/utils/ping-mcp.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithResources,
+ setupApplicationWithResources,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-resources.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+import { isDefined } from 'twenty-shared/utils';
+
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
+
+type GlobalTestContext = {
+ agentUniversalIdentifier: string;
+ applicationRoleId: string;
+ applicationToken: string;
+};
+
+const captureSandboxTokenForAgentRun = async ({
+ globalTestContext,
+ token,
+}: {
+ globalTestContext: GlobalTestContext;
+ token: string;
+}) =>
+ captureCodeInterpreterSandboxToken({
+ authContext: (
+ await captureAgentRunExecution({
+ agentUniversalIdentifier: globalTestContext.agentUniversalIdentifier,
+ token,
+ })
+ ).executionContext.authContext,
+ roleId: globalTestContext.applicationRoleId,
+ });
+
+describe('Code interpreter sandbox token for an agent run should follow the caller', () => {
+ let application: ApplicationWithResources;
+ let globalTestContext: GlobalTestContext;
+
+ beforeAll(async () => {
+ application = await setupApplicationWithResources({
+ name: 'Agent Run Caller Probe',
+ });
+
+ const [{ universalIdentifier: agentUniversalIdentifier }] =
+ await globalThis.testDataSource.query(
+ `SELECT "universalIdentifier" FROM core."agent" WHERE id = $1`,
+ [application.agentId],
+ );
+
+ const [{ defaultRoleId: applicationRoleId }] =
+ await globalThis.testDataSource.query(
+ `SELECT "defaultRoleId" FROM core."application" WHERE id = $1`,
+ [application.id],
+ );
+
+ const { applicationAccessToken } = await generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ });
+
+ globalTestContext = {
+ agentUniversalIdentifier,
+ applicationRoleId,
+ applicationToken: applicationAccessToken.token,
+ };
+ }, 120000);
+
+ afterAll(async () => {
+ if (!isDefined(application)) {
+ return;
+ }
+
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ });
+
+ it('should bind the sandbox to the member who runs another application agent', async () => {
+ const sandboxToken = await captureSandboxTokenForAgentRun({
+ globalTestContext,
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ if (!isDefined(sandboxToken)) {
+ throw new Error('Expected the sandbox to receive a token');
+ }
+
+ const { data } = await currentUser({
+ gqlFields: 'id',
+ token: sandboxToken,
+ expectToFail: false,
+ });
+
+ expect(data.currentUser.id).toBe(USER_DATA_SEED_IDS.JONY);
+ });
+
+ it('should hand the sandbox no token when an API key runs an application agent', async () => {
+ const sandboxToken = await captureSandboxTokenForAgentRun({
+ globalTestContext,
+ token: API_KEY_ACCESS_TOKEN,
+ });
+
+ expect(sandboxToken).toBeUndefined();
+ });
+
+ it('should still hand the sandbox a working token when the application runs its own agent', async () => {
+ const sandboxToken = await captureSandboxTokenForAgentRun({
+ globalTestContext,
+ token: globalTestContext.applicationToken,
+ });
+
+ if (!isDefined(sandboxToken)) {
+ throw new Error('Expected the sandbox to receive a token');
+ }
+
+ const { status, body } = await pingMcp({ token: sandboxToken });
+
+ expect(status).toBe(200);
+ expect(body.result).toEqual({});
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/successful-code-interpreter-token-on-workspace-operations.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/successful-code-interpreter-token-on-workspace-operations.integration-spec.ts
new file mode 100644
index 00000000000..f8578b1cb36
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/successful-code-interpreter-token-on-workspace-operations.integration-spec.ts
@@ -0,0 +1,123 @@
+import { callMcpTool } from 'test/integration/graphql/suites/application-role-intersection/utils/call-mcp-tool.util';
+import { pingMcp } from 'test/integration/graphql/suites/user-session/utils/ping-mcp.util';
+import {
+ type CodeInterpreterSandboxTokens,
+ captureCodeInterpreterSandboxTokens,
+} from 'test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-tokens.util';
+import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithVariable,
+ setupApplicationWithVariable,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-variable.util';
+import { deleteRecordsByIds } from 'test/integration/utils/delete-records-by-ids';
+import {
+ type EachTestingContext,
+ eachTestingContextFilter,
+} from 'twenty-shared/testing';
+import { isDefined } from 'twenty-shared/utils';
+
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+
+type TestContext = {
+ token: (globalContext: CodeInterpreterSandboxTokens) => string;
+};
+
+const sandboxTokenTestCases: EachTestingContext<TestContext>[] = [
+ {
+ title: 'for an agent an application runs as Jane',
+ context: {
+ token: (globalContext) => globalContext.applicationRunAsJaneToken,
+ },
+ },
+ {
+ title: 'for Jane running the interpreter directly',
+ context: { token: (globalContext) => globalContext.janeDirectRunToken },
+ },
+];
+
+describe('Workspace operations with a code interpreter sandbox token should succeed', () => {
+ let application: ApplicationWithVariable;
+ let globalTestContext: CodeInterpreterSandboxTokens;
+ const createdCompanyIds: string[] = [];
+
+ beforeAll(async () => {
+ application = await setupApplicationWithVariable({
+ name: 'Code Interpreter Workspace Probe',
+ variableKey: 'CODE_INTERPRETER_WORKSPACE_PROBE',
+ });
+
+ globalTestContext = await captureCodeInterpreterSandboxTokens({
+ applicationId: application.id,
+ });
+ }, 120000);
+
+ afterAll(async () => {
+ await deleteRecordsByIds('company', createdCompanyIds);
+
+ if (!isDefined(application)) {
+ return;
+ }
+
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ });
+
+ describe.each(eachTestingContextFilter(sandboxTokenTestCases))(
+ '$title',
+ ({ context }) => {
+ it('should authenticate on the MCP endpoint', async () => {
+ const { status, body } = await pingMcp({
+ token: context.token(globalTestContext),
+ });
+
+ expect(status).toBe(200);
+ expect(body.error).toBeUndefined();
+ expect(body.result).toEqual({});
+ });
+ },
+ );
+
+ it('should run a workspace tool through MCP as Jane from a direct run', async () => {
+ const result = await callMcpTool({
+ toolName: 'execute_tool',
+ toolArguments: {
+ toolName: 'find_many_companies',
+ arguments: { select: ['id'], limit: 1 },
+ },
+ token: globalTestContext.janeDirectRunToken,
+ });
+
+ expect(result.isError).toBe(false);
+ expect(JSON.parse(result.content[0].text).success).toBe(true);
+ });
+
+ it('should credit a record created from a direct run to Jane', async () => {
+ const response = await makeGraphqlApiRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: 'company',
+ gqlFields: `
+ id
+ createdBy {
+ source
+ workspaceMemberId
+ }
+ `,
+ data: { name: 'Code Interpreter Sandbox Company' },
+ }),
+ globalTestContext.janeDirectRunToken,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ const company = response.body.data.createCompany;
+
+ createdCompanyIds.push(company.id);
+
+ expect(company.createdBy.workspaceMemberId).toBe(
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ );
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/utils/capture-agent-run-execution.util.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/utils/capture-agent-run-execution.util.ts
new file mode 100644
index 00000000000..bc993051d78
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/utils/capture-agent-run-execution.util.ts
@@ -0,0 +1,88 @@
+import { runAgentQueryFactory } from 'test/integration/graphql/suites/user-session/utils/run-agent-query-factory.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { type RunAgentThread } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';
+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
+
+export type AgentRunExecution = Parameters<
+ AgentAsyncExecutorService['executeAgent']
+>[0] & { threadId: string };
+
+export const captureAgentRunExecution = async ({
+ agentUniversalIdentifier,
+ token,
+ thread,
+ runAsWorkspaceMemberId,
+ steps = [],
+}: {
+ agentUniversalIdentifier: string;
+ token: string;
+ thread?: RunAgentThread;
+ runAsWorkspaceMemberId?: string;
+ steps?: AgentExecutionResult['steps'];
+}): Promise<AgentRunExecution> => {
+ const executeAgentSpy = jest
+ .spyOn(
+ getAppProviderByClassName<AgentAsyncExecutorService>(
+ 'AgentAsyncExecutorService',
+ ),
+ 'executeAgent',
+ )
+ .mockResolvedValue({
+ result: {},
+ usage: {
+ inputTokens: 0,
+ outputTokens: 0,
+ totalTokens: 0,
+ inputTokenDetails: {
+ noCacheTokens: 0,
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ },
+ outputTokenDetails: { textTokens: 0, reasoningTokens: 0 },
+ },
+ cacheCreationTokens: 0,
+ nativeWebSearchCallCount: 0,
+ hasNoMoreAvailableCredits: false,
+ isPaused: false,
+ steps,
+ modelId: 'stub-model',
+ totalCostInDollars: 0,
+ creditsUsedMicro: 0,
+ turnUsage: {
+ inputTokens: 0,
+ outputTokens: 0,
+ cacheReadTokens: 0,
+ cacheCreationTokens: 0,
+ inputCredits: 0,
+ outputCredits: 0,
+ },
+ });
+
+ try {
+ const response = await makeMetadataApiRequest(
+ runAgentQueryFactory({
+ agentUniversalIdentifier,
+ prompt: 'Run',
+ thread,
+ runAsWorkspaceMemberId,
+ }),
+ token,
+ );
+
+ const execution = executeAgentSpy.mock.calls[0]?.[0];
+
+ if (!isDefined(execution)) {
+ throw new Error(
+ `Expected the agent to run: ${JSON.stringify(response.body.errors ?? response.body.data)}`,
+ );
+ }
+
+ return { ...execution, threadId: response.body.data.runAgent.threadId };
+ } finally {
+ executeAgentSpy.mockRestore();
+ }
+};
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-token.util.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-token.util.ts
new file mode 100644
index 00000000000..82ffa90472a
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-token.util.ts
@@ -0,0 +1,61 @@
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { ToolCategory } from 'twenty-shared/ai';
+
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { type CodeInterpreterService } from 'src/engine/core-modules/code-interpreter/code-interpreter.service';
+import { type ToolExecutorService } from 'src/engine/core-modules/tool-provider/services/tool-executor.service';
+
+export const captureCodeInterpreterSandboxToken = async ({
+ authContext,
+ roleId,
+}: {
+ authContext: WorkspaceAuthContext;
+ roleId: string;
+}): Promise<string | undefined> => {
+ const executeSpy = jest
+ .spyOn(
+ getAppProviderByClassName<CodeInterpreterService>(
+ 'CodeInterpreterService',
+ ),
+ 'execute',
+ )
+ .mockResolvedValue({ exitCode: 0, stdout: '', stderr: '', files: [] });
+
+ try {
+ const output = await getAppProviderByClassName<ToolExecutorService>(
+ 'ToolExecutorService',
+ ).dispatch(
+ {
+ name: 'code_interpreter',
+ label: 'Code interpreter',
+ description: 'Code interpreter',
+ category: ToolCategory.ACTION,
+ executionRef: { kind: 'static', toolId: 'code_interpreter' },
+ },
+ { code: 'pass' },
+ {
+ workspaceId: authContext.workspace.id,
+ roleId,
+ rolePermissionConfig: { intersectionOf: [roleId] },
+ authContext,
+ ...(isUserAuthContext(authContext)
+ ? {
+ userId: authContext.user.id,
+ userWorkspaceId: authContext.userWorkspaceId,
+ }
+ : {}),
+ },
+ );
+
+ if (!output.success) {
+ throw new Error(
+ `Expected the code interpreter to run: ${output.error ?? output.message}`,
+ );
+ }
+
+ return executeSpy.mock.calls[0]?.[2]?.env?.TWENTY_API_TOKEN;
+ } finally {
+ executeSpy.mockRestore();
+ }
+};
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-tokens.util.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-tokens.util.ts
new file mode 100644
index 00000000000..530a20ea4ad
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-tokens.util.ts
@@ -0,0 +1,72 @@
+import { captureCodeInterpreterSandboxToken } from 'test/integration/graphql/suites/user-session/utils/capture-code-interpreter-sandbox-token.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type UserWorkspaceAuthContextService } from 'src/engine/core-modules/user-workspace/services/user-workspace-auth-context.service';
+import { type AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+
+const requireToken = (token: string | undefined): string => {
+ if (!isDefined(token)) {
+ throw new Error('Expected the sandbox to receive a token');
+ }
+
+ return token;
+};
+
+export type CodeInterpreterSandboxTokens = {
+ applicationRunAsJaneToken: string;
+ janeDirectRunToken: string;
+};
+
+export const captureCodeInterpreterSandboxTokens = async ({
+ applicationId,
+}: {
+ applicationId: string;
+}): Promise<CodeInterpreterSandboxTokens> => {
+ const { flatApplicationMaps } =
+ await getAppProviderByClassName<WorkspaceCacheService>(
+ 'WorkspaceCacheService',
+ ).getOrRecompute(SEED_APPLE_WORKSPACE_ID, ['flatApplicationMaps']);
+
+ const flatApplication = flatApplicationMaps.byId[applicationId];
+
+ if (!isDefined(flatApplication)) {
+ throw new Error(`Application ${applicationId} is not in the cache`);
+ }
+
+ const { authContext: runAsJaneContext, roleId: janeRoleId } =
+ await getAppProviderByClassName<AgentActorContextService>(
+ 'AgentActorContextService',
+ ).buildRunAsWorkspaceMemberContext({
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ viaApplication: flatApplication,
+ });
+
+ const janeContext =
+ await getAppProviderByClassName<UserWorkspaceAuthContextService>(
+ 'UserWorkspaceAuthContextService',
+ ).resolve({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ });
+
+ return {
+ applicationRunAsJaneToken: requireToken(
+ await captureCodeInterpreterSandboxToken({
+ authContext: runAsJaneContext,
+ roleId: janeRoleId,
+ }),
+ ),
+ janeDirectRunToken: requireToken(
+ await captureCodeInterpreterSandboxToken({
+ authContext: janeContext,
+ roleId: janeRoleId,
+ }),
+ ),
+ };
+};
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/utils/ping-mcp.util.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/utils/ping-mcp.util.ts
new file mode 100644
index 00000000000..34f2197dcda
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/utils/ping-mcp.util.ts
@@ -0,0 +1,12 @@
+import request from 'supertest';
+
+export const pingMcp = async ({ token }: { token: string }) => {
+ const response = await request(`http://localhost:${APP_PORT}`)
+ .post('/mcp')
+ .set('Authorization', `Bearer ${token}`)
+ .set('Content-Type', 'application/json')
+ .set('Accept', 'application/json')
+ .send(JSON.stringify({ jsonrpc: '2.0', method: 'ping', id: 'ping' }));
+
+ return { status: response.status, body: response.body };
+};
diff --git a/packages/twenty-server/test/integration/graphql/suites/user-session/utils/run-agent-query-factory.util.ts b/packages/twenty-server/test/integration/graphql/suites/user-session/utils/run-agent-query-factory.util.ts
new file mode 100644
index 00000000000..52027db1eff
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/user-session/utils/run-agent-query-factory.util.ts
@@ -0,0 +1,28 @@
+import gql from 'graphql-tag';
+import { type RunAgentThread } from 'twenty-shared/application';
+
+export const runAgentQueryFactory = ({
+ agentUniversalIdentifier,
+ prompt,
+ thread,
+ runAsWorkspaceMemberId,
+}: {
+ agentUniversalIdentifier: string;
+ prompt: string;
+ thread?: RunAgentThread;
+ runAsWorkspaceMemberId?: string;
+}) => ({
+ query: gql`
+ mutation RunAgent($input: RunAgentInput!) {
+ runAgent(input: $input) {
+ result
+ error
+ success
+ threadId
+ }
+ }
+ `,
+ variables: {
+ input: { agentUniversalIdentifier, prompt, thread, runAsWorkspaceMemberId },
+ },
+});
diff --git a/packages/twenty-server/test/integration/microsoft/microsoft-mailbox-handlers.integration-spec.ts b/packages/twenty-server/test/integration/microsoft/microsoft-mailbox-handlers.integration-spec.ts
new file mode 100644
index 00000000000..b1c0174cf62
--- /dev/null
+++ b/packages/twenty-server/test/integration/microsoft/microsoft-mailbox-handlers.integration-spec.ts
@@ -0,0 +1,36 @@
+import nodeFetch from 'node-fetch';
+
+import { setupMicrosoftMock } from 'test/integration/microsoft/mocks/setup-microsoft-mock.util';
+
+jest.useRealTimers();
+
+describe('Microsoft mailbox message listing', () => {
+ setupMicrosoftMock({
+ handle: '[email protected]',
+ messages: [
+ { id: 'inbox-message', parentFolderId: 'inbox' },
+ { id: 'sent-message-1', parentFolderId: 'sentitems' },
+ { id: 'sent-message-2', parentFolderId: 'sentitems' },
+ ],
+ });
+
+ it('serves the recent sent-message lookup with the requested folder and limit', async () => {
+ const response = await nodeFetch(
+ 'https://graph.microsoft.com/v1.0/me/mailFolders/sentitems/messages?$select=id&$orderby=sentDateTime%20desc&$top=1',
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({
+ value: [{ id: 'sent-message-1' }],
+ });
+ });
+
+ it('returns an empty list for a folder without messages', async () => {
+ const response = await nodeFetch(
+ 'https://graph.microsoft.com/v1.0/me/mailFolders/drafts/messages?$select=id&$top=100',
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ value: [] });
+ });
+});
diff --git a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-mailbox-handlers.util.ts b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-mailbox-handlers.util.ts
index c64ec73a355..3c11eb5e573 100644
--- a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-mailbox-handlers.util.ts
+++ b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-mailbox-handlers.util.ts
@@ -14,6 +14,16 @@ export const microsoftMailboxHandlers = (
mailFolderPageSize = Infinity,
}: { unfetchableMessageIds?: string[]; mailFolderPageSize?: number } = {},
): MswHandler[] => [
+ http.get('*/me/mailFolders/:folderId/messages', ({ params, request }) => {
+ const top = Number(new URL(request.url).searchParams.get('$top') ?? 100);
+
+ return HttpResponse.json({
+ value: messages
+ .filter((message) => message.parentFolderId === params.folderId)
+ .slice(0, top)
+ .map((message) => ({ id: message.id })),
+ });
+ }),
http.get('*/me/mailFolders', ({ request }) => {
const { searchParams } = new URL(request.url);
const top = Number(searchParams.get('$top') ?? 10);