@@ -60,15 +60,25 @@ export const SessionContext = createContext<CompassSession>({
6060const authenticated$ = new BehaviorSubject ( false ) ;
6161let isCheckingSession = false ;
6262let isSessionInitialized = false ;
63+ let sessionEventVersion = 0 ;
6364
6465const $authenticated = authenticated$ . pipe ( skip ( 1 ) , distinctUntilChanged ( ) ) ;
6566
66- const handleSessionExists = async ( ) => {
67+ const handleAuthenticatedSession = ( ) => {
68+ authenticated$ . next ( true ) ;
6769 markUserAsAuthenticated ( getLastKnownEmail ( ) ) ;
68- await refreshUserMetadata ( ) ;
70+ void refreshUserMetadata ( ) ;
71+ } ;
72+
73+ const handleSessionExists = ( ) => {
74+ handleAuthenticatedSession ( ) ;
75+ if ( ! sse . getStream ( ) ) {
76+ sse . openStream ( ) ;
77+ }
6978} ;
7079
7180const handleSessionMissing = ( ) => {
81+ authenticated$ . next ( false ) ;
7282 store . dispatch ( authSlice . actions . resetAuth ( ) ) ;
7383 store . dispatch ( userMetadataSlice . actions . clear ( undefined ) ) ;
7484 clearGoogleSyncIndicatorOverride ( ) ;
@@ -81,23 +91,24 @@ async function checkIfSessionExists(): Promise<boolean> {
8191 return false ;
8292 }
8393
84- if ( isCheckingSession ) return false ;
94+ if ( isCheckingSession ) return authenticated$ . value ;
8595
8696 isCheckingSession = true ;
97+ const eventVersionAtCheckStart = sessionEventVersion ;
8798
8899 try {
89100 const exists = await session . doesSessionExist ( ) ;
90101
102+ if ( sessionEventVersion !== eventVersionAtCheckStart ) {
103+ return authenticated$ . value ;
104+ }
105+
91106 if ( exists ) {
92107 handleSessionExists ( ) ;
93- if ( ! sse . getStream ( ) ) {
94- sse . openStream ( ) ;
95- }
96108 } else {
97109 handleSessionMissing ( ) ;
98110 }
99111
100- authenticated$ . next ( exists ) ;
101112 return exists ;
102113 } catch ( error ) {
103114 console . error ( "Error checking auth status:" , error ) ;
@@ -118,22 +129,23 @@ export function sessionInit() {
118129
119130 // No need to unsubscribe as this runs for the lifetime of the app
120131 session . events . pipe ( distinctUntilKeyChanged ( "action" ) ) . subscribe ( ( e ) => {
121- void checkIfSessionExists ( ) ;
122-
123132 switch ( e . action ) {
124133 case "REFRESH_SESSION" :
125134 case "SESSION_CREATED" :
135+ sessionEventVersion += 1 ;
126136 // Mark user as authenticated when session is created or refreshed
127137 // This ensures the flag is set even if markUserAsAuthenticated wasn't called during OAuth
128- markUserAsAuthenticated ( getLastKnownEmail ( ) ) ;
129- void refreshUserMetadata ( ) ;
138+ handleAuthenticatedSession ( ) ;
130139 sse . closeStream ( ) ;
131140 sse . openStream ( ) ;
132141 break ;
133142 case "SIGN_OUT" :
134- store . dispatch ( userMetadataSlice . actions . clear ( undefined ) ) ;
143+ sessionEventVersion += 1 ;
144+ handleSessionMissing ( ) ;
135145 sse . closeStream ( ) ;
136146 break ;
147+ default :
148+ void checkIfSessionExists ( ) ;
137149 }
138150 } ) ;
139151}
0 commit comments