Skip to content

The open alternative to Salesforce, designed for AI.

Stop retrying the SSE event stream once the client is signed out (#23979)

Félix Malfaitd87dc3ac7e05
diff --git a/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.ts b/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.ts
new file mode 100644
index 00000000000..a0f2f415e06
--- /dev/null
+++ b/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.ts
@@ -0,0 +1,143 @@
+import { act, renderHook } from '@testing-library/react';
+import { type Client } from 'graphql-sse';
+import { createStore, Provider } from 'jotai';
+import { createElement, type ReactNode } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+
+import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';
+import { tokenPairState } from '@/auth/states/tokenPairState';
+import { type AuthTokenPair } from '~/generated-metadata/graphql';
+import { shouldDestroyEventStreamState } from '@/sse-db-event/states/shouldDestroyEventStreamState';
+import { sseClientState } from '@/sse-db-event/states/sseClientState';
+import { useHandleSseClientConnectionRetry } from '@/sse-db-event/hooks/useHandleSseClientConnectionRetry';
+
+jest.mock('~/utils/sleep', () => ({
+ sleep: jest.fn().mockResolvedValue(undefined),
+}));
+
+const ensureTokenRenewedMock = jest.fn();
+
+jest.mock('@/auth/utils/ensureTokenRenewed', () => ({
+ ensureTokenRenewed: (...args: unknown[]) => ensureTokenRenewedMock(...args),
+}));
+
+const buildTokenPair = (expiresAt: Date): AuthTokenPair => ({
+ accessOrWorkspaceAgnosticToken: {
+ token: 'access-token',
+ expiresAt: expiresAt.toISOString(),
+ },
+ refreshToken: {
+ token: 'refresh-token',
+ expiresAt: expiresAt.toISOString(),
+ },
+});
+
+// The hook only ever calls dispose, but the atom holds a full Client, so the
+// unused members are stubbed rather than cast away.
+const buildSseClient = (dispose: () => void): Client => ({
+ subscribe: () => () => {},
+ iterate: async function* () {},
+ dispose,
+});
+
+const setupStore = ({
+ isCookieAuthActive,
+ tokenPair,
+}: {
+ isCookieAuthActive: boolean;
+ tokenPair: AuthTokenPair | null;
+}) => {
+ const store = createStore();
+ const dispose = jest.fn();
+
+ store.set(sseClientState.atom, buildSseClient(dispose));
+ store.set(shouldDestroyEventStreamState.atom, false);
+ store.set(isCookieAuthActiveState.atom, isCookieAuthActive);
+ store.set(tokenPairState.atom, tokenPair);
+
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(Provider, { store }, children);
+
+ const { result } = renderHook(() => useHandleSseClientConnectionRetry(), {
+ wrapper,
+ });
+
+ return { store, dispose, result };
+};
+
+const wasStreamDestroyed = (store: ReturnType<typeof createStore>) =>
+ store.get(shouldDestroyEventStreamState.atom) &&
+ !isDefined(store.get(sseClientState.atom));
+
+describe('useHandleSseClientConnectionRetry', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ ensureTokenRenewedMock.mockResolvedValue(true);
+ });
+
+ it('should stop retrying when a cookie-mode client has been signed out', async () => {
+ const { store, dispose, result } = setupStore({
+ isCookieAuthActive: false,
+ tokenPair: null,
+ });
+
+ await act(() => result.current.handleSseClientConnectionRetry(0));
+
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(wasStreamDestroyed(store)).toBe(true);
+ });
+
+ it('should keep retrying a live cookie session that has no token pair', async () => {
+ const { store, dispose, result } = setupStore({
+ isCookieAuthActive: true,
+ tokenPair: null,
+ });
+
+ await act(() => result.current.handleSseClientConnectionRetry(0));
+
+ expect(dispose).not.toHaveBeenCalled();
+ expect(wasStreamDestroyed(store)).toBe(false);
+ expect(ensureTokenRenewedMock).not.toHaveBeenCalled();
+ });
+
+ it('should stop retrying past the attempt cap regardless of credential', async () => {
+ const { store, dispose, result } = setupStore({
+ isCookieAuthActive: true,
+ tokenPair: null,
+ });
+
+ await act(() => result.current.handleSseClientConnectionRetry(11));
+
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(wasStreamDestroyed(store)).toBe(true);
+ });
+
+ it('should renew an expired token in token mode and stop when renewal fails', async () => {
+ ensureTokenRenewedMock.mockResolvedValue(false);
+
+ const { store, dispose, result } = setupStore({
+ isCookieAuthActive: false,
+ tokenPair: buildTokenPair(new Date(Date.now() - 1000)),
+ });
+
+ await act(() => result.current.handleSseClientConnectionRetry(0));
+
+ expect(ensureTokenRenewedMock).toHaveBeenCalledTimes(1);
+ expect(ensureTokenRenewedMock).toHaveBeenCalledWith(store);
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(wasStreamDestroyed(store)).toBe(true);
+ });
+
+ it('should keep retrying in token mode while the token is still valid', async () => {
+ const { store, dispose, result } = setupStore({
+ isCookieAuthActive: false,
+ tokenPair: buildTokenPair(new Date(Date.now() + 60_000)),
+ });
+
+ await act(() => result.current.handleSseClientConnectionRetry(0));
+
+ expect(ensureTokenRenewedMock).not.toHaveBeenCalled();
+ expect(dispose).not.toHaveBeenCalled();
+ expect(wasStreamDestroyed(store)).toBe(false);
+ });
+});
diff --git a/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts b/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts
index 83c7292636b..8f0223b4461 100644
--- a/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts
+++ b/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts
@@ -23,6 +23,13 @@ const destroyStream = async (
store.set(sseClientState.atom, null);
};
+// The session cookie is httpOnly, so a cookie-mode client cannot inspect its own
+// credential. clearSession drops both credentials together, so their joint
+// absence is what "signed out" looks like from here.
+const hasCredential = (store: ReturnType<typeof useStore>): boolean =>
+ store.get(isCookieAuthActiveState.atom) ||
+ isDefined(store.get(tokenPairState.atom)?.accessOrWorkspaceAgnosticToken);
+
export const useHandleSseClientConnectionRetry = () => {
const store = useStore();
@@ -42,19 +49,23 @@ export const useHandleSseClientConnectionRetry = () => {
return;
}
- // In cookie mode the session cookie is the credential: there is no token
- // pair to find missing and nothing to renew, so an absent one must not
- // be read as a lost credential.
- if (!store.get(isCookieAuthActiveState.atom)) {
- const tokenPair = store.get(tokenPairState.atom);
- const accessToken = tokenPair?.accessOrWorkspaceAgnosticToken;
+ // Without this the loop is unbounded: graphql-sse resets its retry count
+ // whenever a result arrives, so retryCount alone never trips on a stream
+ // that keeps reconnecting. A signed-out client has to stop here.
+ if (!hasCredential(store)) {
+ await destroyStream(store, sseClient);
+ return;
+ }
- if (!isDefined(accessToken)) {
- await destroyStream(store, sseClient);
- return;
- }
+ if (!store.get(isCookieAuthActiveState.atom)) {
+ const accessToken = store.get(
+ tokenPairState.atom,
+ )?.accessOrWorkspaceAgnosticToken;
- if (new Date(accessToken.expiresAt) <= new Date()) {
+ if (
+ isDefined(accessToken) &&
+ new Date(accessToken.expiresAt) <= new Date()
+ ) {
const renewed = await ensureTokenRenewed(store);
if (!renewed) {