Skip to content

The open alternative to Salesforce, designed for AI.

12.8 KB
Raw Blame
import { act, renderHook, waitFor } from '@testing-library/react';
import { Provider as JotaiProvider } from 'jotai';
import { type ReactNode } from 'react';
import { type AgentMessageReactionSummary } from 'twenty-shared/ai';

import { AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME } from '@/ai/constants/AgentChatRefetchMessagesEventName';
import { useAgentChatSubscription } from '@/ai/hooks/useAgentChatSubscription';
import { agentChatMessageReactionsFamilyState } from '@/ai/states/agentChatMessageReactionsFamilyState';
import { agentChatMessagesFamilyState } from '@/ai/states/agentChatMessagesFamilyState';
import { agentChatFetchedMessagesFamilyState } from '@/ai/states/agentChatFetchedMessagesFamilyState';
import { agentChatQueuedMessagesFamilyState } from '@/ai/states/agentChatQueuedMessagesFamilyState';
import { agentChatErrorFamilyState } from '@/ai/states/agentChatErrorFamilyState';
import { agentChatIsAwaitingFirstChunkFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkFamilyState';
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
import { sseClientState } from '@/sse-db-event/states/sseClientState';
import {
  jotaiStore,
  resetJotaiStore,
} from '@/ui/utilities/state/jotai/jotaiStore';

const refreshAgentChatThreads = jest.fn();
const mockRefreshPermissions = jest.fn();
jest.mock('@/ai/hooks/useRefreshAgentChatThreadPermissions', () => ({
  useRefreshAgentChatThreadPermissions: () => ({
    refreshAgentChatThreadPermissions: mockRefreshPermissions,
  }),
}));
const subscribe = jest.fn();
const disconnect = jest.fn();
jest.mock('@/ai/hooks/useRefreshAgentChatThreads', () => ({
  useRefreshAgentChatThreads: () => ({ refreshAgentChatThreads }),
}));
const refreshAiChatUsage = jest.fn();
jest.mock('@/ai/hooks/useRefreshAiChatUsage', () => ({
  useRefreshAiChatUsage: () => ({ refreshAiChatUsage }),
}));
const key = { threadId: 'thread' };
const messagesAtom = agentChatMessagesFamilyState.atomFamily(key);
const fetchedAtom = agentChatFetchedMessagesFamilyState.atomFamily(key);
const queuedAtom = agentChatQueuedMessagesFamilyState.atomFamily(key);
const errorAtom = agentChatErrorFamilyState.atomFamily(key);
const Wrapper = ({ children }: { children: ReactNode }) => (
  <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
);
const denial = [
  { message: 'Thread not found', extensions: { code: 'NOT_FOUND' } },
];

describe('Shared conversation access revocation', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    resetJotaiStore();
    subscribe.mockReturnValue(disconnect);
    jotaiStore.set(sseClientState.atom, { subscribe } as never);
    const messages = [
      {
        id: 'message',
        role: 'assistant' as const,
        parts: [{ type: 'text' as const, text: 'Private conversation' }],
      },
    ];
    jotaiStore.set(messagesAtom, messages);
    jotaiStore.set(fetchedAtom, messages);
    jotaiStore.set(queuedAtom, messages);
  });

  it('refreshes only the subscribed thread on heartbeats, at most once every 30 seconds', () => {
    jest.useFakeTimers();
    const { unmount } = renderHook(() => useAgentChatSubscription('thread'), {
      wrapper: Wrapper,
    });
    const sink = subscribe.mock.calls[0][1];
    const heartbeat = () =>
      sink.next({
        data: {
          onAgentChatEvent: {
            threadId: 'thread',
            event: { type: 'keepalive' },
          },
        },
      });
    act(() => {
      heartbeat();
      heartbeat();
    });
    expect(mockRefreshPermissions).toHaveBeenCalledTimes(1);
    expect(mockRefreshPermissions).toHaveBeenLastCalledWith(['thread']);
    act(() => jest.advanceTimersByTime(30_000));
    expect(mockRefreshPermissions).toHaveBeenCalledTimes(1);
    act(heartbeat);
    expect(mockRefreshPermissions).toHaveBeenCalledTimes(2);
    expect(refreshAgentChatThreads).not.toHaveBeenCalled();
    unmount();
    act(heartbeat);
    expect(mockRefreshPermissions).toHaveBeenCalledTimes(2);
    jest.useRealTimers();
  });

  it.each(['next', 'error'])(
    'clears displayed, fetched, and queued content on a %s access error',
    async (channel) => {
      const { unmount } = renderHook(() => useAgentChatSubscription('thread'), {
        wrapper: Wrapper,
      });
      const sink = subscribe.mock.calls[0][1];
      act(() =>
        channel === 'next' ? sink.next({ errors: denial }) : sink.error(denial),
      );
      expect(jotaiStore.get(messagesAtom)).toEqual([]);
      expect(jotaiStore.get(fetchedAtom)).toEqual([]);
      expect(jotaiStore.get(queuedAtom)).toEqual([]);
      expect(jotaiStore.get(errorAtom)).toMatchObject({ code: 'NOT_FOUND' });
      expect(refreshAgentChatThreads).toHaveBeenCalledTimes(1);
      expect(disconnect).toHaveBeenCalledTimes(1);
      unmount();
      expect(disconnect).toHaveBeenCalledTimes(1);
    },
  );

  it('refetches the conversation when one of its tool calls is resolved', () => {
    const refetchListener = jest.fn();
    window.addEventListener(
      AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME,
      refetchListener,
    );
    const { unmount } = renderHook(() => useAgentChatSubscription('thread'), {
      wrapper: Wrapper,
    });
    act(() =>
      subscribe.mock.calls[0][1].next({
        data: {
          onAgentChatEvent: {
            threadId: 'thread',
            event: { type: 'tool-call-resolved', toolCallId: 'call-1' },
          },
        },
      }),
    );
    expect(refetchListener).toHaveBeenCalledTimes(1);
    unmount();
    window.removeEventListener(
      AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME,
      refetchListener,
    );
  });

  it('clears content and disconnects when the AI permission guard denies access', () => {
    renderHook(() => useAgentChatSubscription('thread'), { wrapper: Wrapper });
    act(() =>
      subscribe.mock.calls[0][1].error([{ extensions: { code: 'FORBIDDEN' } }]),
    );
    expect(jotaiStore.get(messagesAtom)).toEqual([]);
    expect(jotaiStore.get(queuedAtom)).toEqual([]);
    expect(disconnect).toHaveBeenCalledTimes(1);
  });

  it('does not let buffered stream updates restore content after revocation', async () => {
    const { unmount } = renderHook(() => useAgentChatSubscription('thread'), {
      wrapper: Wrapper,
    });
    const sink = subscribe.mock.calls[0][1];
    const send = (chunk: object) =>
      sink.next({
        data: {
          onAgentChatEvent: {
            threadId: 'thread',
            event: { type: 'stream-chunk', chunk },
          },
        },
      });
    await act(async () => {
      send({ type: 'start', messageId: 'stream-message' });
      send({ type: 'text-start', id: 'text' });
      send({ type: 'text-delta', id: 'text', delta: 'Buffered content' });
    });
    await waitFor(() =>
      expect(
        jotaiStore
          .get(messagesAtom)
          .some((message) => message.id === 'stream-message'),
      ).toBe(true),
    );
    act(() => {
      sink.error(denial);
      sink.next({
        data: {
          onAgentChatEvent: {
            threadId: 'thread',
            event: { type: 'keepalive' },
          },
        },
      });
      send({
        type: 'text-delta',
        id: 'text',
        delta: 'Late content after revocation',
      });
    });
    await act(async () => {
      await new Promise((resolve) => setTimeout(resolve, 150));
    });
    expect(jotaiStore.get(messagesAtom)).toEqual([]);
    expect(jotaiStore.get(errorAtom)).toMatchObject({ code: 'NOT_FOUND' });
    unmount();
  });

  it.each(['next', 'error'])(
    'preserves queued messages during session expiry on the %s channel',
    (channel) => {
      renderHook(() => useAgentChatSubscription('thread'), {
        wrapper: Wrapper,
      });
      const sink = subscribe.mock.calls[0][1];
      const errors = [{ extensions: { code: 'UNAUTHENTICATED' } }];
      act(() =>
        channel === 'next' ? sink.next({ errors }) : sink.error(errors),
      );
      expect(jotaiStore.get(messagesAtom)).toHaveLength(1);
      expect(jotaiStore.get(fetchedAtom)).toHaveLength(1);
      expect(jotaiStore.get(queuedAtom)).toHaveLength(1);
      expect(refreshAgentChatThreads).not.toHaveBeenCalled();
      expect(disconnect).not.toHaveBeenCalled();
    },
  );

  it('disconnects when access is denied before the subscription returns', () => {
    subscribe.mockImplementationOnce((_request, sink) => {
      sink.next({ errors: denial });
      return disconnect;
    });
    const { unmount } = renderHook(() => useAgentChatSubscription('thread'), {
      wrapper: Wrapper,
    });
    expect(disconnect).toHaveBeenCalledTimes(1);
    unmount();
    expect(disconnect).toHaveBeenCalledTimes(1);
  });

  it('keeps existing messages on an ordinary connection error', () => {
    renderHook(() => useAgentChatSubscription('thread'), { wrapper: Wrapper });
    act(() => subscribe.mock.calls[0][1].error(new Error('offline')));
    expect(jotaiStore.get(messagesAtom)).toHaveLength(1);
    expect(refreshAgentChatThreads).not.toHaveBeenCalled();
  });
});

