Skip to content

The open alternative to Salesforce, designed for AI.

8.2 KB
Raw Blame
import { randomUUID } from 'node:crypto';

import { followAgentRunEventsOrThrow } from 'test/integration/ai/utils/follow-agent-run-events.util';
import { generateQueryFactory } from 'test/integration/ai/utils/generate-query-factory.util';
import {
  answerWith,
  mockScriptedAiModel,
} from 'test/integration/ai/utils/mock-scripted-ai-model.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 { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
import { isAgentChatTurnEndEvent } from 'twenty-shared/ai';
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 { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';

const INPUT = [{ role: 'user' as const, content: 'Qualify Acme' }];
const GENERATE_TIMEOUT_MS = 30_000;
const STREAM_WAIT_TIMEOUT_MS = 10_000;

const setupApplicationWithToken = async (name: string) => {
  const application = await setupApplicationWithResources({ name });
  const { applicationAccessToken } = await generateApplicationTokenPair({
    workspaceId: SEED_APPLE_WORKSPACE_ID,
    applicationId: application.id,
  });

  return { application, token: applicationAccessToken.token };
};

const waitForOrThrow = async (isDone: () => boolean) => {
  const startedAt = Date.now();

  while (!isDone()) {
    if (Date.now() - startedAt > STREAM_WAIT_TIMEOUT_MS) {
      throw new Error('Timed out waiting for the run stream');
    }

    await new Promise((resolve) => setTimeout(resolve, 20));
  }
};

describe('ai.generate runs followed by their application (integration)', () => {
  let application: ApplicationWithResources;
  let token: string;
  let otherApplication: ApplicationWithResources;
  let otherToken: string;

  beforeAll(async () => {
    // one after the other, since each setup switches Jest's process-wide timer mode
    ({ application, token } = await setupApplicationWithToken(
      'Generate Stream Probe',
    ));
    ({ application: otherApplication, token: otherToken } =
      await setupApplicationWithToken('Generate Stream Other Probe'));
  }, 120000);

  // setupApplicationWithResources leaves fake timers on, which would freeze every wait below
  beforeEach(() => jest.useRealTimers());

  afterEach(() => jest.restoreAllMocks());

  afterAll(async () => {
    await Promise.all(
      [application, otherApplication]
        .filter(isDefined)
        .map(({ universalIdentifier }) =>
          cleanupApplicationAndAppRegistration({
            applicationUniversalIdentifier: universalIdentifier,
          }),
        ),
    );
  });

  it('streams a run to its application under the run id it chose, and to no other application', async () => {
    const runId = randomUUID();
    const streams: Awaited<ReturnType<typeof followAgentRunEventsOrThrow>>[] =
      [];

    try {
      const ownStream = await followAgentRunEventsOrThrow({ runId, token });

      streams.push(ownStream);

      const otherStream = await followAgentRunEventsOrThrow({
        runId,
        token: otherToken,
      });

      streams.push(otherStream);

      await waitForOrThrow(
        () => ownStream.events.length > 0 && otherStream.events.length > 0,
      );
      mockScriptedAiModel(() => answerWith('Acme looks like a fit'));

      const response = await makeMetadataApiRequest(
        generateQueryFactory({ input: INPUT, runId }),
        token,
      ).timeout(GENERATE_TIMEOUT_MS);

      expect(response.body.errors).toBeUndefined();
      expect(response.body.data.generate).toMatchObject({
        success: true,
        text: 'Acme looks like a fit',
        runId,
      });

      await waitForOrThrow(() =>
        ownStream.events.some(isAgentChatTurnEndEvent),
      );

      const chunks = ownStream.events.flatMap((event) =>
        event.type === 'stream-chunk' ? [event.chunk] : [],
      );

      expect(chunks[0]).toMatchObject({ type: 'start' });
      expect(
        chunks
          .filter(({ type }) => type === 'text-delta')
          .map(({ delta }) => delta)
          .join(''),
      ).toBe('Acme looks like a fit');
      expect(ownStream.events.find(isAgentChatTurnEndEvent)).toMatchObject({
        type: 'run-finished',
      });

      // the server's one Redis subscriber relays both channels in publish order, so a keepalive the
      // other stream gets after the run ended comes after anything the run published
      const otherEventCountAtRunEnd = otherStream.events.length;

      await waitForOrThrow(
        () => otherStream.events.length > otherEventCountAtRunEnd,
      );
    } finally {
      await Promise.all(streams.map((stream) => stream.close()));
    }

    const [ownStream, otherStream] = streams;

    expect(ownStream.errors).toEqual([]);
    expect(otherStream.errors).toEqual([]);
    expect(otherStream.events.every(({ type }) => type === 'keepalive')).toBe(
      true,
    );
  });

  it('streams a run started with a member-bound token of the application to the same channel', async () => {
    const runId = randomUUID();
    const { applicationAccessToken: memberBoundToken } =
      await generateApplicationTokenPair({
        workspaceId: SEED_APPLE_WORKSPACE_ID,
        applicationId: application.id,
        userId: USER_DATA_SEED_IDS.JANE,
        userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
      });
    const stream = await followAgentRunEventsOrThrow({
      runId,
      token: memberBoundToken.token,
    });

    try {
      await waitForOrThrow(() => stream.events.length > 0);
      mockScriptedAiModel(() => answerWith('Acme looks like a fit'));

      const response = await makeMetadataApiRequest(
        generateQueryFactory({ input: INPUT, runId }),
        memberBoundToken.token,
      ).timeout(GENERATE_TIMEOUT_MS);

      expect(response.body.errors).toBeUndefined();
      expect(response.body.data.generate).toMatchObject({
        success: true,
        runId,
      });

      await waitForOrThrow(() => stream.events.some(isAgentChatTurnEndEvent));
    } finally {
      await stream.close();
    }

    expect(stream.errors).toEqual([]);
    expect(
      stream.events.some(
        (event) =>
          event.type === 'stream-chunk' && event.chunk.type === 'text-delta',
      ),
    ).toBe(true);
  });

  it('refuses a run id that is already used', async () => {
    const runId = randomUUID();

    mockScriptedAiModel(() => answerWith('Done'));

    const firstResponse = await makeMetadataApiRequest(
      generateQueryFactory({ input: INPUT, runId }),
      token,
    );

    expect(firstResponse.body.data.generate.runId).toBe(runId);

    const secondResponse = await makeMetadataApiRequest(
      generateQueryFactory({ input: INPUT, runId }),
      token,
    );

    expect(secondResponse.body.errors[0].extensions.code).toBe(
      'BAD_USER_INPUT',
    );
  });

  it('runs only one of two concurrent calls with the same run id', async () => {
    const runId = randomUUID();

    mockScriptedAiModel(() => answerWith('Done'));

    const responses = await Promise.all(
      [1, 2].map(() =>
        makeMetadataApiRequest(
          generateQueryFactory({ input: INPUT, runId }),
          token,
        ),
      ),
    );

    expect(
      responses.map(({ body }) =>
        isDefined(body.errors)
          ? body.errors[0].extensions.code
          : body.data.generate.runId,
      ),
    ).toEqual(expect.arrayContaining([runId, 'BAD_USER_INPUT']));
  });

  it('refuses a run id from a member session', async () => {
    const response = await makeMetadataApiRequest(
      generateQueryFactory({ input: INPUT, runId: randomUUID() }),
    );

    expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
  });
});