π€― 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): keep the device gateway connected after auth_failed (#20683)
Arvin Xu78c8e661f53a
diff --git a/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts b/apps/desktop/src/main/controllers/RemoteServerConfigCtr.tsindex b476706ca14..21a3d95aeed 100644--- a/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts+++ b/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts@@ -251,6 +251,7 @@ export default class RemoteServerConfigCtr extends ControllerModule {lastRefreshAt: this.lastRefreshAt,refreshToken: this.encryptedRefreshToken,});+ this.syncGatewayAccessToken(accessToken);return;}@@ -272,6 +273,22 @@ export default class RemoteServerConfigCtr extends ControllerModule {lastRefreshAt: this.lastRefreshAt,refreshToken: this.encryptedRefreshToken,});++ this.syncGatewayAccessToken(accessToken);+ }++ /**+ * Hand a freshly stored access token to the live device-gateway socket.+ *+ * The gateway client caches the token it was constructed with and replays it+ * on every backoff / heartbeat reconnect, while the token itself is rotated+ * here (AuthCtr's auto-refresh timer). Without this push the refresh only+ * became visible after the connection had already been torn down and rejected+ * β the socket dropped, the client replayed the stale token, and `auth_failed`+ * left the device offline.+ */+ private syncGatewayAccessToken(accessToken: string) {+ this.app.getService(GatewayConnectionService)?.updatePersonalToken(accessToken);}/**diff --git a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.tsindex 1fc0679d1f4..caeee93041c 100644--- a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts@@ -47,6 +47,7 @@ const mockBrowserManager = {const mockGatewayConnectionSrv = {disconnect: vi.fn().mockResolvedValue({ success: true }),+ updatePersonalToken: vi.fn(),};const mockApp = {@@ -748,6 +749,12 @@ describe('RemoteServerConfigCtr', () => {}),);});++ it('should hand the new access token to the live gateway connection', async () => {+ await controller.saveTokens('fresh-access', 'refresh', 3600);++ expect(mockGatewayConnectionSrv.updatePersonalToken).toHaveBeenCalledWith('fresh-access');+ });});describe('getRemoteServerUrl', () => {diff --git a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.tsindex 1fc9b845fd8..a181bd87180 100644--- a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts+++ b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts@@ -1,3 +1,5 @@+import { EventEmitter } from 'node:events';+import type { GatewayClient } from '@lobechat/device-gateway-client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -234,3 +236,156 @@ describe('GatewayConnectionService status broadcast', () => {expect(broadcastStatuses()).toEqual(['disconnected']);});});++describe('GatewayConnectionService auth recovery', () => {+ let service: GatewayConnectionService;+ let doConnect: ReturnType<typeof vi.fn>;++ const createFakeClient = () => {+ const client = new EventEmitter() as any;+ client.connect = vi.fn().mockResolvedValue(undefined);+ client.disconnect = vi.fn().mockResolvedValue(undefined);+ client.reconnect = vi.fn().mockResolvedValue(undefined);+ client.updateToken = vi.fn();+ return client as GatewayClient & {+ disconnect: ReturnType<typeof vi.fn>;+ reconnect: ReturnType<typeof vi.fn>;+ updateToken: ReturnType<typeof vi.fn>;+ };+ };++ /** Flush the async handlers that the event listeners kick off without awaiting. */+ const flush = async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ await new Promise((resolve) => setTimeout(resolve, 0));+ };++ beforeEach(() => {+ const app = {+ browserManager: { broadcastToAllWindows: vi.fn() },+ storeManager: { get: vi.fn((_key: string, fallback?: unknown) => fallback), set: vi.fn() },+ } as unknown as App;+ service = new GatewayConnectionService(app);+ doConnect = vi.fn().mockResolvedValue({ success: true });+ (service as any).doConnect = doConnect;+ });++ describe('personal connection', () => {+ it('refreshes the token and reconnects after auth_failed', async () => {+ const refresher = vi.fn().mockResolvedValue({ success: true });+ service.setTokenRefresher(refresher);+ const client = createFakeClient();+ (service as any).setupClientEvents(client);++ client.emit('auth_failed', 'exp claim timestamp check failed');+ await flush();++ expect(refresher).toHaveBeenCalledTimes(1);+ expect(doConnect).toHaveBeenCalledTimes(1);+ });++ it('retries only once when the refreshed token is rejected again', async () => {+ const refresher = vi.fn().mockResolvedValue({ success: true });+ service.setTokenRefresher(refresher);+ const client = createFakeClient();+ (service as any).setupClientEvents(client);++ client.emit('auth_failed', 'exp claim timestamp check failed');+ await flush();+ client.emit('auth_failed', 'exp claim timestamp check failed');+ await flush();++ expect(refresher).toHaveBeenCalledTimes(1);+ expect(doConnect).toHaveBeenCalledTimes(1);+ expect(service.getStatus()).toBe('disconnected');+ });++ it('gives the retry budget back once a connection authenticates', async () => {+ const refresher = vi.fn().mockResolvedValue({ success: true });+ service.setTokenRefresher(refresher);+ const client = createFakeClient();+ (service as any).setupClientEvents(client);++ client.emit('auth_failed', 'first');+ await flush();+ client.emit('connected');+ client.emit('auth_failed', 'second');+ await flush();++ expect(refresher).toHaveBeenCalledTimes(2);+ expect(doConnect).toHaveBeenCalledTimes(2);+ });++ it('stays disconnected without looping when the refresh fails', async () => {+ const refresher = vi.fn().mockResolvedValue({ success: false, error: 'invalid_grant' });+ service.setTokenRefresher(refresher);+ const client = createFakeClient();+ (service as any).setupClientEvents(client);++ client.emit('auth_failed', 'exp claim timestamp check failed');+ await flush();++ expect(refresher).toHaveBeenCalledTimes(1);+ expect(doConnect).not.toHaveBeenCalled();+ expect(service.getStatus()).toBe('disconnected');+ });++ it('pushes a refreshed token into the live client', () => {+ const client = createFakeClient();+ (service as any).client = client;++ service.updatePersonalToken('fresh-token');++ expect(client.updateToken).toHaveBeenCalledWith('fresh-token');+ });+ });++ describe('workspace connection', () => {+ const setupWorkspace = (service: GatewayConnectionService, workspaceId: string) => {+ const client = createFakeClient();+ (service as any).workspaceClients.set(workspaceId, client);+ (service as any).setupClientEvents(client, { workspaceId });+ return client;+ };++ it('re-mints the connect token and reconnects after auth_failed', async () => {+ const client = setupWorkspace(service, 'ws-1');+ const mint = vi.fn().mockResolvedValue('ws-token');+ service.setWorkspaceTokenProvider(mint);++ client.emit('auth_failed', 'token expired');+ await flush();++ expect(mint).toHaveBeenCalledWith('ws-1');+ expect(client.updateToken).toHaveBeenCalledWith('ws-token');+ expect(client.reconnect).toHaveBeenCalledTimes(1);+ expect((service as any).workspaceClients.has('ws-1')).toBe(true);+ });++ it('closes the share instead of looping when it fails again', async () => {+ const client = setupWorkspace(service, 'ws-1');+ const mint = vi.fn().mockResolvedValue('ws-token');+ service.setWorkspaceTokenProvider(mint);++ client.emit('auth_failed', 'token expired');+ await flush();+ client.emit('auth_failed', 'token expired');+ await flush();++ expect(mint).toHaveBeenCalledTimes(1);+ expect(client.disconnect).toHaveBeenCalledTimes(1);+ expect((service as any).workspaceClients.has('ws-1')).toBe(false);+ });++ it('closes the share when the connect token cannot be re-minted', async () => {+ const client = setupWorkspace(service, 'ws-1');+ service.setWorkspaceTokenProvider(vi.fn().mockResolvedValue(null));++ client.emit('auth_failed', 'token expired');+ await flush();++ expect(client.reconnect).not.toHaveBeenCalled();+ expect((service as any).workspaceClients.has('ws-1')).toBe(false);+ });+ });+});diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.tsindex 980193da3ec..8ce7441c0f8 100644--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts@@ -177,6 +177,22 @@ export default class GatewayConnectionService extends ServiceModule {private workspaceClients = new Map<string, GatewayClient>();/** Serializes enrollment restores so reconnect churn can't double-open sockets. */private workspaceRestoreInFlight = false;+ /**+ * Set once an `auth_failed` has already triggered a token refresh for the+ * current personal connection. Unlike `auth_expired`, `auth_failed` is+ * terminal inside the gateway client (it disconnects and switches the backoff+ * reconnect off), so the service is the only thing that can bring the socket+ * back β and this guard is what stops a refresh that keeps yielding a+ * rejected token from spinning forever. Cleared by a successful+ * authentication, or by a user-initiated connect.+ */+ private authRecoveryAttempted = false;+ /**+ * Workspace clients that already spent their single `auth_failed` retry. A+ * weak set on purpose: the retry budget is per client instance (a re-enroll+ * builds a new one), so entries must die with their client.+ */+ private workspaceAuthRetried = new WeakSet<GatewayClient>();// βββ Configuration βββ@@ -194,6 +210,20 @@ export default class GatewayConnectionService extends ServiceModule {this.tokenRefresher = refresher;}+ /**+ * Push a freshly refreshed access token into the live personal connection.+ *+ * The gateway client captures its token at construction and replays that same+ * value on every backoff / heartbeat reconnect, while the access token is+ * refreshed elsewhere (AuthCtr's auto-refresh timer, not the gateway path).+ * Without this push, a token that roams past `exp` while the socket is+ * healthy is re-sent on the next reconnect, rejected with `auth_failed`, and+ * the device goes offline until the user intervenes.+ */+ updatePersonalToken(token: string) {+ this.client?.updateToken(token);+ }+/*** Set tool call handler (to route tool calls to LocalFileCtr/ShellCommandCtr)*/@@ -358,6 +388,9 @@ export default class GatewayConnectionService extends ServiceModule {if (this.status === 'connected' || this.status === 'connecting') {return { success: true };}+ // A user-initiated connect always gets a fresh retry budget β only the+ // automatic recoveries are rationed by the guard.+ this.authRecoveryAttempted = false;return this.doConnect();}@@ -497,7 +530,25 @@ export default class GatewayConnectionService extends ServiceModule {void this.handleWorkspaceAuthExpired(scope.workspaceId);} else {logger.warn('Received auth_expired, will reconnect with refreshed token');- this.handleAuthExpired();+ void this.handleAuthExpired();+ }+ });++ client.on('auth_failed', (reason) => {+ if (scope) {+ void this.handleWorkspaceAuthFailed(scope.workspaceId, reason);+ } else {+ void this.handleAuthFailed(reason);+ }+ });++ client.on('connected', () => {+ // A live authenticated socket is the reset point for the auth_failed+ // retry guards: the next rejection gets a fresh single retry.+ if (scope) {+ this.workspaceAuthRetried.delete(client);+ } else {+ this.authRecoveryAttempted = false;}});@@ -635,6 +686,33 @@ export default class GatewayConnectionService extends ServiceModule {}}+ /**+ * A workspace share connection was rejected outright by the gateway. Recover+ * the same way as an expired connect token β re-mint and reconnect in place β+ * but only once per client instance, so a share that keeps being rejected+ * (revoked membership / revoked share) is closed instead of retried forever.+ * The persisted enrollment is kept: the next startup's restore path settles it+ * against the server row.+ */+ private async handleWorkspaceAuthFailed(workspaceId: string, reason: string) {+ const client = this.workspaceClients.get(workspaceId);+ if (!client) return;++ if (this.workspaceAuthRetried.has(client)) {+ logger.warn(+ `Workspace ${workspaceId} authentication failed again (${reason}), closing share connection`,+ );+ await this.closeWorkspaceClient(workspaceId);+ return;+ }++ this.workspaceAuthRetried.add(client);+ logger.warn(+ `Workspace ${workspaceId} authentication failed (${reason}), re-minting connect token`,+ );+ await this.handleWorkspaceAuthExpired(workspaceId);+ }+/*** Re-open share connections persisted by a previous run. Before reconnecting,* confirm the derived workspace deviceId still has a registered row β the@@ -704,9 +782,14 @@ export default class GatewayConnectionService extends ServiceModule {);}- // βββ Auth Expired Handling βββ+ // βββ Auth Expired / Failed Handling βββ- private async handleAuthExpired() {+ /**+ * Refresh the user token and rebuild the personal connection. A failed+ * refresh settles on `disconnected` and waits for the next user action or app+ * start β the refresher already reports the OIDC reason.+ */+ private async refreshTokenAndReconnect() {// Disconnect the current clientif (this.client) {await this.client.disconnect();@@ -714,7 +797,7 @@ export default class GatewayConnectionService extends ServiceModule {}if (!this.tokenRefresher) {- logger.error('No token refresher configured, cannot handle auth_expired');+ logger.error('No token refresher configured, cannot refresh the access token');this.setStatus('disconnected');return;}@@ -731,6 +814,35 @@ export default class GatewayConnectionService extends ServiceModule {}}+ private async handleAuthExpired() {+ await this.refreshTokenAndReconnect();+ }++ /**+ * The gateway rejected our token outright (`auth_failed`). Unlike+ * `auth_expired` this is terminal inside the gateway client: it emits the+ * event and then calls `disconnect()`, which turns the backoff reconnect off.+ * With nobody listening the socket stayed down β and because the UI switch+ * reads the connection status, it surfaced as the switch turning itself off β+ * until the user toggled it or restarted the app.+ *+ * Refresh once and reconnect. {@link authRecoveryAttempted} keeps a refresh+ * that yields another rejected token (revoked grant, clock skew) from looping.+ */+ private async handleAuthFailed(reason: string) {+ if (this.authRecoveryAttempted) {+ logger.error(+ `Authentication failed again after a token refresh (${reason}); staying disconnected until the next connect`,+ );+ this.setStatus('disconnected');+ return;+ }++ this.authRecoveryAttempted = true;+ logger.warn(`Authentication failed: ${reason}. Attempting token refresh before reconnect...`);+ await this.refreshTokenAndReconnect();+ }+// βββ System Info βββ/**