Skip to content

The open alternative to Salesforce, designed for AI.

Fix stale UI state after stop-impersonation (#20088)

Félix Malfaitd8e2de48e662
diff --git a/packages/twenty-front/src/modules/auth/hooks/__tests__/useAuth.test.tsx b/packages/twenty-front/src/modules/auth/hooks/__tests__/useAuth.test.tsx
index 7fb98304eb0..6477c083752 100644
--- a/packages/twenty-front/src/modules/auth/hooks/__tests__/useAuth.test.tsx
+++ b/packages/twenty-front/src/modules/auth/hooks/__tests__/useAuth.test.tsx
@@ -1,11 +1,5 @@
import { useAuth } from '@/auth/hooks/useAuth';
-import { billingState } from '@/client-config/states/billingState';
-import { isDeveloperDefaultSignInPrefilledState } from '@/client-config/states/isDeveloperDefaultSignInPrefilledState';
-import { supportChatState } from '@/client-config/states/supportChatState';
-import { workspaceAuthProvidersState } from '@/workspace/states/workspaceAuthProvidersState';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { useApolloClient } from '@apollo/client/react';
import { MockedProvider } from '@apollo/client/testing/react';
import { type ReactNode, act } from 'react';
import { MemoryRouter } from 'react-router-dom';
@@ -17,10 +11,8 @@ import {
results,
token,
} from '@/auth/hooks/__mocks__/useAuth';
-import { isMultiWorkspaceEnabledState } from '@/client-config/states/isMultiWorkspaceEnabledState';
import { SnackBarComponentInstanceContext } from '@/ui/feedback/snack-bar-manager/contexts/SnackBarComponentInstanceContext';
import { renderHook } from '@testing-library/react';
-import { SupportDriver } from '~/generated-metadata/graphql';
const redirectSpy = jest.fn();
@@ -147,55 +139,15 @@ describe('useAuth', () => {
});
it('should handle sign-out', async () => {
- const { result } = renderHook(
- () => {
- const client = useApolloClient();
- const workspaceAuthProviders = useAtomStateValue(
- workspaceAuthProvidersState,
- );
- const billing = useAtomStateValue(billingState);
- const isDeveloperDefaultSignInPrefilled = useAtomStateValue(
- isDeveloperDefaultSignInPrefilledState,
- );
- const supportChat = useAtomStateValue(supportChatState);
- const isMultiWorkspaceEnabled = useAtomStateValue(
- isMultiWorkspaceEnabledState,
- );
- return {
- ...useAuth(),
- client,
- state: {
- workspaceAuthProviders,
- billing,
- isDeveloperDefaultSignInPrefilled,
- supportChat,
- isMultiWorkspaceEnabled,
- },
- };
- },
- {
- wrapper: Wrapper,
- },
- );
+ sessionStorage.setItem('lingering-key', 'should-be-cleared');
- const { signOut, client } = result.current;
+ const { result } = renderHooks();
await act(async () => {
- await signOut();
+ result.current.signOut();
});
expect(sessionStorage.length).toBe(0);
- expect(client.cache.extract()).toEqual({});
-
- const { state } = result.current;
-
- expect(state.workspaceAuthProviders).toEqual(null);
- expect(state.billing).toBeNull();
- expect(state.isDeveloperDefaultSignInPrefilled).toBe(false);
- expect(state.supportChat).toEqual({
- supportDriver: SupportDriver.NONE,
- supportFrontChatId: null,
- });
});
it('should handle credential sign-up', async () => {
diff --git a/packages/twenty-front/src/modules/auth/hooks/useAuth.ts b/packages/twenty-front/src/modules/auth/hooks/useAuth.ts
index 48d258421ac..a152a60be47 100644
--- a/packages/twenty-front/src/modules/auth/hooks/useAuth.ts
+++ b/packages/twenty-front/src/modules/auth/hooks/useAuth.ts
@@ -1,8 +1,4 @@
-import {
- useApolloClient,
- useLazyQuery,
- useMutation,
-} from '@apollo/client/react';
+import { useLazyQuery, useMutation } from '@apollo/client/react';
import { useCallback } from 'react';
import { AppPath } from 'twenty-shared/types';
@@ -28,16 +24,7 @@ import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomState
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
import { isAppEffectRedirectEnabledState } from '@/app/states/isAppEffectRedirectEnabledState';
-import { availableWorkspacesState } from '@/auth/states/availableWorkspacesState';
-import { currentUserState } from '@/auth/states/currentUserState';
-import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';
-import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
-import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';
-import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useSignUpInNewWorkspace } from '@/auth/sign-in-up/hooks/useSignUpInNewWorkspace';
-import { useLoadMockedMetadata } from '@/metadata-store/hooks/useLoadMockedMetadata';
-import { preloadMockedMetadata } from '@/metadata-store/utils/preloadMockedMetadata';
-import { lastAuthenticatedMethodState } from '@/auth/states/lastAuthenticatedMethodState';
import { loginTokenState } from '@/auth/states/loginTokenState';
import {
SignInUpStep,
@@ -49,18 +36,13 @@ import {
countAvailableWorkspaces,
getFirstAvailableWorkspaces,
} from '@/auth/utils/availableWorkspacesUtils';
-import { useRequestFreshCaptchaToken } from '@/captcha/hooks/useRequestFreshCaptchaToken';
-import { isCaptchaScriptLoadedState } from '@/captcha/states/isCaptchaScriptLoadedState';
import { isEmailVerificationRequiredState } from '@/client-config/states/isEmailVerificationRequiredState';
import { isMultiWorkspaceEnabledState } from '@/client-config/states/isMultiWorkspaceEnabledState';
import { useLastAuthenticatedWorkspaceDomain } from '@/domain-manager/hooks/useLastAuthenticatedWorkspaceDomain';
import { useOrigin } from '@/domain-manager/hooks/useOrigin';
import { useRedirect } from '@/domain-manager/hooks/useRedirect';
import { useRedirectToWorkspaceDomain } from '@/domain-manager/hooks/useRedirectToWorkspaceDomain';
-import { domainConfigurationState } from '@/domain-manager/states/domainConfigurationState';
-import { useClearSseClient } from '@/sse-db-event/hooks/useClearSseClient';
import { useLoadCurrentUser } from '@/users/hooks/useLoadCurrentUser';
-import { workspaceAuthProvidersState } from '@/workspace/states/workspaceAuthProvidersState';
import { i18n } from '@lingui/core';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { SOURCE_LOCALE } from 'twenty-shared/translations';
@@ -78,8 +60,6 @@ export const useAuth = () => {
);
const { origin } = useOrigin();
- const { requestFreshCaptchaToken } = useRequestFreshCaptchaToken();
- const isCaptchaScriptLoaded = useAtomStateValue(isCaptchaScriptLoadedState);
const isMultiWorkspaceEnabled = useAtomStateValue(
isMultiWorkspaceEnabledState,
);
@@ -87,9 +67,7 @@ export const useAuth = () => {
isEmailVerificationRequiredState,
);
const { loadCurrentUser } = useLoadCurrentUser();
- const { clearSseClient } = useClearSseClient();
- const { applyMockedMetadata } = useLoadMockedMetadata();
const { createWorkspace } = useSignUpInNewWorkspace();
const setSignInUpStep = useSetAtomState(signInUpStepState);
@@ -121,64 +99,17 @@ export const useAuth = () => {
CheckUserExistsDocument,
);
- const client = useApolloClient();
-
const [, setSearchParams] = useSearchParams();
const navigate = useNavigate();
- const clearSession = useCallback(async () => {
- clearSseClient();
- store.set(isAppEffectRedirectEnabledState.atom, false);
-
- const mockedData = await preloadMockedMetadata();
-
- const authProvidersValue = store.get(workspaceAuthProvidersState.atom);
- const domainConfigurationValue = store.get(domainConfigurationState.atom);
- const workspacePublicDataValue = store.get(workspacePublicDataState.atom);
- const lastAuthenticatedMethod = store.get(
- lastAuthenticatedMethodState.atom,
- );
- const isCaptchaScriptLoadedValue = store.get(
- isCaptchaScriptLoadedState.atom,
- );
-
+ const clearSession = useCallback(() => {
sessionStorage.clear();
clearSessionLocalStorageKeys();
-
- store.set(workspaceAuthProvidersState.atom, authProvidersValue);
- store.set(workspacePublicDataState.atom, workspacePublicDataValue);
- store.set(domainConfigurationState.atom, domainConfigurationValue);
- store.set(isCaptchaScriptLoadedState.atom, isCaptchaScriptLoadedValue);
- store.set(lastAuthenticatedMethodState.atom, lastAuthenticatedMethod);
-
store.set(tokenPairState.atom, null);
- store.set(currentUserState.atom, null);
- store.set(currentWorkspaceState.atom, null);
- store.set(currentUserWorkspaceState.atom, null);
- store.set(currentWorkspaceMemberState.atom, null);
- store.set(currentWorkspaceMembersState.atom, []);
- store.set(availableWorkspacesState.atom, {
- availableWorkspacesForSignIn: [],
- availableWorkspacesForSignUp: [],
- });
- store.set(loginTokenState.atom, null);
- store.set(signInUpStepState.atom, SignInUpStep.Init);
-
- applyMockedMetadata(mockedData);
-
- await client.clearStore();
setLastAuthenticateWorkspaceDomain(null);
- navigate(AppPath.SignInUp);
- store.set(isAppEffectRedirectEnabledState.atom, true);
- }, [
- clearSseClient,
- client,
- setLastAuthenticateWorkspaceDomain,
- applyMockedMetadata,
- navigate,
- store,
- ]);
+ window.location.assign(AppPath.SignInUp);
+ }, [store, setLastAuthenticateWorkspaceDomain]);
const handleSetAuthTokens = useCallback(
(tokens: AuthTokenPair) => {
@@ -475,11 +406,10 @@ export const useAuth = () => {
[handleGetLoginTokenFromCredentials, handleGetAuthTokensFromLoginToken],
);
- const handleSignOut = useCallback(async () => {
+ const handleSignOut = useCallback(() => {
broadcastSignOutToOtherTabs();
- await clearSession();
- if (isCaptchaScriptLoaded) await requestFreshCaptchaToken();
- }, [clearSession, isCaptchaScriptLoaded, requestFreshCaptchaToken]);
+ clearSession();
+ }, [clearSession]);
const handleCredentialsSignUpInWorkspace = useCallback(
async ({
diff --git a/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts b/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts
index 3d44f6ce8d1..3a5c5a8b8d7 100644
--- a/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts
+++ b/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts
@@ -1,13 +1,8 @@
-import { useApolloClient } from '@apollo/client/react';
import { useCallback } from 'react';
-import { useNavigate } from 'react-router-dom';
import { useStore } from 'jotai';
-import { isAppEffectRedirectEnabledState } from '@/app/states/isAppEffectRedirectEnabledState';
import { useAuth } from '@/auth/hooks/useAuth';
import { tokenPairState } from '@/auth/states/tokenPairState';
-import { useClearSseClient } from '@/sse-db-event/hooks/useClearSseClient';
-import { useLoadCurrentUser } from '@/users/hooks/useLoadCurrentUser';
import { type AuthTokenPair } from '~/generated-metadata/graphql';
const IMPERSONATION_SESSION_KEY = 'impersonation_original_session';
@@ -17,22 +12,27 @@ type StoredImpersonationSession = {
returnPath: string;
};
+// Token swaps without a full reload would require enumerating every
+// user-scoped atom, localStorage entry, and Apollo cache key — brittle and
+// silently broken every time a new piece of user state is added. Instead,
+// set the cookie-backed token pair and let the browser re-bootstrap the app.
+const reloadWithSession = (returnPath: string) => {
+ window.location.assign(returnPath);
+};
+
export const useImpersonationSession = () => {
const store = useStore();
- const client = useApolloClient();
- const navigate = useNavigate();
const { getAuthTokensFromLoginToken, signOut } = useAuth();
- const { clearSseClient } = useClearSseClient();
- const { loadCurrentUser } = useLoadCurrentUser();
const startImpersonating = useCallback(
async (loginToken: string, returnPath?: string) => {
const currentTokenPair = store.get(tokenPairState.atom);
+ const targetPath = returnPath ?? window.location.pathname;
if (currentTokenPair) {
const session: StoredImpersonationSession = {
tokenPair: currentTokenPair,
- returnPath: returnPath ?? window.location.pathname,
+ returnPath: targetPath,
};
sessionStorage.setItem(
IMPERSONATION_SESSION_KEY,
@@ -40,30 +40,25 @@ export const useImpersonationSession = () => {
);
}
- clearSseClient();
- await client.clearStore();
-
- store.set(isAppEffectRedirectEnabledState.atom, false);
await getAuthTokensFromLoginToken(loginToken);
- store.set(isAppEffectRedirectEnabledState.atom, true);
+ reloadWithSession(targetPath);
},
- [store, client, clearSseClient, getAuthTokensFromLoginToken],
+ [store, getAuthTokensFromLoginToken],
);
const stopImpersonating = useCallback(async () => {
const raw = sessionStorage.getItem(IMPERSONATION_SESSION_KEY);
if (!raw) {
- // No stored session — likely a cross-workspace tab opened via redirect.
- // Try closing the tab (works when opened via window.open or target=_blank).
+ // Cross-workspace tab opened via redirect — no stored admin session
+ // to restore. Close the tab; fall back to sign out if the browser
+ // blocks window.close().
window.close();
- // If window.close() was blocked by the browser, fall back to sign out.
await signOut();
return;
}
let session: StoredImpersonationSession;
-
try {
session = JSON.parse(raw);
} catch {
@@ -73,19 +68,9 @@ export const useImpersonationSession = () => {
}
sessionStorage.removeItem(IMPERSONATION_SESSION_KEY);
-
- clearSseClient();
- await client.clearStore();
-
- store.set(isAppEffectRedirectEnabledState.atom, false);
store.set(tokenPairState.atom, session.tokenPair);
-
- await loadCurrentUser();
-
- store.set(isAppEffectRedirectEnabledState.atom, true);
-
- navigate(session.returnPath);
- }, [store, client, clearSseClient, loadCurrentUser, signOut, navigate]);
+ reloadWithSession(session.returnPath);
+ }, [store, signOut]);
const hasStoredSession = useCallback(() => {
return sessionStorage.getItem(IMPERSONATION_SESSION_KEY) !== null;