Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(auth): preserve local session during login handoff

Steven Enamakel50465317884a
diff --git a/app/src/providers/CoreStateProvider.tsx b/app/src/providers/CoreStateProvider.tsx
index 53fa0323c9..aabb4f2391 100644
--- a/app/src/providers/CoreStateProvider.tsx
+++ b/app/src/providers/CoreStateProvider.tsx
@@ -679,33 +679,46 @@ export default function CoreStateProvider({ children }: { children: ReactNode })
[refresh]
);
+ // The core switches credentials before the refreshed app snapshot reaches
+ // React. Keep the token being installed visible to the expiry handler during
+ // that gap; otherwise a late 401 from the previous/cloud surface can clear a
+ // newly stored local session even though the core correctly ignores it.
+ const sessionTokenBeingStoredRef = useRef<string | null>(null);
+
const storeSessionToken = useCallback(
async (token: string, user?: object) => {
logoutGuardUntilRef.current = 0;
- await storeSession(token, user ?? {});
+ sessionTokenBeingStoredRef.current = token;
try {
- await syncMemoryClientToken(token);
- memoryTokenRef.current = token;
- } catch (error) {
- console.warn('[core-state] memory client sync failed after session store:', error);
- }
- // refresh() drives refreshCore, which now owns identity-flip detection
- // and dispatches handleIdentityFlip when both prev and next are
- // authenticated and identities differ. The previous standalone
- // restartApp call here was redundant and skipped the persist purge,
- // letting redux-persist rehydrate the prior user's slices on launch
- // (#900). Restart now happens inside handleIdentityFlip after purge.
- // Swallow refresh failures here so a cold-boot `app_state_snapshot`
- // timeout post-login doesn't surface as an unhandled rejection
- // (OPENHUMAN-REACT-Z/Y) — the polling loop reconciles within
- // `POLL_MS`.
- await refresh().catch(err => {
- log('refresh failed after session store: %O', sanitizeError(err));
- });
- if (!isLocalSessionToken(token)) {
- await refreshTeams().catch(err => {
- log('refreshTeams failed after session store: %O', sanitizeError(err));
+ await storeSession(token, user ?? {});
+ try {
+ await syncMemoryClientToken(token);
+ memoryTokenRef.current = token;
+ } catch (error) {
+ console.warn('[core-state] memory client sync failed after session store:', error);
+ }
+ // refresh() drives refreshCore, which now owns identity-flip detection
+ // and dispatches handleIdentityFlip when both prev and next are
+ // authenticated and identities differ. The previous standalone
+ // restartApp call here was redundant and skipped the persist purge,
+ // letting redux-persist rehydrate the prior user's slices on launch
+ // (#900). Restart now happens inside handleIdentityFlip after purge.
+ // Swallow refresh failures here so a cold-boot `app_state_snapshot`
+ // timeout post-login doesn't surface as an unhandled rejection
+ // (OPENHUMAN-REACT-Z/Y) — the polling loop reconciles within
+ // `POLL_MS`.
+ await refresh().catch(err => {
+ log('refresh failed after session store: %O', sanitizeError(err));
});
+ if (!isLocalSessionToken(token)) {
+ await refreshTeams().catch(err => {
+ log('refreshTeams failed after session store: %O', sanitizeError(err));
+ });
+ }
+ } finally {
+ if (sessionTokenBeingStoredRef.current === token) {
+ sessionTokenBeingStoredRef.current = null;
+ }
}
},
[refresh, refreshTeams]
@@ -782,7 +795,9 @@ export default function CoreStateProvider({ children }: { children: ReactNode })
// so re-registers are rare.
useEffect(() => {
const runReauth = async (method: string, source: string, reason: AuthExpiredReason) => {
- if (isLocalSessionToken(getCoreStateSnapshot().snapshot.sessionToken)) {
+ const effectiveToken =
+ sessionTokenBeingStoredRef.current ?? getCoreStateSnapshot().snapshot.sessionToken;
+ if (isLocalSessionToken(effectiveToken)) {
log('auth-expired ignored for local session (method=%s source=%s)', method, source);
return;
}
diff --git a/app/src/providers/__tests__/CoreStateProvider.test.tsx b/app/src/providers/__tests__/CoreStateProvider.test.tsx
index 6b3751857a..c48f850ed3 100644
--- a/app/src/providers/__tests__/CoreStateProvider.test.tsx
+++ b/app/src/providers/__tests__/CoreStateProvider.test.tsx
@@ -536,6 +536,45 @@ describe('CoreStateProvider — identity-change cache clearing', () => {
expect(vi.mocked(tauriCommands.logout)).not.toHaveBeenCalled();
});
+ it('does not clear a local session while its refreshed snapshot is still pending', async () => {
+ const localToken = `eyJhbGciOiJub25lIn0.${window.btoa(JSON.stringify({ sub: 'local' }))}.local`;
+ const stored = deferred<void>();
+ fetchSnapshot.mockResolvedValue(makeSnapshot({ userId: 'cloud-user', sessionToken: 'old' }));
+ listTeams.mockResolvedValue([]);
+ vi.mocked(tauriCommands.storeSession).mockReset();
+ vi.mocked(tauriCommands.storeSession).mockReturnValue(stored.promise as never);
+ vi.mocked(tauriCommands.logout).mockReset();
+ vi.mocked(tauriCommands.logout).mockResolvedValue(undefined as never);
+
+ let ctx: CoreStateContextValue | undefined;
+ render(
+ <CoreStateProvider>
+ <Consumer captureCtx={next => (ctx = next)} />
+ </CoreStateProvider>
+ );
+ await waitFor(() => expect(screen.getByTestId('ready').textContent).toBe('ready'));
+
+ let storing!: Promise<void>;
+ await act(async () => {
+ storing = ctx!.storeSessionToken(localToken, { id: 'local' });
+ await Promise.resolve();
+ window.dispatchEvent(
+ new CustomEvent('core-rpc-auth-expired', {
+ detail: {
+ method: 'openhuman.announcements_get_latest',
+ source: 'rpc',
+ reason: 'confirmed',
+ },
+ })
+ );
+ await Promise.resolve();
+ });
+
+ expect(vi.mocked(tauriCommands.logout)).not.toHaveBeenCalled();
+ stored.resolve();
+ await act(async () => storing);
+ });
+
it('dispatching core-rpc-auth-expired triggers clearSession (and debounces repeated fires within 10s)', async () => {
fetchSnapshot.mockResolvedValue(makeSnapshot({ userId: 'u1', sessionToken: 'tok1' }));
listTeams.mockResolvedValue([]);