Skip to content

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

fix: session expiry loop leaves user stuck on chat screen (#5868)

shanuf9190bb81935
diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsx
index 87b97da7af..06e8cac456 100644
--- a/app/src/providers/ChatRuntimeProvider.tsx
+++ b/app/src/providers/ChatRuntimeProvider.tsx
@@ -1281,6 +1281,19 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {
scope: 'chat',
sourceDomain: 'chat',
});
+ // #5868: a session_expired chat error means the Rust core already
+ // published DomainEvent::SessionExpired and set signed_out=true, but
+ // the auth:session_expired socket event may have been suppressed
+ // (isBootstrapping guard) or missed. Dispatch the same window event
+ // socketService emits so CoreStateProvider's runReauth() fires the
+ // clearSession() → login redirect path from this side too. The 10s
+ // debounce in runReauth() ensures a concurrent socket event does not
+ // cause a double-clear.
+ if (event.error_type === 'session_expired') {
+ window.dispatchEvent(
+ new CustomEvent('openhuman:session-expired', { detail: { source: 'chat-error' } })
+ );
+ }
}
// Parallel (forked) turn error: resolve only its lane, leaving the
diff --git a/app/src/providers/CoreStateProvider.tsx b/app/src/providers/CoreStateProvider.tsx
index 53fa0323c9..11ccbe2072 100644
--- a/app/src/providers/CoreStateProvider.tsx
+++ b/app/src/providers/CoreStateProvider.tsx
@@ -719,6 +719,9 @@ export default function CoreStateProvider({ children }: { children: ReactNode })
const lastReauthReasonRef = useRef<AuthExpiredReason | null>(null);
const reauthAttemptIdRef = useRef(0);
const suppressReauthUntilRef = useRef(0);
+ // Set to true when a `confirmed` session-expiry event fires while isBootstrapping
+ // is still true. The bootstrap-completion effect below replays it.
+ const pendingConfirmedReauthRef = useRef(false);
// Listen for deep-link auth suppression signals so that an in-flight
// `auth_store_session` call (OAuth deep link) does not race with the
@@ -754,12 +757,32 @@ export default function CoreStateProvider({ children }: { children: ReactNode })
// here either — the signed-out UI doesn't render user-scoped slices,
// and a same-user re-login should not pay a "rehydrate from disk"
// cost (slices are still in memory). See [#900].
- await tauriLogout();
+ // Wrap tauriLogout separately so a failure (e.g. the Rust-side
+ // SessionExpiredSubscriber already cleared the session first) does not
+ // prevent the subsequent refresh() — which is what actually flips the
+ // router to the login screen.
+ await tauriLogout().catch(err => {
+ log('tauriLogout failed in clearSession — proceeding with refresh: %O', sanitizeError(err));
+ });
await refresh().catch(err => {
log('refresh failed after clearSession: %O', sanitizeError(err));
});
}, [commitState, refresh]);
+ // When a confirmed session-expiry event arrives while the core is still
+ // bootstrapping, runReauth() sets pendingConfirmedReauthRef instead of
+ // dropping it. Once isBootstrapping flips to false (first successful
+ // snapshot) this effect replays it so the router reaches the login screen.
+ useEffect(() => {
+ if (!state.isBootstrapping && pendingConfirmedReauthRef.current) {
+ pendingConfirmedReauthRef.current = false;
+ log('auth-expired: replaying confirmed reauth suppressed during bootstrap');
+ void clearSession().catch(err => {
+ log('clearSession failed after post-bootstrap replay: %O', sanitizeError(err));
+ });
+ }
+ }, [state.isBootstrapping, clearSession]);
+
// Listen for two flavours of session expiry, both routed through the
// same debounced `clearSession`:
//
@@ -787,7 +810,15 @@ export default function CoreStateProvider({ children }: { children: ReactNode })
return;
}
if (getCoreStateSnapshot().isBootstrapping) {
- log('auth-expired suppressed during bootstrap (method=%s source=%s)', method, source);
+ if (reason === 'confirmed') {
+ // Queue so the bootstrap-completion effect can replay it once the first
+ // snapshot lands. Without this the event is lost: signed_out=true prevents
+ // re-publication, leaving the user stuck in the chat shell forever.
+ pendingConfirmedReauthRef.current = true;
+ log('auth-expired queued for post-bootstrap replay (method=%s source=%s)', method, source);
+ } else {
+ log('auth-expired suppressed during bootstrap (method=%s source=%s)', method, source);
+ }
return;
}
const now = Date.now();
diff --git a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
index 9044213625..ad307e2107 100644
--- a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
+++ b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
@@ -2052,6 +2052,45 @@ describe('ChatRuntimeProvider — skill tool-chain latency (#4273 AC3)', () => {
);
});
+ it('dispatches openhuman:session-expired window event on session_expired chat error (#5868)', () => {
+ const listeners = renderProvider();
+ const received: Event[] = [];
+ const handler = (e: Event) => received.push(e);
+ window.addEventListener('openhuman:session-expired', handler);
+
+ act(() => {
+ listeners.onError?.({
+ thread_id: 't-sess',
+ request_id: 'r1',
+ error_type: 'session_expired',
+ message: 'Your OpenHuman session has expired. Please sign in again to continue.',
+ } as chatService.ChatErrorEvent);
+ });
+
+ window.removeEventListener('openhuman:session-expired', handler);
+ expect(received).toHaveLength(1);
+ expect((received[0] as CustomEvent).detail?.source).toBe('chat-error');
+ });
+
+ it('does not dispatch openhuman:session-expired for non-session error types', () => {
+ const listeners = renderProvider();
+ const received: Event[] = [];
+ const handler = (e: Event) => received.push(e);
+ window.addEventListener('openhuman:session-expired', handler);
+
+ act(() => {
+ listeners.onError?.({
+ thread_id: 't-inf',
+ request_id: 'r1',
+ error_type: 'inference',
+ message: 'Something went wrong.',
+ } as chatService.ChatErrorEvent);
+ });
+
+ window.removeEventListener('openhuman:session-expired', handler);
+ expect(received).toHaveLength(0);
+ });
+
it('closes the latency window on chat_error without warning', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const listeners = renderProvider();
diff --git a/app/src/providers/__tests__/CoreStateProvider.test.tsx b/app/src/providers/__tests__/CoreStateProvider.test.tsx
index 6b3751857a..20f5514dd5 100644
--- a/app/src/providers/__tests__/CoreStateProvider.test.tsx
+++ b/app/src/providers/__tests__/CoreStateProvider.test.tsx
@@ -971,6 +971,77 @@ describe('CoreStateProvider — config recovery notice (#5167)', () => {
});
});
+describe('session expiry fixes (#5868)', () => {
+ it('clearSession calls refresh even when tauriLogout throws', async () => {
+ vi.mocked(coreStateApi.fetchCoreAppSnapshot).mockResolvedValue(
+ makeSnapshot({ userId: 'u1', sessionToken: 'tok1' })
+ );
+ vi.mocked(tauriCommands.logout).mockReset();
+ vi.mocked(tauriCommands.logout).mockRejectedValue(new Error('already cleared'));
+
+ render(
+ <CoreStateProvider>
+ <Consumer />
+ </CoreStateProvider>
+ );
+ await waitFor(() => expect(screen.getByTestId('ready').textContent).toBe('ready'));
+
+ // Trigger a confirmed session-expiry via the socket path.
+ await act(async () => {
+ window.dispatchEvent(
+ new CustomEvent('openhuman:session-expired', { detail: { source: 'test' } })
+ );
+ });
+
+ // Even though logout threw, refresh must still have fired and the snapshot
+ // should now show signed-out state.
+ await waitFor(() =>
+ expect(screen.getByTestId('token').textContent).toBe('none')
+ );
+ });
+
+ it('confirmed session-expiry during bootstrap is replayed after the first snapshot lands (#5868)', async () => {
+ // The module-level store may carry isBootstrapping:false from prior tests;
+ // reset it so the component mounts with the correct initial value.
+ setCoreStateSnapshot({ ...getCoreStateSnapshot(), isBootstrapping: true, isReady: false });
+
+ // Hold the first snapshot until we control the release.
+ let resolveSnapshot!: (v: Awaited<ReturnType<typeof coreStateApi.fetchCoreAppSnapshot>>) => void;
+ vi.mocked(coreStateApi.fetchCoreAppSnapshot).mockImplementation(
+ () => new Promise(res => { resolveSnapshot = res; })
+ );
+ vi.mocked(tauriCommands.logout).mockReset();
+ vi.mocked(tauriCommands.logout).mockResolvedValue(undefined as never);
+ // getSessionToken: return null so confirmSessionTokenGone fast-paths to true
+ // (only reached for unconfirmed events — confirmed skips the check entirely).
+ vi.mocked(tauriCommands.getSessionToken).mockResolvedValue(null);
+
+ render(
+ <CoreStateProvider>
+ <Consumer />
+ </CoreStateProvider>
+ );
+
+ // Fire a confirmed session-expiry WHILE bootstrap is still pending.
+ await act(async () => {
+ window.dispatchEvent(
+ new CustomEvent('openhuman:session-expired', { detail: { source: 'test-bootstrap' } })
+ );
+ });
+
+ // logout must NOT have been called yet — bootstrap not done.
+ expect(vi.mocked(tauriCommands.logout)).not.toHaveBeenCalled();
+
+ // Now let the snapshot land, completing bootstrap.
+ await act(async () => {
+ resolveSnapshot(makeSnapshot({ userId: 'u1', sessionToken: 'tok1' }));
+ });
+
+ // The pending reauth must replay and call logout.
+ await waitFor(() => expect(vi.mocked(tauriCommands.logout)).toHaveBeenCalledTimes(1));
+ });
+});
+
describe('coreStatePollFailureDebugMessage', () => {
it('describes post-bootstrap poll failures without impossible retry counters', () => {
expect(coreStatePollFailureDebugMessage(0)).toBeNull();
diff --git a/src/openhuman/web_chat/web_errors_part_02.rs b/src/openhuman/web_chat/web_errors_part_02.rs
index b94be461c7..b637e84297 100644
--- a/src/openhuman/web_chat/web_errors_part_02.rs
+++ b/src/openhuman/web_chat/web_errors_part_02.rs
@@ -47,8 +47,8 @@ pub(crate) fn classify_inference_error(err: &str) -> ClassifiedError {
// `auth_error`.
ClassifiedError {
error_type: "session_expired",
- message: "Your OpenHuman session expired while the app was idle. \
- Please sign in again to resume."
+ message: "Your OpenHuman session has expired. \
+ Please sign in again to continue."
.to_string(),
source: "auth",
retryable: false,