π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(desktop): trace Session Expired cause and resume onboarding at Login (#15604)
Innei991c2f79e8f7
diff --git a/apps/desktop/src/main/controllers/AuthCtr.ts b/apps/desktop/src/main/controllers/AuthCtr.tsindex d67967de998..7b37adbea00 100644--- a/apps/desktop/src/main/controllers/AuthCtr.ts+++ b/apps/desktop/src/main/controllers/AuthCtr.ts@@ -321,7 +321,9 @@ export default class AuthCtr extends ControllerModule {this.stopAutoRefresh();await this.remoteServerConfigCtr.clearTokens();await this.remoteServerConfigCtr.setRemoteServerConfig({ active: false });- this.broadcastAuthorizationRequired();+ this.broadcastAuthorizationRequired(+ `auto-refresh:non_retryable ${result.error ?? ''}`.trim(),+ );} else {// For other errors (after retries exhausted), log but don't clear tokens immediately// The next refresh cycle will retry@@ -432,7 +434,7 @@ export default class AuthCtr extends ControllerModule {this.stopAutoRefresh();await this.remoteServerConfigCtr.clearTokens();await this.remoteServerConfigCtr.setRemoteServerConfig({ active: false });- this.broadcastAuthorizationRequired();+ this.broadcastAuthorizationRequired(`refresh:non_retryable ${result.error ?? ''}`.trim());} else {// For transient errors, don't clear tokens - allow manual retrylogger.warn('Refresh failed but error may be transient, tokens preserved for retry');@@ -450,7 +452,7 @@ export default class AuthCtr extends ControllerModule {this.stopAutoRefresh();await this.remoteServerConfigCtr.clearTokens();await this.remoteServerConfigCtr.setRemoteServerConfig({ active: false });- this.broadcastAuthorizationRequired();+ this.broadcastAuthorizationRequired(`refresh:exception ${errorMessage}`);}return { error: errorMessage, success: false };@@ -618,15 +620,17 @@ export default class AuthCtr extends ControllerModule {}/**- * Broadcast authorization required event+ * Broadcast authorization required event.+ * `reason` is a short tag (e.g. `refresh:invalid_grant`, `startup:non_retryable`)+ * recorded so the renderer can log why the Session Expired modal appeared.*/- private broadcastAuthorizationRequired() {- logger.debug('Broadcasting authorizationRequired event to all windows');+ private broadcastAuthorizationRequired(reason: string) {+ logger.info(`Broadcasting authorizationRequired event (reason=${reason})`);const allWindows = BrowserWindow.getAllWindows();for (const win of allWindows) {if (!win.isDestroyed()) {- win.webContents.send('authorizationRequired');+ win.webContents.send('authorizationRequired', { reason });}}}@@ -751,7 +755,9 @@ export default class AuthCtr extends ControllerModule {logger.warn('Non-retryable error during proactive refresh, clearing tokens');await this.remoteServerConfigCtr.clearTokens();await this.remoteServerConfigCtr.setRemoteServerConfig({ active: false });- this.broadcastAuthorizationRequired();+ this.broadcastAuthorizationRequired(+ `startup:non_retryable ${refreshResult.error ?? ''}`.trim(),+ );} else {// For transient errors, still start auto-refresh timer to retry laterlogger.warn('Transient error during proactive refresh, will retry via auto-refresh');diff --git a/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.tsindex 691bcd0bdca..d66c2ec7e4a 100644--- a/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts@@ -797,7 +797,12 @@ describe('AuthCtr', () => {expect(mockRemoteServerConfigCtr.setRemoteServerConfig).toHaveBeenCalledWith({active: false,});- expect(mockWindow.webContents.send).toHaveBeenCalledWith('authorizationRequired');+ expect(mockWindow.webContents.send).toHaveBeenCalledWith(+ 'authorizationRequired',+ expect.objectContaining({+ reason: expect.stringContaining('startup:non_retryable'),+ }),+ );});it('should preserve tokens on transient error', async () => {diff --git a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.tsindex 41038cf2a1c..02200a7a8f2 100644--- a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts+++ b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts@@ -32,22 +32,30 @@ export class BackendProxyProtocolManager {private readonly logger = createLogger('core:BackendProxyProtocolManager');private authRequiredDebounceTimer: NodeJS.Timeout | null = null;+ private pendingAuthRequiredReason: string | null = null;private static readonly AUTH_REQUIRED_DEBOUNCE_MS = 1000;- private notifyAuthorizationRequired() {+ private notifyAuthorizationRequired(reason: string) {// Trailing-edge debounce: coalesce rapid 401 bursts and fire AFTER the burst settles.// This ensures the IPC event is sent after the renderer has had time to mount listeners.+ // The most recent reason wins β within a burst they almost always describe the same cause.+ this.pendingAuthRequiredReason = reason;+if (this.authRequiredDebounceTimer) {clearTimeout(this.authRequiredDebounceTimer);}this.authRequiredDebounceTimer = setTimeout(() => {this.authRequiredDebounceTimer = null;+ const finalReason = this.pendingAuthRequiredReason ?? reason;+ this.pendingAuthRequiredReason = null;++ this.logger.info(`Broadcasting authorizationRequired (reason=${finalReason})`);const allWindows = BrowserWindow.getAllWindows();for (const win of allWindows) {if (!win.isDestroyed()) {- win.webContents.send('authorizationRequired');+ win.webContents.send('authorizationRequired', { reason: finalReason });}}}, BackendProxyProtocolManager.AUTH_REQUIRED_DEBOUNCE_MS);@@ -196,7 +204,32 @@ export class BackendProxyProtocolManager {// Other failures keep 401 without this header (e.g., invalid API keys) and must not notify here.const authRequired = upstreamResponse.headers.get(AUTH_REQUIRED_HEADER) === 'true';if (authRequired) {- this.notifyAuthorizationRequired();+ const pathTag = (() => {+ try {+ return new URL(rewrittenUrl).pathname;+ } catch {+ return rewrittenUrl;+ }+ })();+ const sourceTag = context.source ? `${context.source}:` : '';+ const wwwAuth = upstreamResponse.headers.get('www-authenticate') ?? '';+ // Clone before forwarding the body downstream β the original stream stays+ // intact for the renderer. Body snippet is truncated to keep logs small+ // and to avoid leaking large payloads if the server ever returns one.+ let bodySnippet: string;+ try {+ bodySnippet = (await upstreamResponse.clone().text()).slice(0, 300).replaceAll(/\s+/g, ' ');+ } catch (error) {+ bodySnippet = `<body-read-failed:${error instanceof Error ? error.message : 'unknown'}>`;+ }+ const parts = [+ `proxy:${sourceTag}status=${upstreamResponse.status}`,+ `${request.method} ${pathTag}`,+ `hadToken=${Boolean(token)}`,+ ];+ if (wwwAuth) parts.push(`wwwAuth=${wwwAuth}`);+ if (bodySnippet) parts.push(`body=${bodySnippet}`);+ this.notifyAuthorizationRequired(parts.join(' '));}return new Response(upstreamResponse.body, {diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.tsindex caebffd1a47..36b8b97c646 100644--- a/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts+++ b/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts@@ -258,7 +258,63 @@ describe('BackendProxyProtocolManager', () => {expect(send).not.toHaveBeenCalled();await vi.advanceTimersByTimeAsync(1000);- expect(send).toHaveBeenCalledWith('authorizationRequired');+ expect(send).toHaveBeenCalledWith(+ 'authorizationRequired',+ expect.objectContaining({+ reason: expect.stringContaining('status=207'),+ }),+ );+ });++ it('captures www-authenticate, body snippet and hadToken in reason on 401', async () => {+ vi.useFakeTimers();+ const send = vi.fn();+ vi.mocked(BrowserWindow.getAllWindows).mockReturnValue([+ { isDestroyed: () => false, webContents: { send } },+ ] as any);++ const manager = new BackendProxyProtocolManager();+ const session = {} as any;++ const upstreamBody = JSON.stringify({+ error: { json: { data: { code: 'UNAUTHORIZED' }, message: 'token expired at 2026-06-09' } },+ });+ const headers = new Headers({+ [AUTH_REQUIRED_HEADER]: 'true',+ 'Content-Type': 'application/json',+ 'www-authenticate': 'Bearer error="invalid_token", error_description="expired"',+ });+ const fetchMock = vi.fn<FetchMock>(+ async () => new Response(upstreamBody, { headers, status: 401, statusText: 'Unauthorized' }),+ );+ vi.stubGlobal('fetch', fetchMock as any);++ manager.registerWithRemoteBaseUrl(session, {+ getAccessToken: async () => 'fake-token',+ getRemoteBaseUrl: async () => 'https://remote.example.com',+ });++ const response = await manager.proxy(+ {+ headers: new Headers(),+ method: 'POST',+ url: 'app://renderer/trpc/lambda/me',+ } as any,+ session,+ );++ // Original body is still readable by the downstream caller β clone() must not consume it.+ expect(await response!.text()).toBe(upstreamBody);++ await vi.advanceTimersByTimeAsync(1000);+ expect(send).toHaveBeenCalledTimes(1);+ const [, payload] = send.mock.calls[0];+ expect(payload.reason).toContain('status=401');+ expect(payload.reason).toContain('POST /trpc/lambda/me');+ expect(payload.reason).toContain('hadToken=true');+ expect(payload.reason).toContain('wwwAuth=Bearer error="invalid_token"');+ expect(payload.reason).toContain('UNAUTHORIZED');+ expect(payload.reason).toContain('token expired');});describe('createAppRequestInterceptor', () => {diff --git a/packages/electron-client-ipc/src/events/remoteServer.ts b/packages/electron-client-ipc/src/events/remoteServer.tsindex 576311ce153..a556d58fdea 100644--- a/packages/electron-client-ipc/src/events/remoteServer.ts+++ b/packages/electron-client-ipc/src/events/remoteServer.ts@@ -30,7 +30,13 @@ export interface RemoteServerBroadcastEvents {authorizationFailed: (params: { error: string }) => void;/** Broadcast authorization progress for UI updates */authorizationProgress: (params: AuthorizationProgress) => void;- authorizationRequired: (params: void) => void;+ /**+ * Broadcast when the main process needs the user to re-authenticate.+ * `reason` is a short, log-friendly tag describing why (e.g. `refresh:invalid_grant`,+ * `proxy:status=401`, `startup:non_retryable`). Useful for diagnosing why the+ * Session Expired modal showed up in field reports.+ */+ authorizationRequired: (params: { reason: string }) => void;authorizationSuccessful: (params: void) => void;remoteServerConfigUpdated: (params: void) => void;tokenRefreshed: (params: void) => void;diff --git a/src/features/Electron/AuthRequiredModal/index.tsx b/src/features/Electron/AuthRequiredModal/index.tsxindex addcda240dc..203a826b081 100644--- a/src/features/Electron/AuthRequiredModal/index.tsx+++ b/src/features/Electron/AuthRequiredModal/index.tsx@@ -9,13 +9,15 @@ import {ModalFooter,type ModalInstance,} from '@lobehub/ui/base-ui';-import { t as i18nt } from 'i18next';+import debug from 'debug';import { AlertCircle, LogIn } from 'lucide-react';import { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useElectronStore } from '@/store/electron';+const log = debug('lobe-client:auth-required-modal');+interface AuthRequiredModalContentProps {onActionReady: (api: { signIn: () => Promise<void> }) => void;onClose: () => void;@@ -94,6 +96,7 @@ const AuthRequiredFooter = memo<FooterProps>(({ isSigningIn, onLater, onSignIn }AuthRequiredFooter.displayName = 'AuthRequiredFooter';export const useAuthRequiredModal = () => {+ const { t } = useTranslation('auth');const instanceRef = useRef<ModalInstance | null>(null);const open = useCallback(() => {@@ -140,11 +143,11 @@ export const useAuthRequiredModal = () => {title: (<Flexbox horizontal align="center" gap={8}><Icon icon={AlertCircle} />- {i18nt('authModal.title', { ns: 'auth' })}+ {t('authModal.title')}</Flexbox>),});- }, []);+ }, [t]);return { open };};@@ -152,14 +155,25 @@ export const useAuthRequiredModal = () => {const AuthRequiredModal = memo(() => {const { open } = useAuthRequiredModal();- useWatchBroadcast('authorizationRequired', () => {+ useWatchBroadcast('authorizationRequired', (payload) => {+ const reason = payload?.reason ?? 'unknown';const state = useElectronStore.getState();- if (state.isConnectionDrawerOpen) return;+ if (state.isConnectionDrawerOpen) {+ log('authorizationRequired ignored (connection drawer open). reason=%s', reason);+ return;+ }// Wait until remote sync config has loaded once (avoid a flash before SWR resolves).// Do not gate on `dataSyncConfig.active`: after sign-out `active` is false but 401 + X-Auth-Required// still means the user must re-authenticate; gating on active would suppress the modal forever.- if (!state.isInitRemoteServerConfig) return;-+ if (!state.isInitRemoteServerConfig) {+ log(+ 'authorizationRequired ignored (remote server config not initialized). reason=%s',+ reason,+ );+ return;+ }++ log('authorizationRequired: opening modal. reason=%s', reason);open();});diff --git a/src/routes/(desktop)/desktop-onboarding/index.tsx b/src/routes/(desktop)/desktop-onboarding/index.tsxindex 041ed9b5b5b..d883b52e42a 100644--- a/src/routes/(desktop)/desktop-onboarding/index.tsx+++ b/src/routes/(desktop)/desktop-onboarding/index.tsx@@ -13,10 +13,13 @@ import DataModeStep from './features/DataModeStep';import LoginStep from './features/LoginStep';import PermissionsStep from './features/PermissionsStep';import WelcomeStep from './features/WelcomeStep';+import { resolveInitialScreen } from './resolveInitialScreen';import {clearDesktopOnboardingScreen,+ getDesktopOnboardingEverCompleted,getDesktopOnboardingScreen,setDesktopOnboardingCompleted,+ setDesktopOnboardingEverCompleted,setDesktopOnboardingScreen,} from './storage';import { DesktopOnboardingScreen, isDesktopOnboardingScreen } from './types';@@ -40,11 +43,13 @@ const DesktopOnboardingPage = memo(() => {];const resolveScreenForPlatform = useCallback(- (screen: DesktopOnboardingScreen) => {- if (!isMac && screen === DesktopOnboardingScreen.Permissions)- return DesktopOnboardingScreen.DataMode;- return screen;- },+ (screen: DesktopOnboardingScreen) =>+ resolveInitialScreen({+ everCompleted: false,+ isMac,+ requested: screen,+ saved: null,+ }),[isMac],);@@ -62,10 +67,12 @@ const DesktopOnboardingPage = memo(() => {useEffect(() => {if (isLoading) return;- const saved = getDesktopOnboardingScreen();- const requested = getRequestedScreenFromUrl();-- const initial = resolveScreenForPlatform(requested ?? saved ?? DesktopOnboardingScreen.Welcome);+ const initial = resolveInitialScreen({+ everCompleted: getDesktopOnboardingEverCompleted(),+ isMac,+ requested: getRequestedScreenFromUrl(),+ saved: getDesktopOnboardingScreen(),+ });setCurrentScreen(initial);@@ -74,13 +81,7 @@ const DesktopOnboardingPage = memo(() => {if (currentUrlScreen !== initial) {setSearchParams({ screen: initial });}- }, [- getRequestedScreenFromUrl,- isLoading,- resolveScreenForPlatform,- searchParams,- setSearchParams,- ]);+ }, [getRequestedScreenFromUrl, isLoading, isMac, searchParams, setSearchParams]);// Persist current screen to localStorage.useEffect(() => {@@ -147,6 +148,7 @@ const DesktopOnboardingPage = memo(() => {if (!next) {// Complete onboarding - mark as completed and clear persisted screen statesetDesktopOnboardingCompleted();+ setDesktopOnboardingEverCompleted();clearDesktopOnboardingScreen();// Restore window minimum size before hard reload (cleanup won't run due to hard navigation)diff --git a/src/routes/(desktop)/desktop-onboarding/resolveInitialScreen.test.ts b/src/routes/(desktop)/desktop-onboarding/resolveInitialScreen.test.tsnew file mode 100644index 00000000000..40cfd82e567--- /dev/null+++ b/src/routes/(desktop)/desktop-onboarding/resolveInitialScreen.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from 'vitest';++import { resolveInitialScreen } from './resolveInitialScreen';+import { DesktopOnboardingScreen } from './types';++describe('resolveInitialScreen', () => {+ it('returns Welcome for first-time users with no saved/requested screen', () => {+ expect(+ resolveInitialScreen({+ everCompleted: false,+ isMac: true,+ requested: null,+ saved: null,+ }),+ ).toBe(DesktopOnboardingScreen.Welcome);+ });++ it('returns Login when the user has previously completed onboarding (returning user)', () => {+ expect(+ resolveInitialScreen({+ everCompleted: true,+ isMac: true,+ requested: null,+ saved: null,+ }),+ ).toBe(DesktopOnboardingScreen.Login);+ });++ it('prefers the saved (in-progress) screen over the ever-completed fallback', () => {+ // Edge case: an in-progress user who somehow has ever-completed=true (e.g.+ // re-entered after first completion). The mid-flow position still wins.+ expect(+ resolveInitialScreen({+ everCompleted: true,+ isMac: true,+ requested: null,+ saved: DesktopOnboardingScreen.DataMode,+ }),+ ).toBe(DesktopOnboardingScreen.DataMode);+ });++ it('honours an explicit ?screen= URL parameter over everything else', () => {+ expect(+ resolveInitialScreen({+ everCompleted: true,+ isMac: true,+ requested: DesktopOnboardingScreen.Welcome,+ saved: DesktopOnboardingScreen.DataMode,+ }),+ ).toBe(DesktopOnboardingScreen.Welcome);+ });++ it('rewrites Permissions to DataMode on non-macOS', () => {+ expect(+ resolveInitialScreen({+ everCompleted: false,+ isMac: false,+ requested: DesktopOnboardingScreen.Permissions,+ saved: null,+ }),+ ).toBe(DesktopOnboardingScreen.DataMode);+ });+});diff --git a/src/routes/(desktop)/desktop-onboarding/resolveInitialScreen.ts b/src/routes/(desktop)/desktop-onboarding/resolveInitialScreen.tsnew file mode 100644index 00000000000..2966af64b4d--- /dev/null+++ b/src/routes/(desktop)/desktop-onboarding/resolveInitialScreen.ts@@ -0,0 +1,41 @@+import { DesktopOnboardingScreen } from './types';++interface ResolveInitialScreenInput {+ /** Has the user previously completed onboarding on this install? */+ everCompleted: boolean;+ /** Running on macOS β drives the Permissions screen fallback. */+ isMac: boolean;+ /** Explicit `?screen=` query parameter, when present and valid. */+ requested: DesktopOnboardingScreen | null;+ /** Whatever screen the component last persisted, or `null` if cleared/missing. */+ saved: DesktopOnboardingScreen | null;+}++/**+ * Pick which onboarding screen the user should land on when entering+ * `/desktop-onboarding`. Priority:+ *+ * 1. `requested` from the URL β explicit deep-link wins.+ * 2. `saved` β a mid-flow user resumes where they left off.+ * 3. `Login` if the user has *ever* completed onboarding (returning user after+ * sign-out / token expiry β Welcome / Permissions / DataMode are first-run+ * screens and would force the whole flow again).+ * 4. `Welcome` for first-time users.+ *+ * On non-macOS, `Permissions` is rewritten to `DataMode` since the macOS-only+ * screen has no useful content.+ */+export const resolveInitialScreen = ({+ everCompleted,+ isMac,+ requested,+ saved,+}: ResolveInitialScreenInput): DesktopOnboardingScreen => {+ const fallback = everCompleted ? DesktopOnboardingScreen.Login : DesktopOnboardingScreen.Welcome;+ const chosen = requested ?? saved ?? fallback;++ if (!isMac && chosen === DesktopOnboardingScreen.Permissions) {+ return DesktopOnboardingScreen.DataMode;+ }+ return chosen;+};diff --git a/src/routes/(desktop)/desktop-onboarding/storage.test.ts b/src/routes/(desktop)/desktop-onboarding/storage.test.tsnew file mode 100644index 00000000000..739e421b091--- /dev/null+++ b/src/routes/(desktop)/desktop-onboarding/storage.test.ts@@ -0,0 +1,34 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import {+ DESKTOP_ONBOARDING_EVER_COMPLETED_KEY,+ getDesktopOnboardingEverCompleted,+ setDesktopOnboardingEverCompleted,+} from './storage';++describe('desktop-onboarding storage', () => {+ beforeEach(() => {+ window.localStorage.clear();+ });++ afterEach(() => {+ window.localStorage.clear();+ });++ describe('ever-completed flag', () => {+ it('returns false by default', () => {+ expect(getDesktopOnboardingEverCompleted()).toBe(false);+ });++ it('persists set-and-read across calls', () => {+ expect(setDesktopOnboardingEverCompleted()).toBe(true);+ expect(getDesktopOnboardingEverCompleted()).toBe(true);+ expect(window.localStorage.getItem(DESKTOP_ONBOARDING_EVER_COMPLETED_KEY)).toBe('1');+ });++ it('returns false when localStorage holds an unrelated value', () => {+ window.localStorage.setItem(DESKTOP_ONBOARDING_EVER_COMPLETED_KEY, '0');+ expect(getDesktopOnboardingEverCompleted()).toBe(false);+ });+ });+});diff --git a/src/routes/(desktop)/desktop-onboarding/storage.ts b/src/routes/(desktop)/desktop-onboarding/storage.tsindex 6bb71921db0..178a0fb0063 100644--- a/src/routes/(desktop)/desktop-onboarding/storage.ts+++ b/src/routes/(desktop)/desktop-onboarding/storage.ts@@ -2,6 +2,7 @@ import { type DesktopOnboardingScreen } from './types';import { isDesktopOnboardingScreen } from './types';export const DESKTOP_ONBOARDING_COMPLETED_KEY = 'lobechat:desktop:onboarding:completed:v1';+export const DESKTOP_ONBOARDING_EVER_COMPLETED_KEY = 'lobechat:desktop:onboarding:everCompleted:v1';export const DESKTOP_ONBOARDING_SCREEN_KEY = 'lobechat:desktop:onboarding:screen:v1';/**@@ -32,6 +33,37 @@ export const setDesktopOnboardingCompleted = () => {}};+/**+ * Whether the user has *ever* completed desktop onboarding on this install.+ * Backed by localStorage so it survives quit/relaunch β used to skip first-run+ * screens (Welcome / Permissions / DataMode) when a returning user is sent+ * back to /desktop-onboarding (e.g. token refresh failed, sign-out).+ */+export const getDesktopOnboardingEverCompleted = () => {+ if (typeof window === 'undefined') return false;++ try {+ return window.localStorage.getItem(DESKTOP_ONBOARDING_EVER_COMPLETED_KEY) === '1';+ } catch {+ return false;+ }+};++/**+ * Mark desktop onboarding as completed permanently. Should be called once on+ * first-time completion and is never cleared.+ */+export const setDesktopOnboardingEverCompleted = () => {+ if (typeof window === 'undefined') return false;++ try {+ window.localStorage.setItem(DESKTOP_ONBOARDING_EVER_COMPLETED_KEY, '1');+ return true;+ } catch {+ return false;+ }+};+/*** Get the persisted onboarding screen (for restoring after app restart)*/