describe('Stream liveness', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    jest.useFakeTimers();
    resetJotaiStore();
    subscribe.mockReturnValue(disconnect);
    jotaiStore.set(sseClientState.atom, { subscribe } as never);
    jotaiStore.set(
      agentChatIsAwaitingFirstChunkFamilyState.atomFamily(key),
      true,
    );
  });

  afterEach(() => {
    jest.useRealTimers();
  });

  it('reports a lost connection when resubscribing only yields the initial keepalive, then clears it once broadcasts arrive', () => {
    const keepalive = {
      data: {
        onAgentChatEvent: { threadId: 'thread', event: { type: 'keepalive' } },
      },
    };
    subscribe.mockImplementation((_request, sink) => {
      sink.next(keepalive);
      return disconnect;
    });
    renderHook(() => useAgentChatSubscription('thread'), { wrapper: Wrapper });

    for (let index = 0; index < 15; index++) {
      act(() => jest.advanceTimersByTime(2_000));
    }

    expect(subscribe).toHaveBeenCalledTimes(4);
    expect(jotaiStore.get(errorAtom)).toMatchObject({
      code: 'CONNECTION_LOST',
    });

    act(() => subscribe.mock.calls[3][1].next(keepalive));

    expect(jotaiStore.get(errorAtom)).toBeNull();
  });
});

