The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
perf(ai-chat): share one access check across the steps and tool calls of a short window (#27216)
Félix Malfaita6148759ddf2
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.tsindex 6714a4816ae..ca2c5b565db 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts@@ -108,6 +108,8 @@ import {} from 'src/engine/metadata-modules/ai/ai.exception';import { SkillService } from 'src/engine/metadata-modules/skill/skill.service';import { getChatModelId } from 'src/engine/metadata-modules/ai/ai-models/utils/get-chat-model-id.util';+import { AGENT_CHAT_KEEPALIVE_INTERVAL_MS } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-keepalive-interval-ms.constant';+import { createTurnAuthorizer } from 'src/engine/metadata-modules/ai/ai-chat/utils/create-turn-authorizer.util';export type ChatExecutionOptions = {workspace: WorkspaceEntity;@@ -171,18 +173,21 @@ export class ChatExecutionService {abortSignal,conversationSizeTokens,}: ChatExecutionOptions): Promise<ChatExecutionResult> {- const resolveExecutionContext = async (): Promise<ToolContext> => {- const authorization = await this.chatActorService.authorize({- workspaceId: workspace.id,- threadId,- sender,- });- return {- ...toolContext,- ...authorization,- resolveExecutionContext: undefined,- };- };+ const getAuthorization = createTurnAuthorizer({+ authorize: () =>+ this.chatActorService.authorize({+ workspaceId: workspace.id,+ threadId,+ sender,+ }),+ authorization,+ maxAgeMs: AGENT_CHAT_KEEPALIVE_INTERVAL_MS,+ });+ const resolveExecutionContext = async (): Promise<ToolContext> => ({+ ...toolContext,+ ...(await getAuthorization()),+ resolveExecutionContext: undefined,+ });const { actorContext, roleId, userId, userContext } =await this.agentActorContextService.buildUserAndAgentActorContext(userWorkspaceId,@@ -557,11 +562,7 @@ export class ChatExecutionService {promptCacheKey: threadId,}),prepareStep: async ({ messages }) => {- await this.chatActorService.authorize({- workspaceId: workspace.id,- threadId,- sender,- });+ await getAuthorization();stepStartedAt = performance.now();return {diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/create-turn-authorizer.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/create-turn-authorizer.util.spec.tsnew file mode 100644index 00000000000..9542af122fb--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/create-turn-authorizer.util.spec.ts@@ -0,0 +1,89 @@+import { createTurnAuthorizer } from 'src/engine/metadata-modules/ai/ai-chat/utils/create-turn-authorizer.util';++describe('createTurnAuthorizer', () => {+ beforeEach(() => {+ jest.useFakeTimers();+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ it('reuses the authorization the turn started with until it is too old', async () => {+ const authorize = jest.fn().mockResolvedValue('rechecked');+ const getAuthorization = createTurnAuthorizer({+ authorize,+ authorization: 'initial',+ maxAgeMs: 2_000,+ });++ await expect(getAuthorization()).resolves.toBe('initial');+ jest.advanceTimersByTime(1_999);+ await expect(getAuthorization()).resolves.toBe('initial');+ expect(authorize).not.toHaveBeenCalled();++ jest.advanceTimersByTime(1);+ await expect(getAuthorization()).resolves.toBe('rechecked');+ expect(authorize).toHaveBeenCalledTimes(1);+ });++ it('shares one check between concurrent callers', async () => {+ const authorize = jest.fn().mockResolvedValue('rechecked');+ const getAuthorization = createTurnAuthorizer({+ authorize,+ authorization: 'initial',+ maxAgeMs: 2_000,+ });++ jest.advanceTimersByTime(2_000);+ await Promise.all([getAuthorization(), getAuthorization()]);++ expect(authorize).toHaveBeenCalledTimes(1);+ });++ it('refuses every caller in the window once access is revoked', async () => {+ const authorize = jest+ .fn()+ .mockRejectedValueOnce(new Error('revoked'))+ .mockResolvedValue('restored');+ const getAuthorization = createTurnAuthorizer({+ authorize,+ authorization: 'initial',+ maxAgeMs: 2_000,+ });++ jest.advanceTimersByTime(2_000);+ await expect(getAuthorization()).rejects.toThrow('revoked');+ await expect(getAuthorization()).rejects.toThrow('revoked');+ expect(authorize).toHaveBeenCalledTimes(1);++ jest.advanceTimersByTime(2_000);+ await expect(getAuthorization()).resolves.toBe('restored');+ expect(authorize).toHaveBeenCalledTimes(2);+ });++ it('keeps sharing a check that outlasts the window', async () => {+ let finishCheck: (authorization: string) => void = () => {};+ const authorize = jest.fn(+ () =>+ new Promise<string>((resolve) => {+ finishCheck = resolve;+ }),+ );+ const getAuthorization = createTurnAuthorizer({+ authorize,+ authorization: 'initial',+ maxAgeMs: 2_000,+ });++ jest.advanceTimersByTime(2_000);+ const firstCaller = getAuthorization();+ jest.advanceTimersByTime(5_000);+ const secondCaller = getAuthorization();+ finishCheck('rechecked');++ await expect(firstCaller).resolves.toBe('rechecked');+ await expect(secondCaller).resolves.toBe('rechecked');+ expect(authorize).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/create-turn-authorizer.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/create-turn-authorizer.util.tsnew file mode 100644index 00000000000..288ab38c431--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/create-turn-authorizer.util.ts@@ -0,0 +1,28 @@+// A turn runs for minutes, so the sender's access is checked again as it goes, but+// the steps and parallel tool calls that land in one window share a single check+export const createTurnAuthorizer = <TAuthorization>({+ authorize,+ authorization,+ maxAgeMs,+}: {+ authorize: () => Promise<TAuthorization>;+ authorization: TAuthorization;+ maxAgeMs: number;+}): (() => Promise<TAuthorization>) => {+ let latestAuthorization: Promise<TAuthorization> =+ Promise.resolve(authorization);+ let checkedAt = performance.now();+ let isChecking = false;++ return () => {+ if (!isChecking && performance.now() - checkedAt >= maxAgeMs) {+ isChecking = true;+ latestAuthorization = authorize().finally(() => {+ checkedAt = performance.now();+ isChecking = false;+ });+ }++ return latestAuthorization;+ };+};