describe('Message reactions', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    resetJotaiStore();
    subscribe.mockReturnValue(disconnect);
    jotaiStore.set(sseClientState.atom, { subscribe } as never);
  });

  it('keeps the newest snapshot when snapshots arrive out of order', () => {
    const { unmount } = renderHook(() => useAgentChatSubscription('thread'), {
      wrapper: Wrapper,
    });
    const sendReactions = (
      revision: number,
      reactions: AgentMessageReactionSummary[],
    ) =>
      subscribe.mock.calls[0][1].next({
        data: {
          onAgentChatEvent: {
            threadId: 'thread',
            event: {
              type: 'message-reactions-updated',
              messageId: 'message',
              reactions,
              revision,
            },
          },
        },
      });
    const newerReactions = [
      {
        emoji: 'πŸ‘',
        workspaceMemberIds: ['julia'],
        agentIds: [],
        hasAssistantReacted: false,
      },
      {
        emoji: 'πŸŽ‰',
        workspaceMemberIds: ['tom'],
        agentIds: [],
        hasAssistantReacted: false,
      },
    ];

    act(() => {
      sendReactions(2, newerReactions);
      sendReactions(1, [
        {
          emoji: 'πŸ‘',
          workspaceMemberIds: ['julia'],
          agentIds: [],
          hasAssistantReacted: false,
        },
      ]);
    });

    expect(
      jotaiStore.get(
        agentChatMessageReactionsFamilyState.atomFamily({
          messageId: 'message',
        }),
      ),
    ).toEqual(newerReactions);
    unmount();
  });
});

describe('User credits exhausted', () => {
  const sendUserCreditsExhausted = (workspaceMemberId: string) =>
    subscribe.mock.calls[0][1].next({
      data: {
        onAgentChatEvent: {
          threadId: 'thread',
          event: {
            type: 'user-credits-exhausted',
            workspaceMemberId,
            isFallingBackToWorkspaceCredits: true,
            renewsAt: '2026-10-26T00:00:00.000Z',
          },
        },
      },
    });

  beforeEach(() => {
    jest.clearAllMocks();
    resetJotaiStore();
    subscribe.mockReturnValue(disconnect);
    jotaiStore.set(sseClientState.atom, { subscribe } as never);
    jotaiStore.set(currentWorkspaceMemberState.atom, {
      id: 'julia',
    } as never);
  });

  it('refreshes the user credits of the member who sent the turn only', () => {
    const { unmount } = renderHook(() => useAgentChatSubscription('thread'), {
      wrapper: Wrapper,
    });

    act(() => sendUserCreditsExhausted('tom'));

    expect(refreshAiChatUsage).not.toHaveBeenCalled();

    act(() => sendUserCreditsExhausted('julia'));

    expect(refreshAiChatUsage).toHaveBeenCalledTimes(1);
    expect(jotaiStore.get(errorAtom)).toBeNull();
    unmount();
  });
});