🤯 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
✨ feat(gateway): discover device gateway addresses for desktop and CLI (#20741)
Bryan79064c53a50f
diff --git a/apps/cli/src/api/client.ts b/apps/cli/src/api/client.tsindex f2b24ae9914..a1ccfae06f9 100644--- a/apps/cli/src/api/client.ts+++ b/apps/cli/src/api/client.ts@@ -90,13 +90,17 @@ export async function getTrpcClient(workspaceId?: string): Promise<TrpcClient> {return client;}-/** Create an anonymous client for public Lambda procedures, without credential discovery. */-export function createPublicLambdaClient(): TrpcClient {+/**+ * Create an anonymous client for public Lambda procedures, without credential+ * discovery. Pass `serverUrl` to stay on the server an already-resolved+ * credential belongs to.+ */+export function createPublicLambdaClient(serverUrl: string = resolveServerUrl()): TrpcClient {return createTRPCClient<LambdaRouter>({links: [httpLink({transformer: superjson,- url: `${resolveServerUrl()}/trpc/lambda`,+ url: `${serverUrl}/trpc/lambda`,}),],});diff --git a/apps/cli/src/commands/connect.integration.test.ts b/apps/cli/src/commands/connect.integration.test.tsindex 53d99f94935..e08b9b0ec18 100644--- a/apps/cli/src/commands/connect.integration.test.ts+++ b/apps/cli/src/commands/connect.integration.test.ts@@ -6,6 +6,7 @@ import os from 'node:os';import path from 'node:path';import { afterEach, describe, expect, it } from 'vitest';+import { WebSocketServer } from 'ws';interface CliResult {exitCode: number;@@ -15,6 +16,24 @@ interface CliResult {const tempHomes: string[] = [];const servers: Server[] = [];+const daemonHomes: string[] = [];++/** `config.getGlobalConfig` as the tRPC lambda router answers it. */+const globalConfigBody = (serverConfig: Record<string, unknown>) =>+ JSON.stringify({ result: { data: { json: { serverConfig } } } });++const unsignedJwt = (sub: string) =>+ [+ Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url'),+ Buffer.from(JSON.stringify({ sub })).toString('base64url'),+ 'signature',+ ].join('.');++const listen = async (server: Server) => {+ servers.push(server);+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ return (server.address() as AddressInfo).port;+};async function runCli(args: string[],@@ -54,6 +73,8 @@ async function runCli(}afterEach(async () => {+ // Never leave a daemon behind, even when an assertion failed.+ await Promise.all(daemonHomes.splice(0).map((home) => runCli(['connect', 'stop'], home)));await new Promise((resolve) => setTimeout(resolve, 100));await Promise.all(servers.splice(0).map(@@ -110,6 +131,11 @@ describe('connect daemon startup', () => {requests.push(request.url ?? '');response.setHeader('Content-Type', 'application/json');+ if (request.url?.includes('config.getGlobalConfig')) {+ response.end(globalConfigBody({ deviceGatewayUrl: 'http://127.0.0.1:9/gateway' }));+ return;+ }+if (request.url?.includes('device.mintWorkspaceConnectToken')) {response.end(JSON.stringify({@@ -163,4 +189,131 @@ describe('connect daemon startup', () => {expect(result.stdout).not.toContain('Daemon started');expect(result.stderr).toContain('workspace registration rejected');});++ it('fails fast when a self-hosted server advertises no gateway and none is saved', async () => {+ const port = await listen(+ createServer((request, response) => {+ response.setHeader('Content-Type', 'application/json');+ response.end(+ request.url?.includes('config.getGlobalConfig')+ ? globalConfigBody({})+ : JSON.stringify({ result: { data: { json: null } } }),+ );+ }),+ );+ const home = await mkdtemp(path.join(os.tmpdir(), 'lobehub-cli-daemon-startup-'));+ tempHomes.push(home);++ const result = await runCli(['connect', '--daemon'], home, {+ LOBEHUB_JWT: unsignedJwt('test-user'),+ LOBEHUB_SERVER: `http://127.0.0.1:${port}`,+ });++ expect(result.exitCode).toBe(1);+ expect(result.stdout).not.toContain('Daemon started');+ expect(result.stderr).toContain('does not advertise a device gateway');+ });++ it('connects the daemon to the advertised gateway, path prefix included', async () => {+ const gatewayServer = createServer();+ const sockets = new WebSocketServer({ server: gatewayServer });+ const handshakes: { auth: any; path: string }[] = [];+ sockets.on('connection', (socket, request) => {+ socket.once('message', (data) => {+ handshakes.push({ auth: JSON.parse(String(data)), path: request.url ?? '' });+ socket.send(JSON.stringify({ type: 'auth_success' }));+ });+ });+ const gatewayPort = await listen(gatewayServer);++ const serverPort = await listen(+ createServer((request, response) => {+ response.setHeader('Content-Type', 'application/json');+ response.end(+ request.url?.includes('config.getGlobalConfig')+ ? globalConfigBody({ deviceGatewayUrl: `http://127.0.0.1:${gatewayPort}/edge/gw` })+ : JSON.stringify({ result: { data: { json: null } } }),+ );+ }),+ );+ const serverUrl = `http://127.0.0.1:${serverPort}`;+ const home = await mkdtemp(path.join(os.tmpdir(), 'lobehub-cli-daemon-startup-'));+ tempHomes.push(home);+ daemonHomes.push(home);+ const token = unsignedJwt('test-user');++ const result = await runCli(['connect', '--daemon'], home, {+ LOBEHUB_JWT: token,+ LOBEHUB_SERVER: serverUrl,+ });+ expect(result.stdout).toContain('Daemon started');++ for (let waited = 0; handshakes.length === 0 && waited < 5000; waited += 100) {+ await new Promise((resolve) => setTimeout(resolve, 100));+ }++ // This login's token reached the gateway its own server advertised.+ expect(handshakes[0]?.path).toMatch(/^\/edge\/gw\/ws\?/);+ expect(handshakes[0]?.auth).toMatchObject({ serverUrl, token, type: 'auth' });++ const status = await runCli(['connect', 'status'], home);+ expect(status.stdout).toContain(`http://127.0.0.1:${gatewayPort}/edge/gw (server)`);+ sockets.close();+ }, 20_000);++ it('remembers --gateway for that server and reuses it ahead of the advertised one', async () => {+ const gatewayServer = createServer();+ const sockets = new WebSocketServer({ server: gatewayServer });+ const paths: string[] = [];+ sockets.on('connection', (socket, request) => {+ socket.once('message', () => {+ paths.push(request.url ?? '');+ socket.send(JSON.stringify({ type: 'auth_success' }));+ });+ });+ const gatewayPort = await listen(gatewayServer);++ let configReads = 0;+ const serverPort = await listen(+ createServer((request, response) => {+ if (request.url?.includes('config.getGlobalConfig')) configReads += 1;+ response.setHeader('Content-Type', 'application/json');+ response.end(+ request.url?.includes('config.getGlobalConfig')+ ? globalConfigBody({ deviceGatewayUrl: `http://127.0.0.1:${gatewayPort}/advertised` })+ : JSON.stringify({ result: { data: { json: null } } }),+ );+ }),+ );+ const env = {+ LOBEHUB_JWT: unsignedJwt('test-user'),+ LOBEHUB_SERVER: `http://127.0.0.1:${serverPort}`,+ };+ const home = await mkdtemp(path.join(os.tmpdir(), 'lobehub-cli-daemon-startup-'));+ tempHomes.push(home);+ daemonHomes.push(home);++ const waitForHandshakes = async (count: number) => {+ for (let waited = 0; paths.length < count && waited < 5000; waited += 100) {+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ };++ const pinned = `http://127.0.0.1:${gatewayPort}/pinned`;+ const first = await runCli(['connect', '--daemon', '--gateway', pinned], home, env);+ expect(first.stdout).toContain('Daemon started');+ await waitForHandshakes(1);+ await runCli(['connect', 'stop'], home);++ // No --gateway: the saved address wins and the server is not asked.+ const second = await runCli(['connect', '--daemon'], home, env);+ expect(second.stdout).toContain('Daemon started');+ await waitForHandshakes(2);++ expect(paths.map((url) => url.split('?')[0])).toEqual(['/pinned/ws', '/pinned/ws']);+ expect(configReads).toBe(0);+ const status = await runCli(['connect', 'status'], home);+ expect(status.stdout).toContain(`${pinned} (manual)`);+ sockets.close();+ }, 30_000);});diff --git a/apps/cli/src/commands/connect.nativeRuntimes.test.ts b/apps/cli/src/commands/connect.nativeRuntimes.test.tsindex 2153fea3c87..aafc1faf1f7 100644--- a/apps/cli/src/commands/connect.nativeRuntimes.test.ts+++ b/apps/cli/src/commands/connect.nativeRuntimes.test.ts@@ -1,8 +1,10 @@import type * as DeviceControlModule from '@lobechat/device-control';+import type * as DeviceGatewayModule from '@lobechat/device-gateway-client';import { GatewayClient } from '@lobechat/device-gateway-client';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type * as ApiClientModule from '../api/client';import type * as RefreshModule from '../auth/refresh';import { resolveToken } from '../auth/resolveToken';import type * as DeviceRegister from '../device/register';@@ -59,15 +61,24 @@ vi.mock('../auth/resolveToken', () => ({vi.mock('../settings', () => ({addWorkspaceEnrollment: vi.fn(),loadOrCreateConnectionId: vi.fn().mockReturnValue('test-connection-id'),+ loadDeviceGatewayUrl: vi.fn().mockReturnValue(undefined),loadSettings: vi.fn().mockReturnValue(null),// Default: no persisted workspace shares, so runConnect skips the restore path.loadWorkspaceEnrollments: vi.fn().mockReturnValue([]),normalizeUrl: vi.fn((url?: string) => (url ? url.replace(/\/$/, '') : undefined)),removeWorkspaceEnrollment: vi.fn(),resolveDeviceMetricsBacklogPath: vi.fn((id: string) => `/tmp/device-metrics/${id}.json`),+ saveDeviceGatewayUrl: vi.fn(),saveSettings: vi.fn(),}));+vi.mock('../api/client', async (importOriginal) => ({+ ...(await importOriginal<typeof ApiClientModule>()),+ createPublicLambdaClient: vi.fn(() => ({+ config: { getGlobalConfig: { query: vi.fn().mockResolvedValue({ serverConfig: {} }) } },+ })),+}));+vi.mock('../tools/shell', () => ({cleanupAllProcesses: vi.fn(),}));@@ -122,7 +133,8 @@ vi.mock('@lobechat/device-control', async (importOriginal) => ({}),}));-vi.mock('@lobechat/device-gateway-client', () => ({+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ ...(await importOriginal<typeof DeviceGatewayModule>()),GatewayClient: vi.fn().mockImplementation(function () {clientEventHandlers = {};lastSentSystemInfoResponse = null;diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.tsindex 88d838c1361..a2e082b3218 100644--- a/apps/cli/src/commands/connect.test.ts+++ b/apps/cli/src/commands/connect.test.ts@@ -3,16 +3,18 @@ import os from 'node:os';import path from 'node:path';import type * as DeviceControlModule from '@lobechat/device-control';+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';import { GatewayClient } from '@lobechat/device-gateway-client';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type * as ApiClientModule from '../api/client';import type * as RefreshModule from '../auth/refresh';import { resolveToken } from '../auth/resolveToken';import { removeStatus, spawnDaemon, stopDaemon, writeStatus } from '../daemon/manager';import type * as DeviceRegister from '../device/register';import type * as SystemInfoModule from '../device/systemInfo';-import { loadSettings, saveSettings } from '../settings';+import { loadDeviceGatewayUrl, saveDeviceGatewayUrl } from '../settings';import { executeToolCall } from '../tools';import { cleanupAllProcesses } from '../tools/shell';import { log, setVerbose } from '../utils/logger';@@ -55,6 +57,7 @@ vi.mock('../auth/resolveToken', () => ({}));vi.mock('../settings', () => ({addWorkspaceEnrollment: vi.fn(),+ loadDeviceGatewayUrl: vi.fn(),loadOrCreateConnectionId: vi.fn().mockReturnValue('test-connection-id'),loadSettings: vi.fn().mockReturnValue(null),// Default: no persisted workspace shares, so runConnect skips the restore path.@@ -62,9 +65,28 @@ vi.mock('../settings', () => ({normalizeUrl: vi.fn((url?: string) => (url ? url.replace(/\/$/, '') : undefined)),removeWorkspaceEnrollment: vi.fn(),resolveDeviceMetricsBacklogPath: vi.fn((id: string) => `/tmp/device-metrics/${id}.json`),+ saveDeviceGatewayUrl: vi.fn(),saveSettings: vi.fn(),}));+// `config.getGlobalConfig` on the server the token belongs to.+const getGlobalConfig = vi.hoisted(() => vi.fn());+const createPublicLambdaClientMock = vi.hoisted(() =>+ vi.fn(() => ({ config: { getGlobalConfig: { query: getGlobalConfig } } })),+);+vi.mock('../api/client', async (importOriginal) => ({+ ...(await importOriginal<typeof ApiClientModule>()),+ createPublicLambdaClient: createPublicLambdaClientMock,+}));++const OFFICIAL_AUTH = {+ serverUrl: 'https://app.lobehub.com',+ token: 'test-token',+ tokenType: 'jwt' as const,+ userId: 'test-user',+};+const SELF_HOSTED = 'https://self-hosted.example.com';+vi.mock('../tools/shell', () => ({cleanupAllProcesses: vi.fn(),}));@@ -122,7 +144,9 @@ vi.mock('@lobechat/device-control', async (importOriginal) => ({}),}));-vi.mock('@lobechat/device-gateway-client', () => ({+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ // Address resolution is real; only the socket is faked.+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),GatewayClient: vi.fn().mockImplementation(function (opts: any) {clientOptions = opts;clientEventHandlers = {};@@ -140,6 +164,7 @@ vi.mock('@lobechat/device-gateway-client', () => ({}),reconnect: vi.fn().mockResolvedValue(undefined),reportMetrics: clientReportMetrics,+ sendRpcResponse: vi.fn(),sendSystemInfoResponse: vi.fn().mockImplementation((data: any) => {lastSentSystemInfoResponse = data;}),@@ -166,6 +191,10 @@ describe('connect command', () => {mockRunningPid = null;mockSpawnedPid = 0;mockStatus = null;+ clientOptions = {};+ vi.mocked(resolveToken).mockResolvedValue(OFFICIAL_AUTH);+ vi.mocked(loadDeviceGatewayUrl).mockReturnValue(undefined);+ getGlobalConfig.mockResolvedValue({ serverConfig: {} });});afterEach(() => {@@ -265,17 +294,6 @@ describe('connect command', () => {expect(log.info).toHaveBeenCalledWith(expect.stringContaining('LobeHub CLI'));});- it('should require explicit gateway for custom login server', async () => {- vi.mocked(loadSettings).mockReturnValueOnce({ serverUrl: 'https://self-hosted.example.com' });-- const program = createProgram();- await expect(program.parseAsync(['node', 'test', 'connect'])).rejects.toThrow('process.exit');- expect(log.error).toHaveBeenCalledWith(- "Current login uses custom --server https://self-hosted.example.com. Please also provide '--gateway <url>' for the device gateway.",- );- expect(exitSpy).toHaveBeenCalledWith(1);- });-it('exits with a retryable code when the workspace token mint fails transiently', async () => {mintWorkspaceConnectTokenMock.mockRejectedValueOnce(new Error('fetch failed'));@@ -328,22 +346,128 @@ describe('connect command', () => {expect(connectCalled).toBe(false);});- it('should use explicit gateway for custom login server', async () => {- vi.mocked(loadSettings).mockReturnValueOnce({ serverUrl: 'https://self-hosted.example.com' });+ describe('device gateway address', () => {+ const connect = (...args: string[]) =>+ createProgram().parseAsync(['node', 'test', 'connect', ...args]);- const program = createProgram();- await program.parseAsync([- 'node',- 'test',- 'connect',- '--gateway',- 'https://gateway.example.com/',- ]);-- expect(clientOptions.gatewayUrl).toBe('https://gateway.example.com');- expect(saveSettings).toHaveBeenCalledWith({- gatewayUrl: 'https://gateway.example.com',- serverUrl: 'https://self-hosted.example.com',+ it("connects to the gateway the token's server advertises when none is saved", async () => {+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl: SELF_HOSTED });+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.example.com/edge/' },+ });++ await connect();++ expect(createPublicLambdaClientMock).toHaveBeenCalledWith(SELF_HOSTED);+ expect(clientOptions).toMatchObject({+ gatewayUrl: 'https://gw.example.com/edge',+ serverUrl: SELF_HOSTED,+ token: 'test-token',+ });+ expect(writeStatus).toHaveBeenCalledWith(+ expect.objectContaining({+ gatewaySource: 'server',+ gatewayUrl: 'https://gw.example.com/edge',+ }),+ );+ expect(log.info).toHaveBeenCalledWith(+ ' Gateway : https://gw.example.com/edge (advertised by the server)',+ );+ });++ it.each([OFFICIAL_AUTH.serverUrl, SELF_HOSTED])(+ 'uses the address saved for the token’s server ahead of its advertisement (%s)',+ async (serverUrl) => {+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl });+ vi.mocked(loadDeviceGatewayUrl).mockImplementation((server) =>+ server === serverUrl ? 'https://gw.saved.example' : undefined,+ );+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.example.com' },+ });++ await connect();++ // Saved, so the server is not even asked: a down server cannot block it.+ expect(getGlobalConfig).not.toHaveBeenCalled();+ expect(clientOptions.gatewayUrl).toBe('https://gw.saved.example');+ expect(log.info).toHaveBeenCalledWith(+ ' Gateway : https://gw.saved.example (saved for this server)',+ );+ expect(saveDeviceGatewayUrl).not.toHaveBeenCalled();+ },+ );++ it('keeps the official gateway for official cloud when nothing is advertised or saved', async () => {+ await connect();++ expect(clientOptions.gatewayUrl).toBe('https://device-gateway.lobehub.com');+ });++ it('refuses to start without a gateway for a self-hosted server that advertises none', async () => {+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl: SELF_HOSTED });++ await expect(connect()).rejects.toThrow(+ `${SELF_HOSTED} does not advertise a device gateway, and none is saved for it.`,+ );+ expect(clientOptions).toEqual({});+ });++ it.each([OFFICIAL_AUTH.serverUrl, SELF_HOSTED])(+ 'does not fall back when the config lookup fails (%s)',+ async (serverUrl) => {+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl });+ getGlobalConfig.mockRejectedValue(new Error('HTTP 502'));++ await expect(connect()).rejects.toThrow('Could not read the device gateway address');+ expect(clientOptions).toEqual({});+ },+ );++ it('uses --gateway without a lookup and saves it for that server', async () => {+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl: SELF_HOSTED });+ vi.mocked(loadDeviceGatewayUrl).mockReturnValue('https://gw.saved.example');+ getGlobalConfig.mockRejectedValue(new Error('server down'));++ await connect('--gateway', 'https://gateway.example.com/');++ expect(getGlobalConfig).not.toHaveBeenCalled();+ expect(clientOptions.gatewayUrl).toBe('https://gateway.example.com');+ expect(saveDeviceGatewayUrl).toHaveBeenCalledWith(SELF_HOSTED, 'https://gateway.example.com');+ });++ it('opens workspace shares on the same gateway as the personal connection', async () => {+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl: SELF_HOSTED });+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.example.com' },+ });+ await connect();+ const personal = clientOptions;++ await clientEventHandlers['rpc_request']?.({+ method: 'enrollWorkspace',+ params: { token: 'ws-token', workspaceId: 'ws-1' },+ requestId: 'rpc-1',+ type: 'rpc_request',+ });++ expect(clientOptions).not.toBe(personal);+ expect(clientOptions).toMatchObject({+ gatewayUrl: 'https://gw.example.com',+ serverUrl: SELF_HOSTED,+ token: 'ws-token',+ workspaceId: 'ws-1',+ });+ });++ it('passes --gateway through to the daemon child, which resolves the same way', async () => {+ await connect('--daemon', '--gateway', 'https://gateway.example.com');++ expect(spawnDaemon).toHaveBeenCalledWith(+ expect.arrayContaining(['connect', '--gateway', 'https://gateway.example.com']),+ );+ // The parent resolves nothing itself; the child runs `runConnect`.+ expect(getGlobalConfig).not.toHaveBeenCalled();});});it('should pass the resolved serverUrl to GatewayClient', async () => {@@ -509,6 +633,9 @@ describe('connect command', () => {tokenType: 'apiKey',userId: 'user',});+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.self-hosted.example.com' },+ });const program = createProgram();await program.parseAsync(['node', 'test', 'connect']);diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex 10a7300c217..69086e6a699 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -31,7 +31,6 @@ import { scheduleProactiveRefresh } from '../auth/proactiveRefresh';import { resolveToken } from '../auth/resolveToken';import { CLI_API_KEY_ENV } from '../constants/auth';import { CLI_CONNECT_SERVICE_NAME, CLI_DISPLAY_NAME, CLI_PRIMARY_BIN } from '../constants/identity';-import { OFFICIAL_GATEWAY_URL } from '../constants/urls';import { CliMaintenance } from '../daemon/maintenance';import {appendLog,@@ -48,6 +47,12 @@ import {} from '../daemon/manager';import { listTasks } from '../daemon/taskRegistry';import { spawnHeteroAgentRun } from '../device/agentRun';+import {+ describeDeviceGateway,+ describeDeviceGatewayFailure,+ rememberGatewayOverride,+ resolveCliDeviceGateway,+} from '../device/gatewayEndpoint';import {mintWorkspaceConnectToken,registerDevice,@@ -70,12 +75,9 @@ import {import {addWorkspaceEnrollment,loadOrCreateConnectionId,- loadSettings,loadWorkspaceEnrollments,- normalizeUrl,removeWorkspaceEnrollment,resolveDeviceMetricsBacklogPath,- saveSettings,} from '../settings';import { executeToolCall } from '../tools';import { executeComputerUseCall, resolveComputerUseDevice } from '../tools/computerUse';@@ -163,7 +165,7 @@ export function registerConnectCommand(program: Command) {if (status) {log.info(` Started at : ${status.startedAt}`);log.info(` Connection : ${status.connectionStatus}`);- log.info(` Gateway : ${status.gatewayUrl}`);+ log.info(` Gateway : ${formatStatusGateway(status)}`);const uptime = formatUptime(new Date(status.startedAt));log.info(` Uptime : ${uptime}`);}@@ -292,7 +294,7 @@ export function registerConnectCommand(program: Command) {}if (status) {log.info(` Connection : ${status.connectionStatus}`);- log.info(` Gateway : ${status.gatewayUrl}`);+ log.info(` Gateway : ${formatStatusGateway(status)}`);const uptime = formatUptime(new Date(status.startedAt));log.info(` Uptime : ${uptime}`);}@@ -356,22 +358,35 @@ function buildDaemonArgs(options: ConnectOptions): string[] {async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {const unavailableExitCode = options.workspace ? CONNECT_RETRYABLE_EXIT_CODE : undefined;let auth = await resolveToken({ ...options, unavailableExitCode });- const settings = loadSettings();- const gatewayUrl = normalizeUrl(options.gateway) || settings?.gatewayUrl;- if (!gatewayUrl && settings?.serverUrl) {- log.error(- `Current login uses custom --server ${settings?.serverUrl}. Please also provide '--gateway <url>' for the device gateway.`,- );- process.exit(1);- throw new Error('process.exit');- }+ const info = (msg: string) => {+ if (isDaemonChild) appendLog(msg);+ else log.info(msg);+ };- if (options.gateway && gatewayUrl) {- saveSettings({ ...settings, gatewayUrl });- }+ const error = (msg: string) => {+ if (isDaemonChild) appendLog(`[ERROR] ${msg}`);+ else log.error(msg);+ };- const resolvedGatewayUrl = gatewayUrl || OFFICIAL_GATEWAY_URL;+ // Resolved once per process, against the server the token belongs to. The+ // client's own reconnects and every workspace share connection reuse it.+ const gateway = await resolveCliDeviceGateway({+ override: options.gateway,+ serverUrl: auth.serverUrl,+ });+ if (!gateway.ok) {+ const { detail, fix } = describeDeviceGatewayFailure(gateway, auth.serverUrl);+ // Thrown, so a daemon parent reports it as the startup error too.+ throw new Error(`${detail} ${fix}`);+ }+ const resolvedGatewayUrl = gateway.endpoint.url;+ const gatewayDescription = describeDeviceGateway(gateway.endpoint);+ if (rememberGatewayOverride(auth.serverUrl, gateway.endpoint)) {+ info(+ `Saved ${resolvedGatewayUrl} as the device gateway for ${auth.serverUrl}; later runs use it ahead of the server's own address.`,+ );+ }// Fail before connecting rather than advertise a tool this device cannot run.const computerUse = await resolveComputerUseDevice(options.auv).catch((err: Error) => {@@ -441,22 +456,12 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {workspaceId,});- const info = (msg: string) => {- if (isDaemonChild) appendLog(msg);- else log.info(msg);- };-- const error = (msg: string) => {- if (isDaemonChild) appendLog(`[ERROR] ${msg}`);- else log.error(msg);- };-// Print device infoinfo(`─── ${CLI_DISPLAY_NAME} ───`);info(` Device ID : ${client.currentDeviceId}`);info(` Hostname : ${os.hostname()}`);info(` Platform : ${process.platform}`);- info(` Gateway : ${resolvedGatewayUrl}`);+ info(` Gateway : ${gatewayDescription}`);info(` Auth : ${auth.tokenType}`);info(` Mode : ${isDaemonChild ? 'daemon' : 'foreground'}`);info('───────────────────');@@ -469,6 +474,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {writeStatus({connectionStatus,deviceId: client.currentDeviceId,+ gatewaySource: gateway.endpoint.source,gatewayUrl: resolvedGatewayUrl,lastRequestAt,pid: process.pid,@@ -1129,6 +1135,12 @@ function createDaemonLogger() {};}+function formatStatusGateway(status: { gatewaySource?: string; gatewayUrl: string }): string {+ return status.gatewaySource+ ? `${status.gatewayUrl} (${status.gatewaySource})`+ : status.gatewayUrl;+}+function formatUptime(startedAt: Date): string {const diff = Date.now() - startedAt.getTime();const seconds = Math.floor(diff / 1000);diff --git a/apps/cli/src/commands/login.test.ts b/apps/cli/src/commands/login.test.tsindex c20047b2fa4..e48f5840958 100644--- a/apps/cli/src/commands/login.test.ts+++ b/apps/cli/src/commands/login.test.ts@@ -248,7 +248,7 @@ describe('login command', () => {});});- it('should clear existing gateway when logging into a different server', async () => {+ it("keeps the old server's gateway with it when logging into a different server", async () => {vi.mocked(loadSettings).mockReturnValueOnce({gatewayUrl: 'https://gateway.example.com',serverUrl: 'https://old.example.com',@@ -260,7 +260,26 @@ describe('login command', () => {const program = createProgram();await runLoginAndAdvanceTimers(program, ['--server', 'https://new.example.com/']);- expect(saveSettings).toHaveBeenCalledWith({ serverUrl: 'https://new.example.com' });+ // Bound to the old server, so the new login never connects to it.+ expect(saveSettings).toHaveBeenCalledWith({+ deviceGatewayUrls: { 'https://old.example.com': 'https://gateway.example.com' },+ serverUrl: 'https://new.example.com',+ });+ });++ it('keeps a gateway saved with official cloud for official cloud when logging in elsewhere', async () => {+ vi.mocked(loadSettings).mockReturnValueOnce({ gatewayUrl: 'http://localhost:8788' });+ vi.mocked(fetch)+ .mockResolvedValueOnce(deviceAuthResponse())+ .mockResolvedValueOnce(tokenSuccessResponse());++ const program = createProgram();+ await runLoginAndAdvanceTimers(program, ['--server', 'https://new.example.com/']);++ expect(saveSettings).toHaveBeenCalledWith({+ deviceGatewayUrls: { 'https://app.lobehub.com': 'http://localhost:8788' },+ serverUrl: 'https://new.example.com',+ });});it('should strip trailing slash from server URL', async () => {diff --git a/apps/cli/src/commands/login.ts b/apps/cli/src/commands/login.tsindex 2d1b94a7c60..4b4cf610a79 100644--- a/apps/cli/src/commands/login.ts+++ b/apps/cli/src/commands/login.ts@@ -11,7 +11,7 @@ import { readCliApiKeyEnv } from '../constants/auth';import { CLI_PRODUCT_NAME } from '../constants/identity';import { OFFICIAL_SERVER_URL } from '../constants/urls';import { registerDevice, resolveDeviceIdentity } from '../device/register';-import { loadSettings, normalizeUrl, saveSettings } from '../settings';+import { loadSettings, normalizeUrl, saveSettings, settingsForLogin } from '../settings';import { log } from '../utils/logger';const CLIENT_ID = 'lobehub-cli';@@ -70,22 +70,8 @@ export function registerLoginCommand(program: Command) {try {await getUserIdFromApiKey(apiKey, serverUrl);- const existingSettings = loadSettings();- const existingServerUrl = existingSettings?.serverUrl || OFFICIAL_SERVER_URL;- const shouldPreserveGateway = !!existingSettings && existingServerUrl === serverUrl;-- saveSettings(- shouldPreserveGateway- ? {- gatewayUrl: existingSettings.gatewayUrl,- serverUrl,- }- : {- // Gateway auth is tied to the login server's token issuer/JWKS.- // When server changes, clear old gateway to avoid stale cross-environment config.- serverUrl,- },- );+ // Device gateway addresses stay bound to the server they were saved for.+ saveSettings(settingsForLogin(loadSettings(), serverUrl));log.info('Login successful! Credentials saved.');return;} catch (error) {@@ -203,22 +189,8 @@ export function registerLoginCommand(program: Command) {refreshToken: body.refresh_token,});- const existingSettings = loadSettings();- const existingServerUrl = existingSettings?.serverUrl || OFFICIAL_SERVER_URL;- const shouldPreserveGateway = !!existingSettings && existingServerUrl === serverUrl;-- saveSettings(- shouldPreserveGateway- ? {- gatewayUrl: existingSettings.gatewayUrl,- serverUrl,- }- : {- // Gateway auth is tied to the login server's token issuer/JWKS.- // When server changes, clear old gateway to avoid stale cross-environment config.- serverUrl,- },- );+ // Device gateway addresses stay bound to the server they were saved for.+ saveSettings(settingsForLogin(loadSettings(), serverUrl));// Register this device in the server registry right after auth, so// the device row exists without waiting for a later `lh connect`diff --git a/apps/cli/src/commands/status.test.ts b/apps/cli/src/commands/status.test.tsindex 53bd58b98b0..c91f2b80e0e 100644--- a/apps/cli/src/commands/status.test.ts+++ b/apps/cli/src/commands/status.test.ts@@ -1,23 +1,34 @@+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { loadSettings, saveSettings } from '../settings';+import { createPublicLambdaClient } from '../api/client';+import { resolveToken } from '../auth/resolveToken';+import { loadDeviceGatewayUrl, saveDeviceGatewayUrl } from '../settings';import { log } from '../utils/logger';import { registerStatusCommand } from './status';+const OFFICIAL_AUTH = {+ serverUrl: 'https://app.lobehub.com',+ token: 'test-token',+ tokenType: 'jwt' as const,+ userId: 'test-user',+};+const SELF_HOSTED = 'https://self-hosted.example.com';+// Mock resolveToken-vi.mock('../auth/resolveToken', () => ({- resolveToken: vi.fn().mockResolvedValue({- serverUrl: 'https://app.lobehub.com',- token: 'test-token',- tokenType: 'jwt',- userId: 'test-user',- }),-}));+vi.mock('../auth/resolveToken', () => ({ resolveToken: vi.fn() }));vi.mock('../settings', () => ({- loadSettings: vi.fn().mockReturnValue(null),- normalizeUrl: vi.fn((url?: string) => (url ? url.replace(/\/$/, '') : undefined)),- saveSettings: vi.fn(),+ loadDeviceGatewayUrl: vi.fn(),+ saveDeviceGatewayUrl: vi.fn(),+}));++// `config.getGlobalConfig` on the server the token belongs to.+const getGlobalConfig = vi.fn();+vi.mock('../api/client', () => ({+ createPublicLambdaClient: vi.fn(() => ({+ config: { getGlobalConfig: { query: getGlobalConfig } },+ })),}));// Track event handlers registered on GatewayClient instances@@ -25,7 +36,9 @@ let clientEventHandlers: Record<string, (...args: any[]) => any> = {};let connectCalled = false;let clientOptions: any = {};-vi.mock('@lobechat/device-gateway-client', () => ({+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ // The address resolution is real; only the socket is faked.+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),// A plain function, not an arrow: the command calls `new GatewayClient(...)`,// and an arrow implementation is not constructible.GatewayClient: vi.fn().mockImplementation(function (opts: any) {@@ -50,6 +63,10 @@ describe('status command', () => {beforeEach(() => {vi.useFakeTimers();exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);+ clientOptions = {};+ vi.mocked(resolveToken).mockResolvedValue(OFFICIAL_AUTH);+ vi.mocked(loadDeviceGatewayUrl).mockReturnValue(undefined);+ getGlobalConfig.mockResolvedValue({ serverConfig: {} });});afterEach(() => {@@ -77,38 +94,104 @@ describe('status command', () => {expect(clientOptions.autoReconnect).toBe(false);});- it('should require explicit gateway for custom login server', async () => {- vi.mocked(loadSettings).mockReturnValueOnce({ serverUrl: 'https://self-hosted.example.com' });+ /** Run `lh status [...args]` until the probe connects. */+ const runConnected = async (...args: string[]) => {+ const parsePromise = createProgram().parseAsync(['node', 'test', 'status', ...args]);+ await vi.advanceTimersByTimeAsync(0);+ clientEventHandlers['connected']?.();+ await parsePromise;+ };++ it("probes the gateway advertised by the token's server when none is saved", async () => {+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl: SELF_HOSTED });+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.example.com/edge/' },+ });+ // Another server's saved address is never borrowed.+ vi.mocked(loadDeviceGatewayUrl).mockImplementation((server) =>+ server === SELF_HOSTED ? undefined : 'http://localhost:8788',+ );++ await runConnected();++ // The server the token belongs to — never LOBEHUB_SERVER / settings on their own.+ expect(createPublicLambdaClient).toHaveBeenCalledWith(SELF_HOSTED);+ expect(clientOptions.gatewayUrl).toBe('https://gw.example.com/edge');+ expect(clientOptions.serverUrl).toBe(SELF_HOSTED);+ expect(log.info).toHaveBeenCalledWith(+ 'Gateway: https://gw.example.com/edge (advertised by the server)',+ );+ });++ it('keeps the official gateway for official cloud when nothing is advertised or saved', async () => {+ await runConnected();++ expect(clientOptions.gatewayUrl).toBe('https://device-gateway.lobehub.com');+ });++ it.each([OFFICIAL_AUTH.serverUrl, SELF_HOSTED])(+ 'probes the address saved for the token’s server ahead of its advertisement (%s)',+ async (serverUrl) => {+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl });+ vi.mocked(loadDeviceGatewayUrl).mockImplementation((server) =>+ server === serverUrl ? 'https://gw.saved.example' : undefined,+ );+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.example.com' },+ });++ await runConnected();++ expect(getGlobalConfig).not.toHaveBeenCalled();+ expect(clientOptions.gatewayUrl).toBe('https://gw.saved.example');+ expect(log.info).toHaveBeenCalledWith(+ 'Gateway: https://gw.saved.example (saved for this server)',+ );+ },+ );++ it('asks for a gateway when a self-hosted server advertises none and none is saved', async () => {+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl: SELF_HOSTED });++ await expect(createProgram().parseAsync(['node', 'test', 'status'])).rejects.toThrow(+ 'process.exit',+ );- const program = createProgram();- await expect(program.parseAsync(['node', 'test', 'status'])).rejects.toThrow('process.exit');expect(log.error).toHaveBeenCalledWith(- "Current login uses custom --server https://self-hosted.example.com. Please also provide '--gateway <url>' for the device gateway.",+ `FAILED - ${SELF_HOSTED} does not advertise a device gateway, and none is saved for it.`,);+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('--gateway <url>'));+ expect(clientOptions).toEqual({});expect(exitSpy).toHaveBeenCalledWith(1);});- it('should use explicit gateway for custom login server', async () => {- vi.mocked(loadSettings).mockReturnValueOnce({ serverUrl: 'https://self-hosted.example.com' });+ it.each([true, false])(+ 'does not fall back when the config lookup fails (official: %s)',+ async (official) => {+ if (!official)+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl: SELF_HOSTED });+ getGlobalConfig.mockRejectedValue(new Error('Unexpected token < in JSON'));- const program = createProgram();- const parsePromise = program.parseAsync([- 'node',- 'test',- 'status',- '--gateway',- 'https://gateway.example.com/',- ]);- await vi.advanceTimersByTimeAsync(0);+ await expect(createProgram().parseAsync(['node', 'test', 'status'])).rejects.toThrow(+ 'process.exit',+ );- clientEventHandlers['connected']?.();+ expect(log.error).toHaveBeenCalledWith(+ expect.stringContaining('Could not read the device gateway address'),+ );+ expect(clientOptions).toEqual({});+ },+ );- await parsePromise;+ it('uses --gateway without a lookup and saves it for that server', async () => {+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl: SELF_HOSTED });+ getGlobalConfig.mockRejectedValue(new Error('server down'));++ await runConnected('--gateway', 'https://gateway.example.com/');++ expect(getGlobalConfig).not.toHaveBeenCalled();expect(clientOptions.gatewayUrl).toBe('https://gateway.example.com');- expect(saveSettings).toHaveBeenCalledWith({- gatewayUrl: 'https://gateway.example.com',- serverUrl: 'https://self-hosted.example.com',- });+ expect(saveDeviceGatewayUrl).toHaveBeenCalledWith(SELF_HOSTED, 'https://gateway.example.com');});it('should pass the resolved serverUrl to GatewayClient', async () => {const program = createProgram();diff --git a/apps/cli/src/commands/status.ts b/apps/cli/src/commands/status.tsindex ae6b5022b10..a8b6aa2f292 100644--- a/apps/cli/src/commands/status.ts+++ b/apps/cli/src/commands/status.ts@@ -3,8 +3,12 @@ import type { Command } from 'commander';import { resolveToken } from '../auth/resolveToken';import { CLI_PRIMARY_BIN } from '../constants/identity';-import { OFFICIAL_GATEWAY_URL } from '../constants/urls';-import { loadSettings, normalizeUrl, saveSettings } from '../settings';+import {+ describeDeviceGateway,+ describeDeviceGatewayFailure,+ rememberGatewayOverride,+ resolveCliDeviceGateway,+} from '../device/gatewayEndpoint';import { log, setVerbose } from '../utils/logger';/**@@ -37,26 +41,28 @@ export function registerStatusCommand(program: Command) {if (options.verbose) setVerbose(true);const auth = await resolveToken(options);- const settings = loadSettings();- const gatewayUrl = normalizeUrl(options.gateway) || settings?.gatewayUrl;+ // Same resolution as `connect`, against the server this token belongs to.+ const gateway = await resolveCliDeviceGateway({+ override: options.gateway,+ serverUrl: auth.serverUrl,+ });- if (!gatewayUrl && settings?.serverUrl) {- log.error(- `Current login uses custom --server ${settings?.serverUrl}. Please also provide '--gateway <url>' for the device gateway.`,- );+ if (!gateway.ok) {+ const { detail, fix } = describeDeviceGatewayFailure(gateway, auth.serverUrl);+ log.error(`FAILED - ${detail}`);+ log.error(fix);process.exit(1);throw new Error('process.exit');}- if (options.gateway && gatewayUrl) {- saveSettings({ ...settings, gatewayUrl });- }+ rememberGatewayOverride(auth.serverUrl, gateway.endpoint);+ log.info(`Gateway: ${describeDeviceGateway(gateway.endpoint)}`);const timeout = Number.parseInt(options.timeout || '10000', 10);const client = new GatewayClient({autoReconnect: false,- gatewayUrl: gatewayUrl || OFFICIAL_GATEWAY_URL,+ gatewayUrl: gateway.endpoint.url,logger: log,serverUrl: auth.serverUrl,// Status is a one-shot probe, not a serving connection.diff --git a/apps/cli/src/daemon/manager.ts b/apps/cli/src/daemon/manager.tsindex 892e7b1e74e..9368e59d719 100644--- a/apps/cli/src/daemon/manager.ts+++ b/apps/cli/src/daemon/manager.ts@@ -30,6 +30,8 @@ function getLogFilePath() {export interface DaemonStatus {connectionStatus: string;deviceId?: string;+ /** Where `gatewayUrl` came from: `server`, `manual`, `official` or `override`. */+ gatewaySource?: string;gatewayUrl: string;lastRequestAt?: string;pid: number;diff --git a/apps/cli/src/device/gatewayEndpoint.serverResolution.test.ts b/apps/cli/src/device/gatewayEndpoint.serverResolution.test.tsnew file mode 100644index 00000000000..c45f464070b--- /dev/null+++ b/apps/cli/src/device/gatewayEndpoint.serverResolution.test.ts@@ -0,0 +1,147 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type * as RefreshModule from '../auth/refresh';+import { getValidToken } from '../auth/refresh';+import { resolveToken } from '../auth/resolveToken';+import { resolveCliDirName } from '../constants/identity';+import { resolveCliDeviceGateway } from './gatewayEndpoint';++/**+ * The whole chain a device command runs — credential → `auth.serverUrl` →+ * saved address → discovery → default — with the real settings file. Only the+ * network lookup and the stored-token store are stubbed, so a wrong default+ * shows up as a result here instead of as a socket to the official gateway.+ */++const tmpHome = path.join(os.tmpdir(), 'lobehub-cli-test-gateway-server');+const settingsFile = path.join(tmpHome, resolveCliDirName(), 'settings.json');++vi.mock('node:os', async (importOriginal) => {+ const actual = await importOriginal<Record<string, any>>();+ return {+ ...actual,+ default: {+ ...actual.default,+ homedir: () => path.join(actual.default.tmpdir(), 'lobehub-cli-test-gateway-server'),+ },+ };+});++const getGlobalConfig = vi.fn();+const lookedUp: string[] = [];+vi.mock('../api/client', () => ({+ createPublicLambdaClient: vi.fn((serverUrl: string) => {+ lookedUp.push(serverUrl);+ return { config: { getGlobalConfig: { query: getGlobalConfig } } };+ }),+}));++vi.mock('../auth/refresh', async (importOriginal) => ({+ ...(await importOriginal<typeof RefreshModule>()),+ getValidToken: vi.fn(),+}));++const unsignedJwt = (sub: string) =>+ [+ Buffer.from(JSON.stringify({ alg: 'none' })).toString('base64url'),+ Buffer.from(JSON.stringify({ sub })).toString('base64url'),+ 'signature',+ ].join('.');++const SELF_HOSTED = 'https://self.example.com';+const OFFICIAL_GATEWAY = 'https://device-gateway.lobehub.com';++const writeSettings = (settings: Record<string, unknown>) => {+ fs.mkdirSync(path.dirname(settingsFile), { recursive: true });+ fs.writeFileSync(settingsFile, JSON.stringify(settings));+};++const resolveFor = async () => {+ const auth = await resolveToken({});+ return { auth, gateway: await resolveCliDeviceGateway({ serverUrl: auth.serverUrl }) };+};++describe('device gateway for the server the credential is used against', () => {+ const originalServer = process.env.LOBEHUB_SERVER;+ const originalJwt = process.env.LOBEHUB_JWT;++ beforeEach(() => {+ fs.mkdirSync(tmpHome, { recursive: true });+ delete process.env.LOBEHUB_SERVER;+ delete process.env.LOBEHUB_JWT;+ lookedUp.length = 0;+ getGlobalConfig.mockReset();+ vi.mocked(getValidToken).mockResolvedValue({+ credentials: { accessToken: unsignedJwt('user-1') },+ status: 'ok',+ } as any);+ });++ afterEach(() => {+ fs.rmSync(tmpHome, { force: true, recursive: true });+ process.env.LOBEHUB_SERVER = originalServer;+ process.env.LOBEHUB_JWT = originalJwt;+ });++ it.each([+ ['the stored login', () => {}],+ [+ 'LOBEHUB_JWT',+ () => {+ process.env.LOBEHUB_JWT = unsignedJwt('user-1');+ },+ ],+ ])(+ 'treats a server set only through LOBEHUB_SERVER as self-hosted with %s',+ async (_label, useCredential) => {+ // The saved login is official cloud (no serverUrl), and the address it+ // saved belongs to official cloud.+ writeSettings({ gatewayUrl: 'http://127.0.0.1:8788' });+ process.env.LOBEHUB_SERVER = `${SELF_HOSTED}/`;+ useCredential();+ getGlobalConfig.mockResolvedValue({ serverConfig: {} });++ const { auth, gateway } = await resolveFor();++ expect(auth.serverUrl).toBe(SELF_HOSTED);+ expect(lookedUp).toEqual([SELF_HOSTED]);+ // Neither the official gateway nor official cloud's saved address.+ expect(gateway).toEqual({ ok: false, reason: 'not_configured' });+ },+ );++ it('uses what a LOBEHUB_SERVER-only self-hosted server advertises', async () => {+ writeSettings({ gatewayUrl: 'http://127.0.0.1:8788' });+ process.env.LOBEHUB_SERVER = SELF_HOSTED;+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.self.example.com/' },+ });++ await expect(resolveFor()).resolves.toMatchObject({+ gateway: { endpoint: { source: 'server', url: 'https://gw.self.example.com' }, ok: true },+ });+ });++ it('uses the address saved for that self-hosted server without asking it', async () => {+ writeSettings({ deviceGatewayUrls: { [SELF_HOSTED]: 'https://gw.saved.example.com' } });+ process.env.LOBEHUB_SERVER = SELF_HOSTED;++ await expect(resolveFor()).resolves.toMatchObject({+ gateway: { endpoint: { source: 'manual', url: 'https://gw.saved.example.com' }, ok: true },+ });+ expect(lookedUp).toEqual([]);+ });++ it('keeps the official default for official cloud when it advertises nothing', async () => {+ process.env.LOBEHUB_SERVER = 'https://app.lobehub.com/';+ getGlobalConfig.mockResolvedValue({ serverConfig: {} });++ await expect(resolveFor()).resolves.toMatchObject({+ gateway: { endpoint: { source: 'official', url: OFFICIAL_GATEWAY }, ok: true },+ });+ });+});diff --git a/apps/cli/src/device/gatewayEndpoint.test.ts b/apps/cli/src/device/gatewayEndpoint.test.tsnew file mode 100644index 00000000000..bed92c781a0--- /dev/null+++ b/apps/cli/src/device/gatewayEndpoint.test.ts@@ -0,0 +1,253 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createPublicLambdaClient } from '../api/client';+import { OFFICIAL_GATEWAY_URL } from '../constants/urls';+import { loadDeviceGatewayUrl, saveDeviceGatewayUrl } from '../settings';+import {+ describeDeviceGatewayFailure,+ discoverDeviceGateway,+ rememberGatewayOverride,+ resolveCliDeviceGateway,+} from './gatewayEndpoint';++const getGlobalConfig = vi.fn();+vi.mock('../api/client', () => ({+ createPublicLambdaClient: vi.fn(() => ({+ config: { getGlobalConfig: { query: getGlobalConfig } },+ })),+}));+vi.mock('../settings', () => ({+ loadDeviceGatewayUrl: vi.fn(),+ saveDeviceGatewayUrl: vi.fn(),+}));++const refused = () =>+ Object.assign(new Error('Unable to connect'), {+ cause: Object.assign(new Error('fetch failed'), { code: 'ConnectionRefused' }),+ });++describe('discoverDeviceGateway', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ getGlobalConfig.mockReset();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('asks the given server, anonymously', async () => {+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.example.com' },+ });++ await expect(discoverDeviceGateway('https://self.example.com')).resolves.toEqual({+ status: 'advertised',+ url: 'https://gw.example.com',+ });+ expect(createPublicLambdaClient).toHaveBeenCalledWith('https://self.example.com');+ });++ it('rides out a transient network failure on the same server', async () => {+ getGlobalConfig.mockRejectedValueOnce(refused()).mockResolvedValueOnce({ serverConfig: {} });++ const discovery = discoverDeviceGateway('https://self.example.com');+ await vi.runAllTimersAsync();++ await expect(discovery).resolves.toEqual({ status: 'absent' });+ expect(getGlobalConfig).toHaveBeenCalledTimes(2);+ });++ it('reports the cause once retries are exhausted', async () => {+ getGlobalConfig.mockRejectedValue(refused());++ const discovery = discoverDeviceGateway('https://self.example.com');+ await vi.runAllTimersAsync();++ await expect(discovery).resolves.toEqual({+ reason: expect.stringContaining('ConnectionRefused'),+ status: 'failed',+ });+ expect(getGlobalConfig).toHaveBeenCalledTimes(4);+ });++ it('bounds all attempts by one deadline, including a hanging retry', async () => {+ getGlobalConfig+ .mockImplementationOnce(+ () => new Promise((_, reject) => setTimeout(() => reject(refused()), 8000)),+ )+ .mockImplementationOnce(+ (_, { signal }: { signal: AbortSignal }) =>+ new Promise((_, reject) =>+ signal.addEventListener('abort', () => reject(signal.reason), { once: true }),+ ),+ );++ let result: Awaited<ReturnType<typeof discoverDeviceGateway>> | undefined;+ const discovery = discoverDeviceGateway('https://self.example.com').then((value) => {+ result = value;+ });+ await vi.advanceTimersByTimeAsync(10_000);++ expect(result).toMatchObject({+ status: 'failed',+ reason: expect.stringContaining('timed out'),+ });+ expect(getGlobalConfig).toHaveBeenCalledTimes(2);+ expect(vi.getTimerCount()).toBe(0);+ await discovery;+ });++ it('does not start a retry whose delay would exceed the deadline', async () => {+ getGlobalConfig.mockImplementation(+ () => new Promise((_, reject) => setTimeout(() => reject(refused()), 9900)),+ );++ let result: Awaited<ReturnType<typeof discoverDeviceGateway>> | undefined;+ const discovery = discoverDeviceGateway('https://self.example.com').then((value) => {+ result = value;+ });+ await vi.advanceTimersByTimeAsync(10_000);++ expect(result).toMatchObject({+ status: 'failed',+ reason: expect.stringContaining('ConnectionRefused'),+ });+ expect(getGlobalConfig).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ await discovery;+ });++ it('redacts HTTP credentials throughout the cause chain before displaying discovery errors', async () => {+ const serverUrl = 'https://test-user:[email protected]';+ getGlobalConfig.mockRejectedValue(+ new Error(`Request failed (${serverUrl}/trpc/lambda): invalid URL`, {+ cause: new Error('HTTPS://encoded%40user:encoded%[email protected] blocked'),+ }),+ );+ vi.mocked(loadDeviceGatewayUrl).mockReturnValue(undefined);++ const result = await resolveCliDeviceGateway({ serverUrl });+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error('Expected failed discovery');+ const output = JSON.stringify({+ result,+ display: describeDeviceGatewayFailure(result, serverUrl),+ });+ for (const secret of ['test-user', 'test-password', 'encoded%40user', 'encoded%3Apassword']) {+ expect(output).not.toContain(secret);+ }+ expect(output).toContain('self.example.com/trpc/lambda');+ expect(output).toContain('proxy.example.com');+ expect(output).toContain('invalid URL');+ });++ it('does not retry an error answer', async () => {+ getGlobalConfig.mockRejectedValue(new Error('INTERNAL_SERVER_ERROR'));++ await expect(discoverDeviceGateway('https://self.example.com')).resolves.toMatchObject({+ status: 'failed',+ });+ expect(getGlobalConfig).toHaveBeenCalledTimes(1);+ });+});++describe('resolveCliDeviceGateway', () => {+ beforeEach(() => {+ getGlobalConfig.mockReset();+ vi.mocked(loadDeviceGatewayUrl).mockReset();+ });++ it('uses --gateway ahead of the saved address, without asking the server', async () => {+ vi.mocked(loadDeviceGatewayUrl).mockReturnValue('https://gw.saved.example');++ await expect(+ resolveCliDeviceGateway({+ override: 'https://gw.flag.example/',+ serverUrl: 'https://self.example.com',+ }),+ ).resolves.toEqual({+ endpoint: { source: 'override', url: 'https://gw.flag.example' },+ ok: true,+ });+ expect(getGlobalConfig).not.toHaveBeenCalled();+ });++ it("uses the credential server's saved address ahead of its advertisement, without asking", async () => {+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.advertised.example' },+ });+ vi.mocked(loadDeviceGatewayUrl).mockReturnValue('https://gw.saved.example');++ await expect(+ resolveCliDeviceGateway({ serverUrl: 'https://self.example.com' }),+ ).resolves.toEqual({+ endpoint: { source: 'manual', url: 'https://gw.saved.example' },+ ok: true,+ });+ expect(loadDeviceGatewayUrl).toHaveBeenCalledWith('https://self.example.com');+ expect(getGlobalConfig).not.toHaveBeenCalled();+ });++ it('uses the advertised address when nothing is saved', async () => {+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.advertised.example/edge/' },+ });++ await expect(+ resolveCliDeviceGateway({ serverUrl: 'https://self.example.com' }),+ ).resolves.toEqual({+ endpoint: { source: 'server', url: 'https://gw.advertised.example/edge' },+ ok: true,+ });+ });++ it('keeps the official gateway as the default for official cloud only', async () => {+ getGlobalConfig.mockResolvedValue({ serverConfig: {} });++ await expect(+ resolveCliDeviceGateway({ serverUrl: 'https://app.lobehub.com' }),+ ).resolves.toEqual({ endpoint: { source: 'official', url: OFFICIAL_GATEWAY_URL }, ok: true });+ await expect(+ resolveCliDeviceGateway({ serverUrl: 'https://self.example.com' }),+ ).resolves.toEqual({ ok: false, reason: 'not_configured' });+ });++ it('does not use the official default when the lookup fails', async () => {+ getGlobalConfig.mockRejectedValue(new Error('INTERNAL_SERVER_ERROR'));++ await expect(+ resolveCliDeviceGateway({ serverUrl: 'https://app.lobehub.com' }),+ ).resolves.toMatchObject({ ok: false, reason: 'discovery_failed' });+ });+});++describe('rememberGatewayOverride', () => {+ beforeEach(() => {+ vi.mocked(loadDeviceGatewayUrl).mockReset();+ vi.mocked(saveDeviceGatewayUrl).mockReset();+ });++ const override = { source: 'override' as const, url: 'https://gw.example.com' };++ it.each([+ ['a self-hosted server', 'https://self.example.com'],+ ['official cloud', 'https://app.lobehub.com'],+ ])('saves --gateway as the address of %s', (_label, serverUrl) => {+ expect(rememberGatewayOverride(serverUrl, override)).toBe(true);+ expect(saveDeviceGatewayUrl).toHaveBeenCalledWith(serverUrl, override.url);+ });++ it('saves nothing for an unchanged, saved, advertised or default address', () => {+ vi.mocked(loadDeviceGatewayUrl).mockReturnValue(override.url);+ expect(rememberGatewayOverride('https://self.example.com', override)).toBe(false);++ vi.mocked(loadDeviceGatewayUrl).mockReturnValue(undefined);+ for (const source of ['manual', 'server', 'official'] as const) {+ expect(rememberGatewayOverride('https://self.example.com', { ...override, source })).toBe(+ false,+ );+ }+ expect(saveDeviceGatewayUrl).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/device/gatewayEndpoint.ts b/apps/cli/src/device/gatewayEndpoint.tsnew file mode 100644index 00000000000..b0ee35e77d6--- /dev/null+++ b/apps/cli/src/device/gatewayEndpoint.ts@@ -0,0 +1,167 @@+import { isOfficialCloudServer } from '@lobechat/const';+import {+ type DeviceGatewayDiscovery,+ type DeviceGatewayEndpoint,+ type DeviceGatewayResolution,+ type DeviceGatewayUrlSource,+ parseDeviceGatewayDiscovery,+ resolveDeviceGatewayEndpoint,+} from '@lobechat/device-gateway-client';++import { createPublicLambdaClient } from '../api/client';+import { CLI_PRIMARY_BIN } from '../constants/identity';+import { OFFICIAL_GATEWAY_URL } from '../constants/urls';+import { redactUrlCredentials, scrubText } from '../doctor/redact';+import { loadDeviceGatewayUrl, saveDeviceGatewayUrl } from '../settings';+import { formatError, isTransientNetworkError } from '../utils/error';++/** Total discovery budget, including retries, leaving room in the 30s daemon startup window. */+const DISCOVERY_TIMEOUT_MS = 10_000;+/** Retry quick transient failures against the same server within the total budget. */+const DISCOVERY_RETRY_DELAYS_MS = [250, 1000, 2500];++export type DeviceGatewayFailure = Extract<DeviceGatewayResolution, { ok: false }>;++/**+ * Ask `serverUrl` which Device Gateway its clients should use. Anonymous on+ * purpose — the address is public — and never throws: an unreachable server,+ * an error status or a body that is not a global config is `failed`, distinct+ * from a server that simply advertises nothing.+ */+export async function discoverDeviceGateway(serverUrl: string): Promise<DeviceGatewayDiscovery> {+ const controller = new AbortController();+ const deadline = Date.now() + DISCOVERY_TIMEOUT_MS;+ const timeout = setTimeout(() => {+ controller.abort(new Error('Device gateway discovery timed out'));+ }, DISCOVERY_TIMEOUT_MS);++ try {+ const client = createPublicLambdaClient(serverUrl);+ for (let attempt = 0; ; attempt += 1) {+ try {+ const config = await client.config.getGlobalConfig.query(undefined, {+ signal: controller.signal,+ });+ return parseDeviceGatewayDiscovery(config);+ } catch (error) {+ // Retry the same server only; never start a delay beyond the shared deadline.+ const delay = DISCOVERY_RETRY_DELAYS_MS[attempt];+ if (+ delay !== undefined &&+ !controller.signal.aborted &&+ delay < deadline - Date.now() &&+ isTransientNetworkError(error)+ ) {+ await new Promise((resolve) => setTimeout(resolve, delay));+ continue;+ }+ // Preserve the cause chain while removing URL credentials before any caller logs it.+ return {+ reason: scrubText(+ formatError(controller.signal.aborted ? controller.signal.reason : error),+ ),+ status: 'failed',+ };+ }+ }+ } finally {+ clearTimeout(timeout);+ }+}++/**+ * The Device Gateway for a credential's server — `auth.serverUrl` as resolved+ * with the token, so the address, the server and the token always belong to+ * one login. `connect`, `status` and `doctor` all resolve through here.+ *+ * Order: `--gateway`, then the address saved for this server (both without+ * asking it), then what the server advertises, then — when it advertises+ * nothing — the official gateway for official cloud. A self-hosted server+ * keeps needing an address, as before discovery existed. A failed lookup is an+ * error, never a reason to try another deployment's gateway.+ */+export async function resolveCliDeviceGateway({+ override,+ serverUrl,+}: {+ override?: string;+ serverUrl: string;+}): Promise<DeviceGatewayResolution> {+ return resolveDeviceGatewayEndpoint({+ discover: () => discoverDeviceGateway(serverUrl),+ manualUrl: loadDeviceGatewayUrl(serverUrl),+ officialGatewayUrl: isOfficialCloudServer(serverUrl) ? OFFICIAL_GATEWAY_URL : undefined,+ override,+ });+}++/**+ * Keep an explicit `--gateway` as this server's saved address, reused by later+ * runs ahead of whatever the server advertises — and only for this server.+ *+ * @returns whether anything changed.+ */+export function rememberGatewayOverride(+ serverUrl: string,+ endpoint: DeviceGatewayEndpoint,+): boolean {+ if (endpoint.source !== 'override') return false;+ if (loadDeviceGatewayUrl(serverUrl) === endpoint.url) return false;++ saveDeviceGatewayUrl(serverUrl, endpoint.url);+ return true;+}++const SOURCE_LABELS: Record<DeviceGatewayUrlSource, string> = {+ manual: 'saved for this server',+ official: 'official default',+ override: '--gateway',+ server: 'advertised by the server',+};++/** `https://gw.example.com (advertised by the server)`, safe to print. */+export function describeDeviceGateway(endpoint: DeviceGatewayEndpoint): string {+ return `${redactUrlCredentials(endpoint.url)} (${SOURCE_LABELS[endpoint.source]})`;+}++/** What went wrong and what to do about it, safe to print. */+export function describeDeviceGatewayFailure(+ failure: DeviceGatewayFailure,+ serverUrl: string,+): { detail: string; fix: string } {+ const server = redactUrlCredentials(serverUrl);+ const remember = `Run '${CLI_PRIMARY_BIN} connect --gateway <url>' once with this server's device gateway; it is remembered for ${server} only.`;++ switch (failure.reason) {+ case 'discovery_failed': {+ return {+ detail: `Could not read the device gateway address from ${server}: ${failure.detail ?? 'unknown error'}.`,+ fix: `Check that ${server} is reachable and is the server you logged in to, then retry. A gateway set with '--gateway <url>' is remembered for this server and skips the lookup.`,+ };+ }+ case 'invalid_advertised_url': {+ return {+ detail: `${server} advertises a device gateway address that is not a valid http(s) URL.`,+ fix: `Ask the server administrator to fix DEVICE_GATEWAY_PUBLIC_URL. Until then: ${remember}`,+ };+ }+ case 'invalid_manual': {+ return {+ detail: `The device gateway address saved for ${server} is not a valid http(s) URL.`,+ fix: `Replace it: ${remember}`,+ };+ }+ case 'invalid_override': {+ return {+ detail: '--gateway is not a valid http(s) URL without credentials, query or fragment.',+ fix: 'Pass the gateway base URL, e.g. --gateway https://gateway.example.com',+ };+ }+ case 'not_configured': {+ return {+ detail: `${server} does not advertise a device gateway, and none is saved for it.`,+ fix: remember,+ };+ }+ }+}diff --git a/apps/cli/src/doctor/checks/device.test.ts b/apps/cli/src/doctor/checks/device.test.tsindex da314a806c7..9ec534667e9 100644--- a/apps/cli/src/doctor/checks/device.test.ts+++ b/apps/cli/src/doctor/checks/device.test.ts@@ -1,5 +1,9 @@+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';import { beforeEach, describe, expect, it, vi } from 'vitest';+import type * as ApiClientModule from '../../api/client';+import type * as SettingsModule from '../../settings';+import type * as ProbesModule from '../probes';import { makeContext, runCheck } from '../testUtils';import { deviceChecks } from './device';@@ -28,9 +32,13 @@ vi.mock('../../service/connect', () => ({vi.mock('../../utils/device', () => ({ resolveLocalDeviceId: () => state.localDeviceId }));-vi.mock('../probes', () => ({+const credentialServer = vi.hoisted(() => ({ value: 'https://app.lobehub.com' }));++vi.mock('../probes', async (importOriginal) => ({+ // `probeDeviceGateway` stays real: the check must resolve like `lh connect`.+ ...(await importOriginal<typeof ProbesModule>()),probeCredential: async () => ({- serverUrl: 'https://app.lobehub.com',+ serverUrl: credentialServer.value,token: 't',tokenType: 'jwt',userId: 'u',@@ -38,6 +46,109 @@ vi.mock('../probes', () => ({probeDevices: async () => state.devices,}));+const getGlobalConfig = vi.hoisted(() => vi.fn());+const createPublicLambdaClient = vi.hoisted(() =>+ vi.fn(() => ({ config: { getGlobalConfig: { query: getGlobalConfig } } })),+);+vi.mock('../../api/client', async (importOriginal) => ({+ ...(await importOriginal<typeof ApiClientModule>()),+ createPublicLambdaClient,+}));++const savedGateway = vi.hoisted(() => ({ value: undefined as string | undefined }));+vi.mock('../../settings', async (importOriginal) => ({+ ...(await importOriginal<typeof SettingsModule>()),+ loadDeviceGatewayUrl: () => savedGateway.value,+}));++const gatewayClients = vi.hoisted(() => [] as any[]);+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),+ GatewayClient: vi.fn().mockImplementation(function (options: any) {+ const listeners: Record<string, (...args: any[]) => void> = {};+ const client = {+ connect: vi.fn(async () => listeners.connected?.()),+ disconnect: vi.fn(),+ on: (event: string, listener: (...args: any[]) => void) => {+ listeners[event] = listener;+ },+ options,+ };+ gatewayClients.push(client);+ return client;+ }),+}));++describe('device.gateway', () => {+ const SELF_HOSTED = 'https://lobe.internal';++ beforeEach(() => {+ gatewayClients.length = 0;+ credentialServer.value = SELF_HOSTED;+ savedGateway.value = undefined;+ getGlobalConfig.mockReset();+ createPublicLambdaClient.mockClear();+ });++ it("handshakes with the gateway the credential's server advertises", async () => {+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.lobe.internal/edge/' },+ });++ const outcome = await runCheck(deviceChecks, 'device.gateway', makeContext());++ expect(createPublicLambdaClient).toHaveBeenCalledWith(SELF_HOSTED);+ expect(gatewayClients.map((client) => client.options.gatewayUrl)).toEqual([+ 'https://gw.lobe.internal/edge',+ ]);+ expect(outcome).toMatchObject({+ detail: 'Authenticated to https://gw.lobe.internal/edge (advertised by the server).',+ evidence: { gatewaySource: 'server', serverUrl: SELF_HOSTED },+ status: 'ok',+ });+ });++ it('handshakes with the address saved for that server ahead of its advertisement', async () => {+ savedGateway.value = 'http://127.0.0.1:8788';+ getGlobalConfig.mockResolvedValue({+ serverConfig: { deviceGatewayUrl: 'https://gw.lobe.internal/edge/' },+ });++ const outcome = await runCheck(deviceChecks, 'device.gateway', makeContext());++ expect(getGlobalConfig).not.toHaveBeenCalled();+ expect(gatewayClients.map((client) => client.options.gatewayUrl)).toEqual([+ 'http://127.0.0.1:8788',+ ]);+ expect(outcome).toMatchObject({+ detail: 'Authenticated to http://127.0.0.1:8788 (saved for this server).',+ evidence: { gatewaySource: 'manual', serverUrl: SELF_HOSTED },+ status: 'ok',+ });+ });++ it('says how to configure a self-hosted server that advertises no gateway', async () => {+ getGlobalConfig.mockResolvedValue({ serverConfig: {} });++ const outcome = await runCheck(deviceChecks, 'device.gateway', makeContext());++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('does not advertise a device gateway');+ expect(outcome.fix).toContain('--gateway <url>');+ expect(gatewayClients).toHaveLength(0);+ });++ it('fails a broken lookup instead of probing a default', async () => {+ getGlobalConfig.mockRejectedValue(new Error('INTERNAL_SERVER_ERROR'));++ const outcome = await runCheck(deviceChecks, 'device.gateway', makeContext());++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('Could not read the device gateway address');+ expect(gatewayClients).toHaveLength(0);+ });+});+describe('device.daemon', () => {beforeEach(() => {state.daemonPid = null;diff --git a/apps/cli/src/doctor/checks/device.ts b/apps/cli/src/doctor/checks/device.tsindex 45e088579aa..24031306a8a 100644--- a/apps/cli/src/doctor/checks/device.ts+++ b/apps/cli/src/doctor/checks/device.ts@@ -2,12 +2,12 @@ import { GatewayClient } from '@lobechat/device-gateway-client';import { CLI_PRIMARY_BIN } from '../../constants/identity';import { getRunningDaemonPid, readStatus, removePid, removeStatus } from '../../daemon/manager';+import { describeDeviceGateway, describeDeviceGatewayFailure } from '../../device/gatewayEndpoint';import { readConnectServiceStatus } from '../../service/connect';import { resolveLocalDeviceId } from '../../utils/device';-import { probeCredential, probeDevices } from '../probes';+import { probeCredential, probeDeviceGateway, probeDevices } from '../probes';import { redactUrlCredentials, redactUrlsInMessage } from '../redact';import type { CheckOutcome, DoctorCheck } from '../types';-import { resolveEndpoints } from './endpoints';/*** Is there a `lh connect` daemon on this machine, and is the state it left@@ -38,7 +38,8 @@ const daemon: DoctorCheck = {const evidence = {connectionStatus: status?.connectionStatus,deviceId: status?.deviceId,- gatewayUrl: status?.gatewayUrl,+ gatewaySource: status?.gatewaySource,+ gatewayUrl: redactUrlCredentials(status?.gatewayUrl),pid,service,};@@ -77,8 +78,11 @@ const daemon: DoctorCheck = {status: 'warn',};+ const via = evidence.gatewayUrl+ ? ` via ${evidence.gatewayUrl}${evidence.gatewaySource ? ` (${evidence.gatewaySource})` : ''}`+ : '';return {- detail: `Daemon ${pid} connected as device ${status.deviceId ?? 'unknown'}.`,+ detail: `Daemon ${pid} connected as device ${status.deviceId ?? 'unknown'}${via}.`,evidence,status: 'ok',};@@ -97,8 +101,9 @@ function readServiceStatus(): unknown {/*** Can this machine authenticate to the device gateway at all — separating- * "wrong URL", "rejected token" and "nothing answers", which all present as a- * bare DEVICE_OFFLINE to whoever called the tool.+ * "no address", "wrong URL", "rejected token" and "nothing answers", which all+ * present as a bare DEVICE_OFFLINE to whoever called the tool. The address is+ * resolved the way `lh connect` resolves it, against the credential's server.*/const gatewayHandshake: DoctorCheck = {dependsOn: ['credentials.validity', 'endpoints.resolution'],@@ -115,10 +120,23 @@ const gatewayHandshake: DoctorCheck = {status: 'fail',};- const { gatewayUrl } = resolveEndpoints();+ const serverUrl = redactUrlCredentials(credential.serverUrl);+ const gateway = await probeDeviceGateway(ctx, credential.serverUrl);+ if (!gateway.ok) {+ const { detail, fix } = describeDeviceGatewayFailure(gateway, credential.serverUrl);+ return { detail, evidence: { reason: gateway.reason, serverUrl }, fix, status: 'fail' };+ }++ const { source, url: gatewayUrl } = gateway.endpoint;// The URL is used verbatim to connect and redacted everywhere it is shown.const shownUrl = redactUrlCredentials(gatewayUrl);- const evidence = { gatewayUrl: shownUrl, tokenType: credential.tokenType };+ const shownGateway = describeDeviceGateway(gateway.endpoint);+ const evidence = {+ gatewaySource: source,+ gatewayUrl: shownUrl,+ serverUrl,+ tokenType: credential.tokenType,+ };const outcome = await new Promise<CheckOutcome>((resolve) => {const client = new GatewayClient({@@ -162,13 +180,16 @@ const gatewayHandshake: DoctorCheck = {}),);client.on('connected', () =>- settle({ detail: `Authenticated to ${shownUrl}.`, evidence, status: 'ok' }),+ settle({ detail: `Authenticated to ${shownGateway}.`, evidence, status: 'ok' }),);client.on('auth_failed', (reason: string) =>settle({- detail: `${shownUrl} rejected the credential: ${reason}.`,+ detail: `${shownGateway} rejected the credential: ${reason}.`,evidence,- fix: 'The gateway and the server must trust the same issuer — check the gateway URL matches this server.',+ fix:+ source === 'server'+ ? `The gateway ${serverUrl} advertises does not trust its tokens — the server's DEVICE_GATEWAY_PUBLIC_URL likely points at another deployment.`+ : 'The gateway and the server must trust the same issuer — check the gateway URL matches this server.',status: 'fail',}),);diff --git a/apps/cli/src/doctor/checks/endpoints.test.ts b/apps/cli/src/doctor/checks/endpoints.test.tsindex 4810e55bff3..9cc6bc2e7a3 100644--- a/apps/cli/src/doctor/checks/endpoints.test.ts+++ b/apps/cli/src/doctor/checks/endpoints.test.ts@@ -5,7 +5,13 @@ import { endpointChecks } from './endpoints';const settings = vi.hoisted(() => ({ value: null as any }));+const authKind = vi.hoisted(() => ({ value: 'stored' }));++vi.mock('../../auth/source', () => ({ pickAuthSource: () => ({ kind: authKind.value }) }));+vi.mock('../../settings', () => ({+ // Saved per server; only `settings.deviceGatewayUrls` of the probed server counts.+ loadDeviceGatewayUrl: (serverUrl: string) => settings.value?.deviceGatewayUrls?.[serverUrl],loadSettings: () => settings.value,normalizeUrl: (url?: string) => (url ? url.replace(/\/$/, '') : undefined),resolveAgentGatewayUrl: () => process.env.AGENT_GATEWAY_URL || 'wss://agent-gateway.lobehub.com',@@ -21,6 +27,7 @@ vi.mock('../../constants/urls', () => ({describe('endpoints.resolution', () => {beforeEach(() => {settings.value = null;+ authKind.value = 'stored';delete process.env.LOBEHUB_SERVER;delete process.env.AGENT_GATEWAY_URL;});@@ -30,25 +37,42 @@ describe('endpoints.resolution', () => {expect(outcome.status).toBe('ok');expect(outcome.evidence).toMatchObject({- gatewaySource: 'built-in default',serverSource: 'built-in default',serverUrl: 'https://app.lobehub.com',});+ expect(outcome.detail).toContain('device gateway asked of the server');});- it('warns — never fails — about a self-hosted server on the official device gateway', async () => {+ it("names the gateway saved for this server, and only this server's", async () => {process.env.LOBEHUB_SERVER = 'https://lobe.internal';+ process.env.AGENT_GATEWAY_URL = 'wss://agents.internal';+ authKind.value = 'env-jwt';+ settings.value = {+ deviceGatewayUrls: {+ 'https://lobe.internal': 'https://gw.lobe.internal',+ 'https://other.internal': 'https://gw.other.internal',+ },+ };++ const outcome = await runCheck(endpointChecks, 'endpoints.resolution');++ expect(outcome.status).toBe('ok');+ expect(outcome.evidence).toMatchObject({ savedDeviceGatewayUrl: 'https://gw.lobe.internal' });+ expect(outcome.detail).toContain('https://gw.lobe.internal (saved for this server)');+ });++ it('warns when LOBEHUB_SERVER sends the stored login to another server', async () => {+ process.env.LOBEHUB_SERVER = 'https://other.internal';+ settings.value = { serverUrl: 'https://lobe.internal' };const outcome = await runCheck(endpointChecks, 'endpoints.resolution');- // A failure here would skip every server-side check through the dependency- // chain, leaving an API-only installation undiagnosable.expect(outcome.status).toBe('warn');- expect(outcome.detail).toContain('device gateway is still the official');+ expect(outcome.detail).toContain('the saved login is for https://lobe.internal');});- it('warns when the gateway is on localhost but the server is not', async () => {- settings.value = { gatewayUrl: 'http://127.0.0.1:8788' };+ it('warns when the saved gateway is on localhost but the server is not', async () => {+ settings.value = { deviceGatewayUrls: { 'https://app.lobehub.com': 'http://127.0.0.1:8788' } };const outcome = await runCheck(endpointChecks, 'endpoints.resolution');@@ -58,7 +82,7 @@ describe('endpoints.resolution', () => {it('warns when a self-hosted server still streams agents from the official gateway', async () => {process.env.LOBEHUB_SERVER = 'https://lobe.internal';- settings.value = { gatewayUrl: 'wss://gateway.internal' };+ authKind.value = 'env-jwt';const outcome = await runCheck(endpointChecks, 'endpoints.resolution');diff --git a/apps/cli/src/doctor/checks/endpoints.ts b/apps/cli/src/doctor/checks/endpoints.tsindex 8dc7ceeb65e..a670eb735b0 100644--- a/apps/cli/src/doctor/checks/endpoints.ts+++ b/apps/cli/src/doctor/checks/endpoints.ts@@ -1,11 +1,11 @@import fs from 'node:fs';+import { isOfficialCloudServer } from '@lobechat/const';++import { pickAuthSource } from '../../auth/source';+import { OFFICIAL_AGENT_GATEWAY_URL } from '../../constants/urls';import {- OFFICIAL_AGENT_GATEWAY_URL,- OFFICIAL_GATEWAY_URL,- OFFICIAL_SERVER_URL,-} from '../../constants/urls';-import {+ loadDeviceGatewayUrl,loadSettings,normalizeUrl,resolveAgentGatewayUrl,@@ -18,20 +18,24 @@ import type { CheckOutcome, DoctorCheck } from '../types';export interface ResolvedEndpoints {agentGatewaySource: string;agentGatewayUrl?: string;- gatewaySource: string;- gatewayUrl: string;+ /**+ * Device gateway saved for this server (by `--gateway`); it is used ahead of+ * the server's own. Without one the address is asked of the server at+ * connect time (see `device.gateway`), so it has no static value here.+ */+ savedDeviceGatewayUrl?: string;serverSource: string;serverUrl: string;}/**- * The three URLs the CLI talks to, each with the reason it has that value.+ * The URLs the CLI talks to, each with the reason it has that value.** They do not share a resolution rule — `LOBEHUB_SERVER` and- * `AGENT_GATEWAY_URL` exist but there is no env var for the device gateway,- * and `settings.json` is deleted whenever every URL is back to default. So- * "my config looks right but the CLI behaves like it isn't" has three separate- * causes, and printing the winner plus its source is what tells them apart.+ * `AGENT_GATEWAY_URL` exist, the device gateway is asked of the server, and+ * `settings.json` is deleted whenever every URL is back to default. So "my+ * config looks right but the CLI behaves like it isn't" has separate causes,+ * and printing the winner plus its source is what tells them apart.*/export function resolveEndpoints(): ResolvedEndpoints {const settings = loadSettings();@@ -45,8 +49,7 @@ export function resolveEndpoints(): ResolvedEndpoints {? 'settings.json': 'built-in default',agentGatewayUrl,- gatewaySource: settings?.gatewayUrl ? 'settings.json' : 'built-in default',- gatewayUrl: normalizeUrl(settings?.gatewayUrl) || OFFICIAL_GATEWAY_URL,+ savedDeviceGatewayUrl: loadDeviceGatewayUrl(serverUrl),serverSource: process.env.LOBEHUB_SERVER? 'LOBEHUB_SERVER': settings?.serverUrl@@ -67,37 +70,40 @@ const endpointResolution: DoctorCheck = {// the checks that connect with them.const shown = {agentGatewayUrl: redactUrlCredentials(endpoints.agentGatewayUrl),- gatewayUrl: redactUrlCredentials(endpoints.gatewayUrl),+ savedDeviceGatewayUrl: redactUrlCredentials(endpoints.savedDeviceGatewayUrl),serverUrl: redactUrlCredentials(endpoints.serverUrl),};const evidence = { ...endpoints, ...shown };- const selfHosted = endpoints.serverUrl !== OFFICIAL_SERVER_URL;-- // A self-hosted server with the official device gateway is the trap: only- // `lh status` complains today, while every other device command connects to- // a gateway that has never heard of that server.- //- // A warning, not a failure: an installation that only uses the HTTP API- // never needs a device gateway, and failing here would skip every check- // below through the dependency chain — leaving doctor unable to say- // anything at all about an otherwise healthy server. The device profile's- // own handshake check is what fails concretely when it matters.- if (selfHosted && endpoints.gatewaySource === 'built-in default')+ const selfHosted = !isOfficialCloudServer(endpoints.serverUrl);++ // `LOBEHUB_SERVER` redirects this run, but a stored login belongs to the+ // server `lh login` used. (Env credentials are issued for LOBEHUB_SERVER.)+ const loginServerUrl = normalizeUrl(loadSettings()?.serverUrl);+ if (+ process.env.LOBEHUB_SERVER &&+ loginServerUrl &&+ loginServerUrl !== endpoints.serverUrl &&+ pickAuthSource().kind === 'stored'+ )return {- detail: `Server is ${shown.serverUrl} but the device gateway is still the official ${OFFICIAL_GATEWAY_URL}, which has never heard of that server.`,- evidence,- fix: "Only matters for device commands: pass --gateway <url> to 'lh connect' (it is persisted).",+ detail: `LOBEHUB_SERVER points at ${shown.serverUrl}, but the saved login is for ${redactUrlCredentials(loginServerUrl)}.`,+ evidence: { ...evidence, loginServerUrl: redactUrlCredentials(loginServerUrl) },+ fix: `Unset LOBEHUB_SERVER, or run 'lh login --server ${shown.serverUrl}' so the credential belongs to the server it is sent to.`,status: 'warn',};- // A gateway that only exists on this machine cannot be dispatched to by a- // remote server (and vice versa). Left over from local gateway work, this- // shows up later as an opaque "credential rejected" handshake failure.- if (isLoopback(endpoints.gatewayUrl) !== isLoopback(endpoints.serverUrl))+ // A saved gateway that only exists on this machine cannot be dispatched to+ // by a remote server (and vice versa). Left over from local gateway work,+ // it wins over the server's own address and shows up later as an opaque+ // "credential rejected" handshake failure.+ if (+ endpoints.savedDeviceGatewayUrl &&+ isLoopback(endpoints.savedDeviceGatewayUrl) !== isLoopback(endpoints.serverUrl)+ )return {- detail: `Server ${shown.serverUrl} and device gateway ${shown.gatewayUrl} are not on the same side of localhost.`,+ detail: `Server ${shown.serverUrl} and its saved device gateway ${shown.savedDeviceGatewayUrl} are not on the same side of localhost.`,evidence,- fix: isLoopback(endpoints.gatewayUrl)+ fix: isLoopback(endpoints.savedDeviceGatewayUrl)? "Drop the local gateway: 'lh connect --gateway <the server's gateway>'.": 'Point --gateway at the gateway that belongs to this server.',status: 'warn',@@ -112,7 +118,7 @@ const endpointResolution: DoctorCheck = {};return {- detail: `server ${shown.serverUrl} (${endpoints.serverSource}), device gateway ${shown.gatewayUrl} (${endpoints.gatewaySource}).`,+ detail: `server ${shown.serverUrl} (${endpoints.serverSource}); device gateway ${shown.savedDeviceGatewayUrl ? `${shown.savedDeviceGatewayUrl} (saved for this server)` : 'asked of the server'}.`,evidence,status: 'ok',};diff --git a/apps/cli/src/doctor/probes.ts b/apps/cli/src/doctor/probes.tsindex 8c904bfe655..c83556b4e01 100644--- a/apps/cli/src/doctor/probes.ts+++ b/apps/cli/src/doctor/probes.ts@@ -4,6 +4,7 @@ import { getUserIdFromApiKey } from '../auth/apiKey';import { describeTokenLookup, getValidToken } from '../auth/refresh';import type { AuthSourceKind } from '../auth/source';import { parseJwtPayload, pickAuthSource } from '../auth/source';+import { resolveCliDeviceGateway } from '../device/gatewayEndpoint';import { resolveServerUrl } from '../settings';import type { DoctorContext } from './types';@@ -173,3 +174,12 @@ export async function probeProviders(ctx: DoctorContext): Promise<any[]> {return Array.isArray(providers) ? providers : [];});}++/**+ * The device gateway for `serverUrl`, resolved exactly as `lh connect` does —+ * same lookup, same precedence — so the handshake check probes the gateway a+ * real connection would use.+ */+export async function probeDeviceGateway(ctx: DoctorContext, serverUrl: string) {+ return ctx.probe(`device:gateway:${serverUrl}`, () => resolveCliDeviceGateway({ serverUrl }));+}diff --git a/apps/cli/src/settings/index.test.ts b/apps/cli/src/settings/index.test.tsindex 1dcc811b9a4..2a89363bc65 100644--- a/apps/cli/src/settings/index.test.ts+++ b/apps/cli/src/settings/index.test.ts@@ -8,13 +8,16 @@ import { resolveCliDirName } from '../constants/identity';import { log } from '../utils/logger';import {loadActiveWorkspace,+ loadDeviceGatewayUrl,loadOrCreateConnectionId,loadSettings,normalizeUrl,resolveDeviceMetricsBacklogPath,resolveServerUrl,saveActiveWorkspace,+ saveDeviceGatewayUrl,saveSettings,+ settingsForLogin,} from './index';const tmpDir = path.join(os.tmpdir(), 'lobehub-cli-test-settings');@@ -59,6 +62,67 @@ describe('settings', () => {});});+ describe('device gateway addresses', () => {+ it('binds a saved address to its server only', () => {+ saveDeviceGatewayUrl('https://a.example.com/', 'https://gw-a.example.com/');++ expect(loadDeviceGatewayUrl('https://a.example.com')).toBe('https://gw-a.example.com');+ expect(loadDeviceGatewayUrl('https://b.example.com')).toBeUndefined();+ expect(loadDeviceGatewayUrl('https://app.lobehub.com')).toBeUndefined();+ });++ it('reads a pre-discovery gatewayUrl only for the server it was saved with', () => {+ saveSettings({ gatewayUrl: 'http://localhost:8788', serverUrl: 'https://self.example.com' });+ // LOBEHUB_SERVER points this run at another server than the saved login.+ process.env.LOBEHUB_SERVER = 'https://other.example.com';++ expect(loadDeviceGatewayUrl('https://self.example.com/')).toBe('http://localhost:8788');+ expect(loadDeviceGatewayUrl(resolveServerUrl())).toBeUndefined();+ });++ it('reads a gatewayUrl saved with official cloud as official cloud’s address only', () => {+ saveSettings({ gatewayUrl: 'http://localhost:8788' });++ expect(loadDeviceGatewayUrl('https://app.lobehub.com/')).toBe('http://localhost:8788');+ expect(loadDeviceGatewayUrl('https://self.example.com')).toBeUndefined();+ });++ it('supersedes the legacy value when saving for its server', () => {+ saveSettings({ gatewayUrl: 'http://localhost:8788', serverUrl: 'https://self.example.com' });++ saveDeviceGatewayUrl('https://self.example.com', 'https://gw.self.example.com');++ expect(loadSettings()).toEqual({+ deviceGatewayUrls: { 'https://self.example.com': 'https://gw.self.example.com' },+ serverUrl: 'https://self.example.com',+ });+ });++ it('keeps each address with its own server across logins', () => {+ saveSettings({ gatewayUrl: 'https://gw-a.example.com', serverUrl: 'https://a.example.com' });++ saveSettings(settingsForLogin(loadSettings(), 'https://b.example.com'));++ expect(loadSettings()).toEqual({+ deviceGatewayUrls: { 'https://a.example.com': 'https://gw-a.example.com' },+ serverUrl: 'https://b.example.com',+ });+ expect(loadDeviceGatewayUrl('https://b.example.com')).toBeUndefined();++ saveSettings(settingsForLogin(loadSettings(), 'https://a.example.com'));+ expect(loadDeviceGatewayUrl('https://a.example.com')).toBe('https://gw-a.example.com');+ });++ it('keeps an official cloud gatewayUrl with official cloud across a login elsewhere', () => {+ saveSettings({ gatewayUrl: 'http://localhost:8788' });++ saveSettings(settingsForLogin(loadSettings(), 'https://b.example.com'));++ expect(loadDeviceGatewayUrl('https://b.example.com')).toBeUndefined();+ expect(loadDeviceGatewayUrl('https://app.lobehub.com')).toBe('http://localhost:8788');+ });+ });+it('should clear official server settings instead of persisting them', () => {saveSettings({ serverUrl: 'https://app.lobehub.com/' });diff --git a/apps/cli/src/settings/index.ts b/apps/cli/src/settings/index.tsindex e2d0734f47d..3344d41adbc 100644--- a/apps/cli/src/settings/index.ts+++ b/apps/cli/src/settings/index.ts@@ -4,6 +4,7 @@ import os from 'node:os';import path from 'node:path';import { deviceMetricsBacklogFileName } from '@lobechat/device-control/metrics';+import { deviceGatewayServerKey, normalizeDeviceGatewayUrl } from '@lobechat/device-gateway-client';import { resolveCliDirName } from '../constants/identity';import { OFFICIAL_AGENT_GATEWAY_URL, OFFICIAL_SERVER_URL } from '../constants/urls';@@ -11,6 +12,16 @@ import { log } from '../utils/logger';export interface StoredSettings {agentGatewayUrl?: string;+ /**+ * Device gateway address saved per server (keyed by `deviceGatewayServerKey`)+ * by `--gateway`. Used ahead of that server's own advertisement, and never+ * for another server.+ */+ deviceGatewayUrls?: Record<string, string>;+ /**+ * Pre-discovery global device gateway. Read only as the saved address of the+ * login it was saved with (`serverUrl`, or official cloud when that is unset).+ */gatewayUrl?: string;serverUrl?: string;}@@ -49,17 +60,39 @@ export function resolveAgentGatewayUrl(): string | undefined {return envUrl || settingsUrl || OFFICIAL_AGENT_GATEWAY_URL;}-export function saveSettings(settings: StoredSettings): void {+function normalizeDeviceGatewayUrls(value: unknown): Record<string, string> | undefined {+ if (!value || typeof value !== 'object') return undefined;++ const entries = Object.entries(value).flatMap(([server, url]) => {+ const key = deviceGatewayServerKey(server);+ const normalized = normalizeDeviceGatewayUrl(url);+ return key && normalized ? [[key, normalized] as const] : [];+ });+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;+}++function normalizeSettings(settings: StoredSettings): StoredSettings {const agentGatewayUrl = normalizeUrl(settings.agentGatewayUrl);- const gatewayUrl = normalizeUrl(settings.gatewayUrl);const serverUrl = normalizeUrl(settings.serverUrl);- const normalized: StoredSettings = {++ return {agentGatewayUrl: agentGatewayUrl === OFFICIAL_AGENT_GATEWAY_URL ? undefined : agentGatewayUrl,- gatewayUrl,+ deviceGatewayUrls: normalizeDeviceGatewayUrls(settings.deviceGatewayUrls),+ gatewayUrl: normalizeUrl(settings.gatewayUrl),serverUrl: serverUrl === OFFICIAL_SERVER_URL ? undefined : serverUrl,};+}- if (!normalized.serverUrl && !normalized.gatewayUrl && !normalized.agentGatewayUrl) {+const isDefaultSettings = (settings: StoredSettings) =>+ !settings.serverUrl &&+ !settings.gatewayUrl &&+ !settings.agentGatewayUrl &&+ !settings.deviceGatewayUrls;++export function saveSettings(settings: StoredSettings): void {+ const normalized = normalizeSettings(settings);++ if (isDefaultSettings(normalized)) {try {fs.unlinkSync(SETTINGS_FILE);} catch (error) {@@ -207,19 +240,9 @@ export function loadSettings(): StoredSettings | null {try {const data = fs.readFileSync(SETTINGS_FILE, 'utf8');- const parsed = JSON.parse(data) as StoredSettings;- const agentGatewayUrl = normalizeUrl(parsed.agentGatewayUrl);- const gatewayUrl = normalizeUrl(parsed.gatewayUrl);- const serverUrl = normalizeUrl(parsed.serverUrl);- const normalized: StoredSettings = {- agentGatewayUrl: agentGatewayUrl === OFFICIAL_AGENT_GATEWAY_URL ? undefined : agentGatewayUrl,- gatewayUrl,- serverUrl: serverUrl === OFFICIAL_SERVER_URL ? undefined : serverUrl,- };-- if (!normalized.serverUrl && !normalized.gatewayUrl && !normalized.agentGatewayUrl) return null;-- return normalized;+ const normalized = normalizeSettings(JSON.parse(data) as StoredSettings);++ return isDefaultSettings(normalized) ? null : normalized;} catch {log.warn(`Could not parse ${SETTINGS_FILE}. Please delete this file and run 'lh login' again if needed.`,@@ -227,3 +250,68 @@ export function loadSettings(): StoredSettings | null {return null;}}++/**+ * The server a pre-discovery `gatewayUrl` belongs to: the saved login it was+ * used with (`serverUrl` is only stored for a non-official server).+ */+const legacyGatewayOwner = (settings: StoredSettings | null) =>+ settings?.gatewayUrl+ ? deviceGatewayServerKey(settings.serverUrl || OFFICIAL_SERVER_URL)+ : undefined;++/**+ * Device gateway address saved for `serverUrl` — the server the current+ * credential belongs to, which may differ from `settings.serverUrl` when+ * `LOBEHUB_SERVER` points elsewhere. Never another server's address.+ */+export function loadDeviceGatewayUrl(serverUrl: string): string | undefined {+ const key = deviceGatewayServerKey(serverUrl);+ const settings = loadSettings();+ if (!key || !settings) return undefined;++ return (+ settings.deviceGatewayUrls?.[key] ??+ (legacyGatewayOwner(settings) === key ? settings.gatewayUrl : undefined)+ );+}++/** Remember `gatewayUrl` as the device gateway of `serverUrl`. */+export function saveDeviceGatewayUrl(serverUrl: string, gatewayUrl: string): void {+ const key = deviceGatewayServerKey(serverUrl);+ if (!key) return;++ const settings = loadSettings() ?? {};+ saveSettings({+ ...settings,+ deviceGatewayUrls: { ...settings.deviceGatewayUrls, [key]: gatewayUrl },+ // Superseded by the entry just written for the same server.+ gatewayUrl: legacyGatewayOwner(settings) === key ? undefined : settings.gatewayUrl,+ });+}++/**+ * Settings after logging in to `serverUrl`, from the `existing` ones. Saved+ * device gateway addresses are keyed by server, so they all carry over; a+ * pre-discovery `gatewayUrl` stays with the server it was saved for instead of+ * following the login to another one.+ */+export function settingsForLogin(+ existing: StoredSettings | null,+ serverUrl: string,+): StoredSettings {+ const sameServer = (existing?.serverUrl || OFFICIAL_SERVER_URL) === serverUrl;+ const deviceGatewayUrls = { ...existing?.deviceGatewayUrls };++ const gatewayUrl = sameServer ? existing?.gatewayUrl : undefined;+ const owner = legacyGatewayOwner(existing);+ if (!sameServer && owner && !deviceGatewayUrls[owner]) {+ deviceGatewayUrls[owner] = existing!.gatewayUrl!;+ }++ return {+ ...(Object.keys(deviceGatewayUrls).length > 0 && { deviceGatewayUrls }),+ ...(gatewayUrl && { gatewayUrl }),+ serverUrl,+ };+}diff --git a/apps/desktop/src/main/const/store.ts b/apps/desktop/src/main/const/store.tsindex 034233bce3f..80249511a62 100644--- a/apps/desktop/src/main/const/store.ts+++ b/apps/desktop/src/main/const/store.ts@@ -32,8 +32,7 @@ export const STORE_DEFAULTS: ElectronMainStore = {gatewayDeviceId: '',gatewayEnabled: true,gatewayKeepAwake: true,- gatewayUrl: 'https://device-gateway.lobehub.com',- gatewayWorkspaceEnrollments: [],+ gatewayWorkspaceEnrollmentsByAccount: {},heteroSessionDirPrefs: {},heteroTracingEnabled: false,imessageBridgeConfigs: [],diff --git a/apps/desktop/src/main/controllers/AuthCtr.ts b/apps/desktop/src/main/controllers/AuthCtr.tsindex 56d68a017df..f2a3da958e9 100644--- a/apps/desktop/src/main/controllers/AuthCtr.ts+++ b/apps/desktop/src/main/controllers/AuthCtr.ts@@ -553,13 +553,15 @@ export default class AuthCtr extends ControllerModule {}/**- * Connect to device gateway (fire-and-forget)+ * Connect to device gateway (fire-and-forget). A sign-in may be another+ * account or another server, so whatever the previous login had open is+ * replaced rather than joined.*/private connectGateway() {const gatewaySrv = this.app.getService(GatewayConnectionService);if (gatewaySrv) {logger.info('Triggering gateway connection after login');- gatewaySrv.connect().catch((error) => {+ gatewaySrv.restart().catch((error) => {logger.error('Gateway connection after login failed:', error);});}diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 0155a15cb51..630a84b3415 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -9,7 +9,12 @@ import {toAuvToolOutput,} from '@lobechat/device-control/computer-use';import type { AgentRunRequestMessage, GatewayMcpParams } from '@lobechat/device-gateway-client';-import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';+import { deviceGatewayServerKey } from '@lobechat/device-gateway-client/endpoint';+import type {+ GatewayConnectionState,+ GatewayConnectResult,+ GatewayEndpointInfo,+} from '@lobechat/electron-client-ipc';import type { HeterogeneousAgentCancellationSignal } from '@lobechat/heterogeneous-agents/protocol';import { stripInheritedRunIdentity } from '@lobechat/heterogeneous-agents/protocol';import type { RemotePlatformCommandRuntime } from '@lobechat/heterogeneous-agents/scanHost';@@ -26,7 +31,9 @@ import { updaterConfig } from '@/modules/updater/configs';import { createRemoteAppUpdateDeps } from '@/modules/updater/remoteUpdate';import AuvService, { type AuvRunCommandParams } from '@/services/auvSrv';import { backfillDeviceArchitecture } from '@/services/deviceArchitectureBackfill';-import GatewayConnectionService from '@/services/gatewayConnectionSrv';+import GatewayConnectionService, {+ type WorkspaceDeviceRegistration,+} from '@/services/gatewayConnectionSrv';import ImessageBridgeService from '@/services/imessageBridgeSrv';import { findHeteroExecProcesses } from '@/utils/heteroExecProcess';import { createLogger } from '@/utils/logger';@@ -199,7 +206,8 @@ export default class GatewayConnectionCtr extends ControllerModule {srv.loadOrCreateDeviceId();- // Wire up token provider and refresher+ // Wire up the login the connection is bound to: server, token and refresher+ srv.setServerUrlProvider(() => this.getConfiguredServerUrl());srv.setTokenProvider(() => this.remoteServerConfigCtr.getAccessToken());srv.setTokenRefresher(() => this.remoteServerConfigCtr.refreshAccessToken());@@ -224,14 +232,16 @@ export default class GatewayConnectionCtr extends ControllerModule {srv.setRpcHandler((method, params) => this.executeDeviceRpc(method, params));// Wire up device registrar (persists this device to the server registry)- srv.setDeviceRegistrar((info) => this.registerDevice(info));+ srv.setDeviceRegistrar((info, auth) => this.registerDevice(info, auth));// Wire up the workspace-share hooks: connect-token minting (startup restore// + token expiry) and the "row still registered?" probe that keeps a share// revoked while offline from resurrecting as a ghost device.- srv.setWorkspaceTokenProvider((workspaceId) => this.mintWorkspaceConnectToken(workspaceId));- srv.setWorkspaceDeviceChecker((workspaceId, deviceId) =>- this.checkWorkspaceDeviceRegistered(workspaceId, deviceId),+ srv.setWorkspaceTokenProvider((workspaceId, serverUrl) =>+ this.mintWorkspaceConnectToken(workspaceId, serverUrl),+ );+ srv.setWorkspaceDeviceChecker((workspaceId, deviceId, serverUrl) =>+ this.checkWorkspaceDeviceRegistered(workspaceId, deviceId, serverUrl),);this.resolveGatewayReady?.();@@ -243,7 +253,7 @@ export default class GatewayConnectionCtr extends ControllerModule {// ─── IPC Methods (Renderer → Main) ───@IpcMethod()- async connect(): Promise<{ error?: string; success: boolean }> {+ async connect(): Promise<GatewayConnectResult> {this.app.storeManager.set('gatewayEnabled', true);return this.service.connect();}@@ -255,8 +265,14 @@ export default class GatewayConnectionCtr extends ControllerModule {}@IpcMethod()- async getConnectionStatus(): Promise<{ status: GatewayConnectionStatus }> {- return { status: this.service.getDisplayedStatus() };+ async getConnectionStatus(): Promise<GatewayConnectionState> {+ return this.service.getDisplayedState();+ }++ /** Which gateway this login uses, and the address saved in settings. */+ @IpcMethod()+ async getGatewayEndpoint(): Promise<GatewayEndpointInfo> {+ return this.service.getEndpointInfo();}@IpcMethod()@@ -323,6 +339,13 @@ export default class GatewayConnectionCtr extends ControllerModule {return result.success;}+ /** The signed-in server, or undefined when the desktop has no active login. */+ private async getConfiguredServerUrl(): Promise<string | undefined> {+ const config = await this.remoteServerConfigCtr.getRemoteServerConfig();+ if (!(await this.remoteServerConfigCtr.isRemoteServerConfigured(config))) return undefined;+ return this.remoteServerConfigCtr.getRemoteServerUrl(config);+ }+// ─── Auto Connect ───private async tryAutoConnect() {@@ -1322,18 +1345,15 @@ export default class GatewayConnectionCtr extends ControllerModule {* connection, the device just won't appear in the offline list until the* next successful connect.*/- private async registerDevice(info: {- deviceId: string;- hostname: string;- identitySource: string;- platform: string;- }): Promise<void> {- const [serverUrl, token] = await Promise.all([- this.remoteServerConfigCtr.getRemoteServerUrl(),- this.remoteServerConfigCtr.getAccessToken(),- ]);- if (!serverUrl || !token) return;-+ private async registerDevice(+ info: {+ deviceId: string;+ hostname: string;+ identitySource: string;+ platform: string;+ },+ { serverUrl, token }: { serverUrl: string; token: string },+ ): Promise<void> {const headers: Record<string, string> = {'Content-Type': 'application/json','Oidc-Auth': token,@@ -1351,15 +1371,23 @@ export default class GatewayConnectionCtr extends ControllerModule {* Build the auth headers for a workspace-scoped server call. The* `X-Workspace-Id` header is what routes the request through the workspace* (member+) procedures — same convention as `sendNotify` above.+ *+ * `expectedServerUrl` is the server the gateway session belongs to; when the+ * desktop has since signed out or moved to another server there is no auth+ * to use for that session, so the call is skipped.*/private async buildWorkspaceHeaders(workspaceId: string,+ expectedServerUrl: string,): Promise<{ headers: Record<string, string>; serverUrl: string } | null> {const [serverUrl, token] = await Promise.all([- this.remoteServerConfigCtr.getRemoteServerUrl(),+ this.getConfiguredServerUrl(),this.remoteServerConfigCtr.getAccessToken(),]);if (!serverUrl || !token) return null;+ if (deviceGatewayServerKey(serverUrl) !== deviceGatewayServerKey(expectedServerUrl)) {+ return null;+ }const headers: Record<string, string> = {'Content-Type': 'application/json',@@ -1376,8 +1404,11 @@ export default class GatewayConnectionCtr extends ControllerModule {* when a workspace connection's token expires. Returns null when the desktop* has no usable auth (logged out) — the service treats that as "skip".*/- private async mintWorkspaceConnectToken(workspaceId: string): Promise<string | null> {- const auth = await this.buildWorkspaceHeaders(workspaceId);+ private async mintWorkspaceConnectToken(+ workspaceId: string,+ expectedServerUrl: string,+ ): Promise<string | null> {+ const auth = await this.buildWorkspaceHeaders(workspaceId, expectedServerUrl);if (!auth) return null;const res = await fetch(`${auth.serverUrl}/trpc/lambda/device.mintWorkspaceConnectToken`, {@@ -1396,16 +1427,17 @@ export default class GatewayConnectionCtr extends ControllerModule {/*** Probe whether the workspace-scoped deviceId still has a registered row via- * `device.listDevices`. Returns `false` only on a definitive "row gone"- * answer; `undefined` on any failure — the service must not clear persisted- * enrollments off an inconclusive check.+ * `device.listDevices`, and who enrolled it. `registered: false` is a+ * definitive "row gone" answer; `undefined` on any failure — the service must+ * not clear persisted enrollments off an inconclusive check.*/private async checkWorkspaceDeviceRegistered(workspaceId: string,deviceId: string,- ): Promise<boolean | undefined> {+ expectedServerUrl: string,+ ): Promise<WorkspaceDeviceRegistration | undefined> {try {- const auth = await this.buildWorkspaceHeaders(workspaceId);+ const auth = await this.buildWorkspaceHeaders(workspaceId, expectedServerUrl);if (!auth) return undefined;const res = await fetch(`${auth.serverUrl}/trpc/lambda/device.listDevices`, {@@ -1417,10 +1449,16 @@ export default class GatewayConnectionCtr extends ControllerModule {const devices = payload?.result?.data?.json;if (!Array.isArray(devices)) return undefined;- return devices.some(+ const row = devices.find((d: { deviceId?: unknown; registered?: unknown }) =>d?.deviceId === deviceId && d?.registered === true,- );+ ) as { enroller?: { userId?: unknown } | null } | undefined;+ if (!row) return { registered: false };++ const enrollerUserId = row.enroller?.userId;+ return typeof enrollerUserId === 'string'+ ? { enrollerUserId, registered: true }+ : { registered: true };} catch {return undefined;}diff --git a/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts b/apps/desktop/src/main/controllers/RemoteServerConfigCtr.tsindex 21a3d95aeed..317368c5565 100644--- a/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts+++ b/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts@@ -52,20 +52,17 @@ export default class RemoteServerConfigCtr extends ControllerModule {/*** Normalize legacy config that used local storageMode.* Local mode has been removed; fall back to cloud.+ * Persistence belongs to explicit configuration updates, not reads.*/private normalizeConfig = (config: DataSyncConfig): DataSyncConfig => {// Use type assertion to handle legacy 'local' value from stored dataif ((config.storageMode as string) !== 'local') return config;- const nextConfig: DataSyncConfig = {+ return {...config,remoteServerUrl: config.remoteServerUrl || OFFICIAL_CLOUD_SERVER,storageMode: 'cloud',};-- this.app.storeManager.set('dataSyncConfig', nextConfig);-- return nextConfig;};/**@@ -133,6 +130,17 @@ export default class RemoteServerConfigCtr extends ControllerModule {const merged = this.normalizeConfig({ ...prev, ...config });storeManager.set('dataSyncConfig', merged);+ // The device gateway connection belongs to the login it was opened for.+ // Pointing at another server, or deactivating this one, ends that login:+ // close it and drop whatever was resolved for it before anything reconnects.+ const [prevServerUrl, nextServerUrl] = await Promise.all([+ this.getRemoteServerUrl(prev),+ this.getRemoteServerUrl(merged),+ ]);+ if (prevServerUrl !== nextServerUrl || (prev.active && !merged.active)) {+ await this.app.getService(GatewayConnectionService)?.disconnect();+ }+this.broadcastRemoteServerConfigUpdated();return true;diff --git a/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.tsindex 9475be2c882..fffaca8a3a9 100644--- a/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts@@ -399,6 +399,47 @@ describe('AuthCtr', () => {expect(mockWindow.webContents.send).toHaveBeenCalledWith('authorizationSuccessful');});+ it("replaces the previous login's gateway connection instead of joining it", async () => {+ const gatewaySrv = {+ connect: vi.fn().mockResolvedValue({ success: true }),+ restart: vi.fn().mockResolvedValue({ success: true }),+ };+ vi.mocked(mockApp.getService).mockReturnValue(gatewaySrv as any);+ const tokens = { access_token: 'new-access-token', expires_in: 3600, refresh_token: 'r' };+ mockFetch.mockImplementation((url: string) => {+ const { pathname } = new URL(url);+ if (pathname.includes('/oidc/handoff'))+ return Promise.resolve({+ json: () =>+ Promise.resolve({+ data: { payload: { code: 'mock-auth-code', state: 'mock-random-2' } },+ success: true,+ }),+ ok: true,+ status: 200,+ });+ if (pathname.includes('/oidc/token'))+ return Promise.resolve({+ clone: () => ({ json: () => Promise.resolve(tokens) }),+ ok: true,+ status: 200,+ });+ return Promise.resolve({ ok: false, status: 404 });+ });++ try {+ await authCtr.requestAuthorization({ active: false, storageMode: 'cloud' });+ await vi.advanceTimersByTimeAsync(4000);+ } finally {+ vi.mocked(mockApp.getService).mockReturnValue(null);+ }++ // A still-connected socket of the previous account would otherwise+ // satisfy `connect()` and survive the sign-in.+ expect(gatewaySrv.restart).toHaveBeenCalledTimes(1);+ expect(gatewaySrv.connect).not.toHaveBeenCalled();+ });+it('should validate state parameter and reject mismatched state', async () => {const config: DataSyncConfig = {active: false,diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex f26ea5ae3c5..5cf6fc99f76 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -2,10 +2,12 @@ import type * as ChildProcessModule from 'node:child_process';import type * as CryptoModule from 'node:crypto';import { EventEmitter } from 'node:events';+import type * as DeviceMetricsModule from '@lobechat/device-control/metrics';import { deriveDeviceId, deriveScopedFallbackId } from '@lobechat/device-identity';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';+import type * as DesktopEnvModule from '@/env';import AuvService from '@/services/auvSrv';import GatewayConnectionService from '@/services/gatewayConnectionSrv';import ImessageBridgeService from '@/services/imessageBridgeSrv';@@ -24,9 +26,12 @@ const { ipcMainHandleMock, MockGatewayClient } = vi.hoisted(() => {// Must be defined inside vi.hoisted so it's available when vi.mock factories runclass _MockGatewayClient extends EventEmitter {+ static instances: _MockGatewayClient[] = [];static lastInstance: _MockGatewayClient | null = null;static lastOptions: any = null;+ options: any;+connectionStatus = 'disconnected' as string;currentDeviceId: string;@@ -45,11 +50,16 @@ const { ipcMainHandleMock, MockGatewayClient } = vi.hoisted(() => {constructor(options: any) {super();+ this.options = options;this.currentDeviceId = options.deviceId || 'mock-device-id';+ _MockGatewayClient.instances.push(this);_MockGatewayClient.lastInstance = this;_MockGatewayClient.lastOptions = options;}+ updateToken = vi.fn();+ reconnect = vi.fn(async () => {});+// Test helperssimulateConnected() {this.connectionStatus = 'connected';@@ -229,6 +239,41 @@ vi.mock('@lobechat/device-gateway-client', () => ({GatewayClient: MockGatewayClient,}));+// Logged-in sessions (a JWT with `sub`) start the metrics sampler; keep it inert.+vi.mock('@lobechat/device-control/metrics', async (importOriginal) => ({+ ...(await importOriginal<typeof DeviceMetricsModule>()),+ DeviceMetricsSampler: vi.fn().mockImplementation(function () {+ return {+ flush: vi.fn().mockResolvedValue(undefined),+ start: vi.fn().mockResolvedValue(undefined),+ stop: vi.fn().mockResolvedValue(undefined),+ };+ }),+}));++// `getDesktopEnv` is memoized; read the override per call so a test can stub it.+vi.mock('@/env', async (importOriginal) => {+ const actual = await importOriginal<typeof DesktopEnvModule>();+ return {+ ...actual,+ getDesktopEnv: () => ({+ ...actual.getDesktopEnv(),+ DEVICE_GATEWAY_URL: process.env.DEVICE_GATEWAY_URL || undefined,+ }),+ };+});++// Device gateway discovery goes through Electron's network stack.+const netFetchMock = vi.hoisted(() => vi.fn());+vi.mock('@/utils/net-fetch', () => ({ netFetch: netFetchMock }));++const SERVER_URL = 'https://server.example.com';+const SERVER_GATEWAY_URL = 'https://device-gateway.server.example.com';++/** Answer `config.getGlobalConfig` the way the tRPC lambda router does. */+const globalConfigResponse = (serverConfig: Record<string, unknown>) =>+ Response.json({ result: { data: { json: { serverConfig } } } });+vi.mock('@/services/imessageBridgeSrv', () => ({default: class ImessageBridgeService {},}));@@ -297,6 +342,11 @@ const mockMcpCtr = {const mockRemoteServerConfigCtr = {getAccessToken: vi.fn().mockResolvedValue('mock-access-token'),+ getRemoteServerConfig: vi.fn().mockResolvedValue({+ active: true,+ remoteServerUrl: 'https://server.example.com',+ storageMode: 'selfHost',+ }),getRemoteServerUrl: vi.fn().mockResolvedValue('https://server.example.com'),isRemoteServerConfigured: vi.fn().mockResolvedValue(true),refreshAccessToken: vi.fn().mockResolvedValue({ success: true }),@@ -305,6 +355,7 @@ const mockRemoteServerConfigCtr = {const mockBroadcast = vi.fn();const mockStoreGet = vi.fn();const mockStoreSet = vi.fn();+const mockStoreDelete = vi.fn();const mockApp = {browserManager: { broadcastToAllWindows: mockBroadcast },@@ -322,7 +373,7 @@ const mockApp = {if (Cls === ImessageBridgeService) return mockImessageBridgeSrv;return null;}),- storeManager: { get: mockStoreGet, set: mockStoreSet },+ storeManager: { delete: mockStoreDelete, get: mockStoreGet, set: mockStoreSet },} as unknown as App;// Lazily initialized — created in beforeEach so it uses the current mockApp@@ -355,8 +406,15 @@ describe('GatewayConnectionCtr', () => {}),);executeRemotePlatformMock.mockResolvedValue({ stderr: '', stdout: '' });+ MockGatewayClient.instances = [];MockGatewayClient.lastInstance = null;MockGatewayClient.lastOptions = null;+ netFetchMock.mockImplementation(async () =>+ globalConfigResponse({ deviceGatewayUrl: SERVER_GATEWAY_URL }),+ );+ vi.mocked(mockRemoteServerConfigCtr.getRemoteServerUrl).mockResolvedValue(SERVER_URL);+ vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValue('mock-access-token');+ vi.mocked(mockRemoteServerConfigCtr.refreshAccessToken).mockResolvedValue({ success: true });mockStoreGet.mockImplementation((key: string) => {if (key === 'gatewayEnabled') return true;return undefined;@@ -391,16 +449,18 @@ describe('GatewayConnectionCtr', () => {const options = MockGatewayClient.lastOptions;expect(options).not.toBeNull();expect(options.token).toBe('mock-access-token');+ expect(options.serverUrl).toBe(SERVER_URL);expect(options.deviceId).toBe('stored-device-id');- expect(options.gatewayUrl).toBe('https://device-gateway.lobehub.com');+ expect(options.gatewayUrl).toBe(SERVER_GATEWAY_URL);expect(options.logger).toBeDefined();expect(options.userAgent).toBe('LobeHub Desktop/1.2.3');});- it('should use custom gateway URL from store when set', async () => {+ it('uses the address the server advertises over the official gateway older installs saved', async () => {mockStoreGet.mockImplementation((key: string) => {if (key === 'gatewayEnabled') return true;- if (key === 'gatewayUrl') return 'http://localhost:8787';+ // Older installs persisted the default itself; it is not a choice.+ if (key === 'gatewayUrl') return 'https://device-gateway.lobehub.com';return undefined;});@@ -408,7 +468,15 @@ describe('GatewayConnectionCtr', () => {ctr.afterFirstFrame();await vi.advanceTimersByTimeAsync(0);- expect(MockGatewayClient.lastOptions.gatewayUrl).toBe('http://localhost:8787');+ expect(netFetchMock).toHaveBeenCalledWith(+ `${SERVER_URL}/trpc/lambda/config.getGlobalConfig`,+ expect.objectContaining({ method: 'GET' }),+ );+ // Discovery is public: the login's token is never sent with it.+ expect(JSON.stringify(netFetchMock.mock.calls[0][1].headers)).not.toContain(+ 'mock-access-token',+ );+ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe(SERVER_GATEWAY_URL);});it('should return success:false when no access token', async () => {@@ -420,7 +488,11 @@ describe('GatewayConnectionCtr', () => {vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValueOnce(null);const result = await ctr.connect();- expect(result).toEqual({ error: 'No access token available', success: false });+ expect(result).toEqual({+ error: 'No access token available',+ errorCode: 'not_signed_in',+ success: false,+ });expect(MockGatewayClient.lastInstance).toBeNull();});@@ -520,6 +592,501 @@ describe('GatewayConnectionCtr', () => {});});+ // ─── Device Gateway Discovery ───++ describe('device gateway discovery', () => {+ const OFFICIAL_SERVER_URL = 'https://lobehub.com';+ const OFFICIAL_GATEWAY_URL = 'https://device-gateway.lobehub.com';++ /** Unsigned JWT: the desktop only reads `sub` from it. */+ const jwtFor = (sub: string) =>+ [+ Buffer.from('{"alg":"none"}').toString('base64url'),+ Buffer.from(JSON.stringify({ sub })).toString('base64url'),+ 'sig',+ ].join('.');++ let store: Record<string, unknown>;++ /** A store that remembers writes, seeded with `initial`. */+ const useStore = (initial: Record<string, unknown>) => {+ store = { gatewayDeviceId: 'mock-device-uuid', gatewayEnabled: true, ...initial };+ mockStoreGet.mockImplementation((key: string) => store[key]);+ mockStoreSet.mockImplementation((key: string, value: unknown) => {+ store[key] = value;+ });+ mockStoreDelete.mockImplementation((key: string) => {+ delete store[key];+ });+ };++ const deferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+ };++ const startCtr = async () => {+ ctr = new GatewayConnectionCtr(mockApp);+ ctr.afterFirstFrame();+ await vi.advanceTimersByTimeAsync(0);+ };++ const lastBroadcast = () => {+ const calls = mockBroadcast.mock.calls.filter(+ ([event]) => event === 'gatewayConnectionStatusChanged',+ );+ return calls.at(-1)?.[1];+ };++ const workspaceDeviceId = (workspaceId: string) =>+ deriveDeviceId(`workspace:${workspaceId}`, {+ fallbackId: deriveScopedFallbackId('mock-device-uuid', `workspace:${workspaceId}`),+ }).deviceId;++ beforeEach(() => {+ useStore({});+ });++ it('prefers a custom saved address over the advertised one, without asking', async () => {+ useStore({ gatewayUrl: 'https://gw.self.example' });++ await startCtr();++ expect(netFetchMock).not.toHaveBeenCalled();+ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe('https://gw.self.example');+ expect(await ctr.getGatewayEndpoint()).toEqual({+ endpoint: { source: 'manual', url: 'https://gw.self.example' },+ manualUrl: 'https://gw.self.example',+ serverUrl: SERVER_URL,+ });+ });++ it.each([+ ['an older custom address', 'https://gw.self.example'],+ ['an older official default', OFFICIAL_GATEWAY_URL],+ ['an unusable older address', 'wss://gw.self.example'],+ ])('reads %s without rewriting or deleting it on retries', async (_label, gatewayUrl) => {+ useStore({ gatewayUrl });+ await startCtr();+ await ctr.getGatewayEndpoint();+ await ctr.disconnect();+ await ctr.connect();+ expect(store.gatewayUrl).toBe(gatewayUrl);+ expect(mockStoreSet.mock.calls.map(([key]) => key)).not.toContain('gatewayUrl');+ expect(mockStoreDelete.mock.calls.map(([key]) => key)).not.toContain('gatewayUrl');+ });++ it('keeps using a custom saved address on official cloud too', async () => {+ useStore({ gatewayUrl: 'http://localhost:8788' });+ vi.mocked(mockRemoteServerConfigCtr.getRemoteServerUrl).mockResolvedValue(+ OFFICIAL_SERVER_URL,+ );++ await startCtr();++ expect(netFetchMock).not.toHaveBeenCalled();+ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe('http://localhost:8788');+ });++ it('connects with the saved address while the server config is unreachable', async () => {+ useStore({ gatewayUrl: 'https://gw.self.example' });+ netFetchMock.mockImplementation(async () => {+ throw new TypeError('fetch failed');+ });++ await startCtr();++ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe('https://gw.self.example');+ expect(lastBroadcast()).toEqual({ status: 'connecting' });+ });++ it.each([+ ['nothing saved', {}],+ ['the official gateway saved by an older install', { gatewayUrl: OFFICIAL_GATEWAY_URL }],+ ])("uses this self-hosted server's advertised address with %s", async (_label, saved) => {+ useStore(saved);++ await startCtr();++ expect(netFetchMock).toHaveBeenCalled();+ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe(SERVER_GATEWAY_URL);+ expect((await ctr.getGatewayEndpoint()).endpoint).toEqual({+ source: 'server',+ url: SERVER_GATEWAY_URL,+ });+ });++ it.each([+ ['official cloud', 'https://lobehub.com'],+ ['a self-hosted server', SERVER_URL],+ ])(+ 'uses the official gateway for %s when it answers without an address',+ async (_label, serverUrl) => {+ useStore({ gatewayUrl: OFFICIAL_GATEWAY_URL });+ vi.mocked(mockRemoteServerConfigCtr.getRemoteServerUrl).mockResolvedValue(serverUrl);+ netFetchMock.mockImplementation(async () => globalConfigResponse({}));++ await startCtr();++ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe(OFFICIAL_GATEWAY_URL);+ expect((await ctr.getGatewayEndpoint()).endpoint).toEqual({+ source: 'official',+ url: OFFICIAL_GATEWAY_URL,+ });+ },+ );++ it('reports an unusable saved address instead of discovering around it', async () => {+ useStore({ gatewayUrl: 'wss://gw.self.example' });++ await startCtr();++ expect(netFetchMock).not.toHaveBeenCalled();+ expect(MockGatewayClient.instances).toHaveLength(0);+ expect(lastBroadcast()).toMatchObject({+ error: { code: 'invalid_gateway_url' },+ status: 'disconnected',+ });+ expect(await ctr.getConnectionStatus()).toEqual(lastBroadcast());+ });++ it.each([+ ['an HTTP error', async () => new Response('boom', { status: 500 })],+ ['a tRPC 404', async () => Response.json({ error: { code: -32_004 } }, { status: 404 })],+ ['an HTML page', async () => new Response('<html>login</html>', { status: 200 })],+ [+ 'a network failure',+ async () => {+ throw new TypeError('fetch failed');+ },+ ],+ ])(+ 'reports %s while loading the config instead of using the default',+ async (_label, respond) => {+ useStore({ gatewayUrl: OFFICIAL_GATEWAY_URL });+ netFetchMock.mockImplementation(respond);++ await startCtr();++ expect(MockGatewayClient.instances).toHaveLength(0);+ expect(lastBroadcast()).toMatchObject({+ error: { code: 'config_unavailable' },+ status: 'disconnected',+ });+ },+ );++ it('does not fall back to the official gateway for official cloud when the config read fails', async () => {+ vi.mocked(mockRemoteServerConfigCtr.getRemoteServerUrl).mockResolvedValue(+ OFFICIAL_SERVER_URL,+ );+ netFetchMock.mockImplementation(async () => new Response('down', { status: 503 }));++ await startCtr();++ expect(MockGatewayClient.instances).toHaveLength(0);+ expect(lastBroadcast()?.error?.code).toBe('config_unavailable');+ });++ it.each([+ ['an advertised', { deviceGatewayUrl: SERVER_GATEWAY_URL }, SERVER_GATEWAY_URL],+ ['the default', {}, OFFICIAL_GATEWAY_URL],+ ])(+ 'never writes %s address into the saved setting',+ async (_label, serverConfig, expectedUrl) => {+ netFetchMock.mockImplementation(async () => globalConfigResponse(serverConfig));++ await startCtr();++ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe(expectedUrl);+ expect(mockStoreSet.mock.calls.map(([key]) => key)).not.toContain('gatewayUrl');+ expect(store).not.toHaveProperty('gatewayUrl');+ },+ );++ it('rejects an advertised value that is not a gateway URL', async () => {+ netFetchMock.mockImplementation(async () => globalConfigResponse({ deviceGatewayUrl: null }));++ await startCtr();++ expect(MockGatewayClient.instances).toHaveLength(0);+ expect(lastBroadcast()?.error?.code).toBe('invalid_gateway_url');+ });++ it('keeps the path prefix of an advertised public address', async () => {+ netFetchMock.mockImplementation(async () =>+ globalConfigResponse({ deviceGatewayUrl: 'https://edge.example.com/device-gateway/' }),+ );++ await startCtr();++ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe(+ 'https://edge.example.com/device-gateway',+ );+ });++ it('lets DEVICE_GATEWAY_URL win without depending on the config read', async () => {+ vi.stubEnv('DEVICE_GATEWAY_URL', 'http://localhost:8787');+ useStore({ gatewayUrl: 'https://gw.self.example' });+ netFetchMock.mockImplementation(async () => {+ throw new TypeError('fetch failed');+ });++ await startCtr();++ expect(netFetchMock).not.toHaveBeenCalled();+ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe('http://localhost:8787');+ });++ it('keeps DEVICE_GATEWAY_URL explicit even when it is the official gateway', async () => {+ vi.stubEnv('DEVICE_GATEWAY_URL', OFFICIAL_GATEWAY_URL);++ await startCtr();++ // The server advertises its own gateway, but the env choice stands.+ expect(netFetchMock).not.toHaveBeenCalled();+ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe(OFFICIAL_GATEWAY_URL);+ expect((await ctr.getGatewayEndpoint()).endpoint).toEqual({+ source: 'override',+ url: OFFICIAL_GATEWAY_URL,+ });+ });++ it('discovers the gateway for a deep-link reconnect as well', async () => {+ vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);+ await startCtr();++ await ctr.reconnectFromProtocol({ deviceId: 'mock-device-uuid' });++ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe(SERVER_GATEWAY_URL);+ });++ it('surfaces a gateway auth rejection as a retryable error once the refresh did not help', async () => {+ await startCtr();+ const first = MockGatewayClient.lastInstance!;++ // The first rejection refreshes the token and reconnects to the same gateway.+ first.emit('auth_failed', 'crypto/rsa: verification error');+ first.simulateStatusChanged('disconnected');+ await vi.advanceTimersByTimeAsync(0);+ expect(mockRemoteServerConfigCtr.refreshAccessToken).toHaveBeenCalledTimes(1);+ expect(MockGatewayClient.instances).toHaveLength(2);+ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe(SERVER_GATEWAY_URL);+ expect(lastBroadcast()?.error).toBeUndefined();++ // The refreshed token is rejected too: that is what the user sees.+ const second = MockGatewayClient.lastInstance!;+ second.emit('auth_failed', 'crypto/rsa: verification error');+ second.simulateStatusChanged('disconnected');+ await vi.advanceTimersByTimeAsync(0);++ expect(mockRemoteServerConfigCtr.refreshAccessToken).toHaveBeenCalledTimes(1);+ expect(MockGatewayClient.instances).toHaveLength(2);+ expect(lastBroadcast()).toEqual({+ error: { code: 'auth_failed', detail: 'crypto/rsa: verification error' },+ status: 'disconnected',+ });++ // Retrying clears the reason while it connects again.+ await ctr.connect();+ expect(lastBroadcast()).toEqual({ status: 'connecting' });+ });++ describe('races', () => {+ it('never opens a socket for a config answer that lands after sign-out', async () => {+ const answer = deferred<Response>();+ netFetchMock.mockImplementation(() => answer.promise);++ await startCtr();+ expect(lastBroadcast()).toEqual({ status: 'connecting' });+ const { signal } = netFetchMock.mock.calls[0][1];++ // `clearTokens` on sign-out+ await mockGatewayConnectionSrv.disconnect();+ expect(signal.aborted).toBe(true);++ answer.resolve(globalConfigResponse({ deviceGatewayUrl: SERVER_GATEWAY_URL }));+ await vi.advanceTimersByTimeAsync(0);++ expect(MockGatewayClient.instances).toHaveLength(0);+ expect(lastBroadcast()).toEqual({ status: 'disconnected' });+ });++ it("never sends the new login's token to the previous server's gateway", async () => {+ const answerFromA = deferred<Response>();+ netFetchMock.mockImplementationOnce(() => answerFromA.promise);+ vi.mocked(mockRemoteServerConfigCtr.getRemoteServerUrl).mockResolvedValue(+ 'https://a.example.com',+ );+ vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValue(jwtFor('user-a'));+ await startCtr();++ // Sign in to server B while A's config read is still in flight.+ vi.mocked(mockRemoteServerConfigCtr.getRemoteServerUrl).mockResolvedValue(+ 'https://b.example.com',+ );+ vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValue(jwtFor('user-b'));+ netFetchMock.mockImplementation(async () =>+ globalConfigResponse({ deviceGatewayUrl: 'https://gw.b.example.com' }),+ );+ await mockGatewayConnectionSrv.restart();++ answerFromA.resolve(globalConfigResponse({ deviceGatewayUrl: 'https://gw.a.example.com' }));+ await vi.advanceTimersByTimeAsync(0);++ expect(MockGatewayClient.instances.map((c) => c.options.gatewayUrl)).toEqual([+ 'https://gw.b.example.com',+ ]);+ expect(MockGatewayClient.lastOptions.token).toBe(jwtFor('user-b'));+ });++ it('does not reconnect when signed out during an auth refresh', async () => {+ await startCtr();+ const client = MockGatewayClient.lastInstance!;+ client.simulateConnected();+ const refresh = deferred<{ success: boolean }>();+ vi.mocked(mockRemoteServerConfigCtr.refreshAccessToken).mockReturnValueOnce(+ refresh.promise,+ );++ client.simulateAuthExpired();+ await vi.advanceTimersByTimeAsync(0);+ await mockGatewayConnectionSrv.disconnect();+ refresh.resolve({ success: true });+ await vi.advanceTimersByTimeAsync(0);++ expect(MockGatewayClient.instances).toEqual([client]);+ });++ it('reconnects an auth refresh to the same gateway without re-reading the config', async () => {+ await startCtr();+ const client = MockGatewayClient.lastInstance!;+ client.simulateConnected();++ client.simulateAuthExpired();+ await vi.advanceTimersByTimeAsync(0);++ expect(netFetchMock).toHaveBeenCalledTimes(1);+ expect(MockGatewayClient.instances).toHaveLength(2);+ expect(MockGatewayClient.lastOptions.gatewayUrl).toBe(SERVER_GATEWAY_URL);+ });+ });++ describe('workspace shares', () => {+ const ACCOUNT = `${SERVER_URL}#user-1`;++ /** `device.listDevices` / `device.mintWorkspaceConnectToken` on the server. */+ const serveWorkspaceApi = (enrollers: Record<string, string>) => {+ vi.mocked(fetch).mockImplementation(async (input, init) => {+ const url = String(input);+ const workspaceId = (init?.headers as Record<string, string>)?.['X-Workspace-Id'];+ if (url.endsWith('/device.listDevices')) {+ const enroller = enrollers[workspaceId];+ return Response.json({+ result: {+ data: {+ json: enroller+ ? [+ {+ deviceId: workspaceDeviceId(workspaceId),+ enroller: { userId: enroller },+ registered: true,+ },+ ]+ : [],+ },+ },+ });+ }+ if (url.endsWith('/device.mintWorkspaceConnectToken')) {+ return Response.json({+ result: { data: { json: { token: `ws-token-${workspaceId}` } } },+ });+ }+ return Response.json({ result: { data: { json: null } } });+ });+ };++ const workspaceClients = () =>+ MockGatewayClient.instances.filter((client) => client.options.workspaceId);++ beforeEach(() => {+ vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValue(jwtFor('user-1'));+ });++ it("opens a share on the personal connection's gateway and keeps it for this account", async () => {+ await startCtr();++ await mockGatewayConnectionSrv.enrollWorkspace({ token: 'ws-token', workspaceId: 'ws-1' });++ expect(MockGatewayClient.lastOptions).toMatchObject({+ gatewayUrl: SERVER_GATEWAY_URL,+ serverUrl: SERVER_URL,+ token: 'ws-token',+ workspaceId: 'ws-1',+ });+ expect(store.gatewayWorkspaceEnrollmentsByAccount).toEqual({ [ACCOUNT]: ['ws-1'] });+ });++ it("restores only this account's shares, on the same gateway and server", async () => {+ useStore({+ gatewayWorkspaceEnrollmentsByAccount: {+ [ACCOUNT]: ['ws-own'],+ [`${SERVER_URL}#user-2`]: ['ws-other-account'],+ ['https://other.example.com#user-1']: ['ws-other-server'],+ },+ });+ serveWorkspaceApi({+ 'ws-other-account': 'user-2',+ 'ws-other-server': 'user-1',+ 'ws-own': 'user-1',+ });++ await startCtr();+ await vi.advanceTimersByTimeAsync(0);++ expect(workspaceClients().map((c) => c.options)).toEqual([+ expect.objectContaining({+ gatewayUrl: SERVER_GATEWAY_URL,+ token: 'ws-token-ws-own',+ workspaceId: 'ws-own',+ }),+ ]);+ expect(+ vi.mocked(fetch).mock.calls.every(([url]) => String(url).startsWith(SERVER_URL)),+ ).toBe(true);+ });++ it('adopts a pre-scoping share only when the server shows this account enrolled it', async () => {+ useStore({ gatewayWorkspaceEnrollments: ['ws-mine', 'ws-theirs'] });+ serveWorkspaceApi({ 'ws-mine': 'user-1', 'ws-theirs': 'user-2' });++ await startCtr();+ await vi.advanceTimersByTimeAsync(0);++ expect(workspaceClients().map((c) => c.options.workspaceId)).toEqual(['ws-mine']);+ expect(store.gatewayWorkspaceEnrollmentsByAccount).toEqual({ [ACCOUNT]: ['ws-mine'] });+ // Not ours to restore, and not ours to delete either.+ expect(store.gatewayWorkspaceEnrollments).toEqual(['ws-theirs']);+ });++ it('closes the previous login’s shares when another account signs in', async () => {+ await startCtr();+ await mockGatewayConnectionSrv.enrollWorkspace({ token: 'ws-token', workspaceId: 'ws-1' });+ const [share] = workspaceClients();++ vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValue(jwtFor('user-2'));+ await mockGatewayConnectionSrv.restart();++ expect(share.disconnect).toHaveBeenCalled();+ expect(workspaceClients()).toEqual([share]);+ });+ });+ });+// ─── Disconnect ───describe('disconnect', () => {@@ -1035,6 +1602,7 @@ describe('GatewayConnectionCtr', () => {await vi.advanceTimersByTimeAsync(0);expect(mockBroadcast).toHaveBeenCalledWith('gatewayConnectionStatusChanged', {+ error: { code: 'auth_failed', detail: 'invalid_grant' },status: 'disconnected',});});@@ -1183,9 +1751,9 @@ describe('GatewayConnectionCtr', () => {});it('sends rejected ack when remote server URL is not configured', async () => {- vi.mocked(mockRemoteServerConfigCtr.getRemoteServerUrl).mockResolvedValueOnce('');-const client = await connectAndOpen();+ // After connect, which resolves the server URL for discovery itself.+ vi.mocked(mockRemoteServerConfigCtr.getRemoteServerUrl).mockResolvedValueOnce('');client.simulateAgentRunRequest('openclaw', 'op-fail');await vi.advanceTimersByTimeAsync(0);diff --git a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.tsindex caeee93041c..2db5e695973 100644--- a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts@@ -1,5 +1,5 @@import type { DataSyncConfig } from '@lobechat/electron-client-ipc';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';@@ -108,6 +108,126 @@ describe('RemoteServerConfigCtr', () => {...newConfig,});});++ it('closes the device gateway connection when switching to another server', async () => {+ mockStoreManager.get.mockReturnValue({+ active: true,+ remoteServerUrl: 'https://a.example.com',+ storageMode: 'selfHost',+ });++ await controller.setRemoteServerConfig({+ active: false,+ remoteServerUrl: 'https://b.example.com',+ storageMode: 'selfHost',+ });++ expect(mockGatewayConnectionSrv.disconnect).toHaveBeenCalledTimes(1);+ });++ it('closes the device gateway connection when the login is deactivated', async () => {+ mockStoreManager.get.mockReturnValue({ active: true, storageMode: 'cloud' });++ await controller.setRemoteServerConfig({ active: false });++ expect(mockGatewayConnectionSrv.disconnect).toHaveBeenCalledTimes(1);+ });++ it('keeps the connection when re-activating the same server after sign-in', async () => {+ mockStoreManager.get.mockReturnValue({+ active: false,+ remoteServerUrl: 'https://a.example.com',+ storageMode: 'selfHost',+ });++ await controller.setRemoteServerConfig({ active: true });++ expect(mockGatewayConnectionSrv.disconnect).not.toHaveBeenCalled();+ });+ });++ describe('legacy local configuration', () => {+ let storedConfig: unknown;++ beforeEach(() => {+ storedConfig = { active: false, storageMode: 'local' };+ mockStoreManager.get.mockImplementation((key: string) =>+ key === 'dataSyncConfig' ? structuredClone(storedConfig) : undefined,+ );+ mockStoreManager.set.mockImplementation((key: string, value: unknown) => {+ if (key === 'dataSyncConfig') storedConfig = structuredClone(value);+ });+ });++ afterEach(() => {+ mockStoreManager.get.mockReset();+ mockStoreManager.set.mockReset();+ });++ it('reads legacy configuration as cloud without changing the stored configuration', async () => {+ expect(await controller.getRemoteServerConfig()).toEqual({+ active: false,+ remoteServerUrl: 'https://cloud.lobehub.com',+ storageMode: 'cloud',+ });+ expect(storedConfig).toEqual({ active: false, storageMode: 'local' });+ expect(mockStoreManager.set).not.toHaveBeenCalled();+ });++ it.each([true, false])(+ 'resolves the cloud URL without writing configuration (explicit config: %s)',+ async (explicitConfig) => {+ const config = mockStoreManager.get('dataSyncConfig');+ expect(await controller.getRemoteServerUrl(explicitConfig ? config : undefined)).toBe(+ 'https://cloud.lobehub.com',+ );+ expect(storedConfig).toEqual({ active: false, storageMode: 'local' });+ expect(mockStoreManager.set).not.toHaveBeenCalled();+ },+ );++ it('keeps activation persisted when comparing the previous server URL', async () => {+ expect(await controller.setRemoteServerConfig({ active: true })).toBe(true);++ expect(storedConfig).toEqual({+ active: true,+ remoteServerUrl: 'https://cloud.lobehub.com',+ storageMode: 'cloud',+ });+ expect(mockStoreManager.set).toHaveBeenCalledTimes(1);+ expect(mockGatewayConnectionSrv.disconnect).not.toHaveBeenCalled();+ });++ it('keeps the new self-hosted server persisted and disconnects the previous gateway', async () => {+ expect(+ await controller.setRemoteServerConfig({+ active: true,+ remoteServerUrl: 'https://new.example.com',+ storageMode: 'selfHost',+ }),+ ).toBe(true);++ expect(storedConfig).toEqual({+ active: true,+ remoteServerUrl: 'https://new.example.com',+ storageMode: 'selfHost',+ });+ expect(mockStoreManager.set).toHaveBeenCalledTimes(1);+ expect(mockGatewayConnectionSrv.disconnect).toHaveBeenCalledTimes(1);+ });++ it('keeps deactivation persisted and disconnects the previous gateway', async () => {+ storedConfig = { active: true, storageMode: 'local' };+ expect(await controller.setRemoteServerConfig({ active: false })).toBe(true);++ expect(storedConfig).toEqual({+ active: false,+ remoteServerUrl: 'https://cloud.lobehub.com',+ storageMode: 'cloud',+ });+ expect(mockStoreManager.set).toHaveBeenCalledTimes(1);+ expect(mockGatewayConnectionSrv.disconnect).toHaveBeenCalledTimes(1);+ });});describe('clearRemoteServerConfig', () => {diff --git a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.tsindex 1e4c11b264e..2fa532cd711 100644--- a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts+++ b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts@@ -367,8 +367,19 @@ describe('GatewayConnectionService status broadcast', () => {});describe('GatewayConnectionService auth recovery', () => {+ const SERVER_URL = 'https://server.example.com';+ /** The login a connection belongs to, as `doConnect` binds it. */+ const SESSION = {+ accountKey: `${SERVER_URL}#user-1`,+ endpoint: { source: 'server', url: 'https://gw.example.com' },+ serverKey: SERVER_URL,+ serverUrl: SERVER_URL,+ userId: 'user-1',+ };+let service: GatewayConnectionService;let doConnect: ReturnType<typeof vi.fn>;+ let clients: ReturnType<typeof createFakeClient>[];const createFakeClient = () => {const client = new EventEmitter() as any;@@ -383,6 +394,36 @@ describe('GatewayConnectionService auth recovery', () => {};};+ /** Unsigned JWT: the service only reads `sub` from it. */+ const jwtFor = (sub: string) =>+ [+ Buffer.from('{"alg":"none"}').toString('base64url'),+ Buffer.from(JSON.stringify({ sub })).toString('base64url'),+ 'sig',+ ].join('.');++ const deferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+ };++ /**+ * What a connection attempt leaves behind: a new attempt generation and a+ * fresh client bound to the same login as the current connection.+ */+ const bindClient = () => {+ const client = createFakeClient();+ (service as any).invalidateAttempts();+ (service as any).session = { ...SESSION };+ (service as any).client = client;+ (service as any).setupClientEvents(client);+ clients.push(client);+ return client;+ };+/** Flush the async handlers that the event listeners kick off without awaiting. */const flush = async () => {await new Promise((resolve) => setTimeout(resolve, 0));@@ -392,10 +433,18 @@ describe('GatewayConnectionService auth recovery', () => {beforeEach(() => {const app = {browserManager: { broadcastToAllWindows: vi.fn() },- storeManager: { get: vi.fn((_key: string, fallback?: unknown) => fallback), set: vi.fn() },+ storeManager: {+ delete: vi.fn(),+ 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 });+ clients = [];+ doConnect = vi.fn(async () => {+ bindClient();+ return { success: true };+ });(service as any).doConnect = doConnect;});@@ -403,74 +452,166 @@ describe('GatewayConnectionService auth recovery', () => {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);+ const client = bindClient();client.emit('auth_failed', 'exp claim timestamp check failed');await flush();expect(refresher).toHaveBeenCalledTimes(1);expect(doConnect).toHaveBeenCalledTimes(1);+ expect(client.disconnect).toHaveBeenCalled();+ expect((service as any).client).toBe(clients[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');+ bindClient().emit('auth_failed', 'exp claim timestamp check failed');await flush();- client.emit('auth_failed', 'exp claim timestamp check failed');++ clients[1].emit('auth_failed', 'exp claim timestamp check failed');await flush();expect(refresher).toHaveBeenCalledTimes(1);expect(doConnect).toHaveBeenCalledTimes(1);expect(service.getStatus()).toBe('disconnected');+ // The rejection that ends the recovery is what the user sees.+ expect(service.getDisplayedState()).toEqual({+ error: { code: 'auth_failed', detail: 'exp claim timestamp check failed' },+ status: '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');+ bindClient().emit('auth_failed', 'first');await flush();- client.emit('connected');- client.emit('auth_failed', 'second');++ clients[1].emit('connected');+ clients[1].emit('auth_failed', 'second');await flush();expect(refresher).toHaveBeenCalledTimes(2);expect(doConnect).toHaveBeenCalledTimes(2);});+ it('gives the retry budget back on a user connect', async () => {+ const refresher = vi.fn().mockResolvedValue({ success: true });+ service.setTokenRefresher(refresher);+ bindClient().emit('auth_failed', 'first');+ await flush();+ clients[1].emit('auth_failed', 'again');+ await flush();+ expect(service.getStatus()).toBe('disconnected');++ await service.connect();+ clients[2].emit('auth_failed', 'after the user retried');+ await flush();++ expect(refresher).toHaveBeenCalledTimes(2);+ expect(doConnect).toHaveBeenCalledTimes(3);+ });+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');+ bindClient().emit('auth_failed', 'exp claim timestamp check failed');await flush();expect(refresher).toHaveBeenCalledTimes(1);expect(doConnect).not.toHaveBeenCalled();expect(service.getStatus()).toBe('disconnected');+ expect(service.getDisplayedState().error).toEqual({+ code: 'auth_failed',+ detail: 'invalid_grant',+ });});it('pushes a refreshed token into the live client', () => {- const client = createFakeClient();- (service as any).client = client;+ const client = bindClient();++ service.updatePersonalToken(jwtFor('user-1'));++ expect(client.updateToken).toHaveBeenCalledWith(jwtFor('user-1'));+ });++ it("never pushes another account's token into the live connection", () => {+ const client = bindClient();++ // A new sign-in stores its token before it rebuilds the connection.+ service.updatePersonalToken(jwtFor('user-2'));++ expect(client.updateToken).not.toHaveBeenCalled();+ });++ describe('late events', () => {+ it('ignores an auth_failed that arrives after sign-out', async () => {+ const refresher = vi.fn().mockResolvedValue({ success: true });+ service.setTokenRefresher(refresher);+ const client = bindClient();- service.updatePersonalToken('fresh-token');+ await service.disconnect();+ client.emit('auth_failed', 'late');+ await flush();- expect(client.updateToken).toHaveBeenCalledWith('fresh-token');+ expect(refresher).not.toHaveBeenCalled();+ expect(doConnect).not.toHaveBeenCalled();+ expect(service.getStatus()).toBe('disconnected');+ });++ it('does not reconnect when signed out while the refresh is in flight', async () => {+ const refresh = deferred<{ success: boolean }>();+ service.setTokenRefresher(() => refresh.promise);+ bindClient().emit('auth_failed', 'exp claim timestamp check failed');+ await flush();++ await service.disconnect();+ refresh.resolve({ success: true });+ await flush();++ expect(doConnect).not.toHaveBeenCalled();+ expect((service as any).client).toBeNull();+ });++ it("does not spend the current connection's retry on a replaced client's rejection", async () => {+ const refresher = vi.fn().mockResolvedValue({ success: true });+ service.setTokenRefresher(refresher);+ const replaced = bindClient();+ // A new sign-in replaced the connection before the old verdict landed.+ const current = bindClient();++ replaced.emit('auth_failed', 'late');+ await flush();+ current.emit('auth_failed', 'exp claim timestamp check failed');+ await flush();++ expect(refresher).toHaveBeenCalledTimes(1);+ expect(doConnect).toHaveBeenCalledTimes(1);+ });++ it("does not take a replaced client's late success as the current one's", async () => {+ const refresher = vi.fn().mockResolvedValue({ success: true });+ service.setTokenRefresher(refresher);+ const first = bindClient();+ first.emit('auth_failed', 'first');+ await flush();++ first.emit('connected');+ clients[1].emit('auth_failed', 'rejected again');+ await flush();++ expect(refresher).toHaveBeenCalledTimes(1);+ expect(doConnect).toHaveBeenCalledTimes(1);+ expect(service.getStatus()).toBe('disconnected');+ });});});describe('workspace connection', () => {- const setupWorkspace = (service: GatewayConnectionService, workspaceId: string) => {+ const setupWorkspace = (workspaceId: string) => {+ (service as any).session = { ...SESSION };const client = createFakeClient();(service as any).workspaceClients.set(workspaceId, client);(service as any).setupClientEvents(client, { workspaceId });@@ -478,21 +619,21 @@ describe('GatewayConnectionService auth recovery', () => {};it('re-mints the connect token and reconnects after auth_failed', async () => {- const client = setupWorkspace(service, 'ws-1');+ const client = setupWorkspace('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(mint).toHaveBeenCalledWith('ws-1', SERVER_URL);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 client = setupWorkspace('ws-1');const mint = vi.fn().mockResolvedValue('ws-token');service.setWorkspaceTokenProvider(mint);@@ -506,8 +647,24 @@ describe('GatewayConnectionService auth recovery', () => {expect((service as any).workspaceClients.has('ws-1')).toBe(false);});+ it('gives a share its retry back once it authenticates', async () => {+ const client = setupWorkspace('ws-1');+ const mint = vi.fn().mockResolvedValue('ws-token');+ service.setWorkspaceTokenProvider(mint);++ client.emit('auth_failed', 'first');+ await flush();+ client.emit('connected');+ client.emit('auth_failed', 'second');+ await flush();++ expect(mint).toHaveBeenCalledTimes(2);+ expect(client.reconnect).toHaveBeenCalledTimes(2);+ expect((service as any).workspaceClients.has('ws-1')).toBe(true);+ });+it('closes the share when the connect token cannot be re-minted', async () => {- const client = setupWorkspace(service, 'ws-1');+ const client = setupWorkspace('ws-1');service.setWorkspaceTokenProvider(vi.fn().mockResolvedValue(null));client.emit('auth_failed', 'token expired');@@ -516,6 +673,49 @@ describe('GatewayConnectionService auth recovery', () => {expect(client.reconnect).not.toHaveBeenCalled();expect((service as any).workspaceClients.has('ws-1')).toBe(false);});++ it('ignores an auth_failed from a share already closed by sign-out', async () => {+ const client = setupWorkspace('ws-1');+ const mint = vi.fn().mockResolvedValue('ws-token');+ service.setWorkspaceTokenProvider(mint);++ await service.disconnect();+ client.emit('auth_failed', 'late');+ await flush();++ expect(mint).not.toHaveBeenCalled();+ expect(client.reconnect).not.toHaveBeenCalled();+ });++ it("never closes a re-enrolled share on the replaced client's late rejection", async () => {+ const replaced = setupWorkspace('ws-1');+ service.setWorkspaceTokenProvider(vi.fn().mockResolvedValue('ws-token'));+ replaced.emit('auth_failed', 'first');+ await flush();++ // Re-enrolled: a new client owns the share now.+ const current = setupWorkspace('ws-1');+ replaced.emit('auth_failed', 'late');+ await flush();++ expect((service as any).workspaceClients.get('ws-1')).toBe(current);+ expect(current.disconnect).not.toHaveBeenCalled();+ });++ it('does not re-key a share when signed out during the re-mint', async () => {+ const client = setupWorkspace('ws-1');+ const minted = deferred<string>();+ service.setWorkspaceTokenProvider(() => minted.promise);++ client.emit('auth_failed', 'token expired');+ await flush();+ await service.disconnect();+ minted.resolve('ws-token');+ await flush();++ expect(client.updateToken).not.toHaveBeenCalled();+ expect(client.reconnect).not.toHaveBeenCalled();+ });});});diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.tsindex 6fbdef43cd6..ffd240055d9 100644--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts@@ -19,8 +19,20 @@ import type {ToolCallRequestMessage,ToolCallResponseMessage,} from '@lobechat/device-gateway-client';+import {+ type DeviceGatewayEndpoint,+ type DeviceGatewayResolutionWithDefault,+ deviceGatewayServerKey,+ resolveDeviceGatewayEndpoint,+} from '@lobechat/device-gateway-client/endpoint';import type { DeviceIdentity, IdentitySource } from '@lobechat/device-identity';-import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';+import type {+ GatewayConnectionError,+ GatewayConnectionState,+ GatewayConnectionStatus,+ GatewayConnectResult,+ GatewayEndpointInfo,+} from '@lobechat/electron-client-ipc';import { createRuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';import { app, powerSaveBlocker } from 'electron';@@ -30,13 +42,12 @@ import { createLogger } from '@/utils/logger';import { getDesktopUserAgent } from '@/utils/user-agent';import { safeGetPath } from '@/utils/user-path';+import { discoverDeviceGateway } from './gatewayDiscovery';import { collectBundledCliAgentRuntimes, collectGatewaySystemInfo } from './gatewaySystemInfo';import { ServiceModule } from './index';const logger = createLogger('services:GatewayConnectionSrv');-const DEFAULT_GATEWAY_URL = OFFICIAL_DEVICE_GATEWAY_URL;-/*** The socket drops about once an hour (Cloudflare moving the Durable Object,* edge link resets) and is back within ~2s. A drop that recovers inside this@@ -112,38 +123,93 @@ interface RpcHandler {(method: string, params: unknown): Promise<unknown>;}+/** The server + credential one connection attempt was resolved against. */+interface GatewayAuthContext {+ serverUrl: string;+ token: string;+}+interface DeviceRegistrar {- (info: {- architecture: string;- deviceId: string;- hostname: string;- identitySource: IdentitySource;- metadata: Record<string, string>;- platform: string;- }): Promise<void>;+ (+ info: {+ architecture: string;+ deviceId: string;+ hostname: string;+ identitySource: IdentitySource;+ metadata: Record<string, string>;+ platform: string;+ },+ auth: GatewayAuthContext,+ ): Promise<void>;}/*** Mint a fresh workspace-device connect token for a share connection. Injected- * by the controller (which owns the authed server URL + user token) — used when- * restoring persisted enrollments on startup and when a workspace connection's- * token expires. Returns null when the desktop is not in a state to mint (e.g.- * logged out).+ * by the controller (which owns the authed server calls) — used when restoring+ * persisted enrollments on startup and when a workspace connection's token+ * expires. `serverUrl` is the server the personal connection belongs to: the+ * provider returns null instead of minting on another server (signed out or+ * switched meanwhile).*/interface WorkspaceTokenProvider {- (workspaceId: string): Promise<string | null>;+ (workspaceId: string, serverUrl: string): Promise<string | null>;+}++/** What the server says about this machine's row in a workspace. */+export interface WorkspaceDeviceRegistration {+ /** The member who enrolled the row, when the server reports one. */+ enrollerUserId?: string;+ registered: boolean;}/**- * Check whether the workspace-scoped deviceId still has a registered row on the- * server. Returns `false` only on a definitive "row gone" answer (share revoked- * while offline); `undefined` when the check could not be performed — callers- * must NOT clear local state on `undefined`.+ * Check whether the workspace-scoped deviceId still has a registered row on+ * `serverUrl`. `registered: false` is a definitive "row gone" answer (share+ * revoked while offline); `undefined` means the check could not be performed —+ * callers must NOT clear local state on `undefined`.*/interface WorkspaceDeviceChecker {- (workspaceId: string, deviceId: string): Promise<boolean | undefined>;+ (+ workspaceId: string,+ deviceId: string,+ serverUrl: string,+ ): Promise<WorkspaceDeviceRegistration | undefined>;}+/**+ * The context a personal connection was opened in. Workspace share connections+ * reuse it, so every socket of one session talks to the same gateway on behalf+ * of the same account; anything resolved for an older session is discarded.+ */+interface GatewaySession {+ /** `<serverKey>#<userId>`: scopes persisted workspace enrollments. */+ accountKey?: string;+ endpoint: DeviceGatewayEndpoint;+ serverKey: string;+ serverUrl: string;+ userId: string | null;+}++const CANCELLED: GatewayConnectResult = {+ error: 'Connection attempt was superseded',+ success: false,+};++const describeResolutionFailure = (+ resolution: Extract<DeviceGatewayResolutionWithDefault, { ok: false }>,+): GatewayConnectionError => {+ switch (resolution.reason) {+ case 'discovery_failed': {+ return { code: 'config_unavailable', detail: resolution.detail };+ }+ case 'invalid_advertised_url':+ case 'invalid_manual':+ case 'invalid_override': {+ return { code: 'invalid_gateway_url', detail: resolution.detail };+ }+ }+};+/*** GatewayConnectionService*@@ -157,7 +223,20 @@ export default class GatewayConnectionService extends ServiceModule {private powerSaveBlockerId: number | null = null;/** Status last pushed to renderers; lags `status` during a transient drop. */private displayedStatus: GatewayConnectionStatus = 'disconnected';+ private displayedError: GatewayConnectionError | null = null;private statusBroadcastTimer: ReturnType<typeof setTimeout> | null = null;+ /** Why the last attempt ended; cleared by the next attempt or a disconnect. */+ private connectionError: GatewayConnectionError | null = null;++ /**+ * Bumped by every new connection attempt and every disconnect (sign-out,+ * instance switch). An async step that resumes under an older generation+ * has been superseded and must not open or re-key anything.+ */+ private generation = 0;+ private discoveryAbort: AbortController | null = null;+ private pendingConnect: Promise<GatewayConnectResult> | null = null;+ private session: GatewaySession | null = null;private identitySource: IdentitySource | null = null;private identityCache: { identity: DeviceIdentity; userId: string } | null = null;@@ -169,6 +248,7 @@ export default class GatewayConnectionService extends ServiceModule {*/private readonly agentRuntimes = createRuntimeProbeCache(collectBundledCliAgentRuntimes);+ private serverUrlProvider: (() => Promise<string | undefined>) | null = null;private tokenProvider: (() => Promise<string | null>) | null = null;private tokenRefresher: (() => Promise<{ error?: string; success: boolean }>) | null = null;private toolCallHandler: ToolCallHandler | null = null;@@ -184,8 +264,8 @@ export default class GatewayConnectionService extends ServiceModule {/** Live workspace-share connections, keyed by workspaceId. */private workspaceClients = new Map<string, GatewayClient>();- /** Serializes enrollment restores so reconnect churn can't double-open sockets. */- private workspaceRestoreInFlight = false;+ /** Serializes enrollment restores per session so reconnect churn can't double-open sockets. */+ private workspaceRestoreFor: GatewaySession | null = null;/*** Set once an `auth_failed` has already triggered a token refresh for the* current personal connection. Unlike `auth_expired`, `auth_failed` is@@ -205,7 +285,18 @@ export default class GatewayConnectionService extends ServiceModule {// ─── Configuration ───- /** Set token provider function (to decouple from RemoteServerConfigCtr) */+ /**+ * The server the desktop is signed in to. Read together with the token at the+ * start of every attempt, so discovery, the gateway and the credential all+ * belong to one login.+ */+ setServerUrlProvider(provider: () => Promise<string | undefined>) {+ this.serverUrlProvider = provider;+ }++ /**+ * Set token provider function (to decouple from RemoteServerConfigCtr)+ */setTokenProvider(provider: () => Promise<string | null>) {this.tokenProvider = provider;}@@ -224,9 +315,16 @@ export default class GatewayConnectionService extends ServiceModule {* 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.+ *+ * Only a token for the account this connection belongs to is taken: a new+ * sign-in also stores its token here first, and the sign-in itself rebuilds+ * the connection for its own server.*/updatePersonalToken(token: string) {- this.client?.updateToken(token);+ const session = this.session;+ if (!this.client || !session) return;+ if (this.extractUserIdFromToken(token) !== session.userId) return;+ this.client.updateToken(token);}/**@@ -263,8 +361,8 @@ export default class GatewayConnectionService extends ServiceModule {/*** Persist this device to the server's device registry. Called on every- * connect once the userId is known (deviceId is user-scoped). Injected by the- * controller, which owns the authed server URL + token.+ * connect once the userId is known (deviceId is user-scoped), with the server+ * and token of that attempt so the row lands where the socket authenticates.*/setDeviceRegistrar(registrar: DeviceRegistrar) {this.deviceRegistrar = registrar;@@ -358,6 +456,13 @@ export default class GatewayConnectionService extends ServiceModule {return this.displayedStatus;}+ /** What the UI shows: the displayed status plus why the last attempt ended. */+ getDisplayedState(): GatewayConnectionState {+ return this.displayedError+ ? { error: this.displayedError, status: this.displayedStatus }+ : { status: this.displayedStatus };+ }+getDeviceInfo() {return {deviceId: this.getDeviceId(),@@ -375,9 +480,25 @@ export default class GatewayConnectionService extends ServiceModule {*/async matchesDeviceId(deviceId: string): Promise<boolean> {if (this.getDeviceId() === deviceId) return true;- if ((await this.resolveCurrentDeviceId()) === deviceId) return true;- for (const workspaceId of this.getPersistedWorkspaceEnrollments()) {+ const [serverUrl, token] = await Promise.all([+ this.serverUrlProvider?.(),+ this.tokenProvider?.(),+ ]);+ const userId = token ? this.extractUserIdFromToken(token) : undefined;+ if (userId) {+ const identity = await this.resolveDeviceIdentity(userId);+ if (identity.deviceId === deviceId) return true;+ }++ // Workspace identities are per machine, so a pre-scoping record still+ // identifies this computer; whether it is restored is decided on connect.+ const accountKey = this.toAccountKey(serverUrl, userId);+ const workspaceIds = new Set([+ ...(accountKey ? this.getPersistedWorkspaceEnrollments(accountKey) : []),+ ...this.getLegacyWorkspaceEnrollments(),+ ]);+ for (const workspaceId of workspaceIds) {const identity = await this.resolveWorkspaceDeviceIdentity(workspaceId);if (identity.deviceId === deviceId) return true;}@@ -387,88 +508,202 @@ export default class GatewayConnectionService extends ServiceModule {// ─── Connection Logic ───- async connect(): Promise<{ error?: string; success: boolean }> {+ /**+ * Start (or join) a connection for the current login. Startup auto-connect,+ * post-login connect, the toggle, deep-link reconnects and the auth refresh+ * all come through here, so they share discovery and the generation guard.+ */+ async connect(): Promise<GatewayConnectResult> {+ if (this.pendingConnect) return this.pendingConnect;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();+ return this.startConnect();+ }++ /**+ * Drop everything bound to the previous login and connect afresh. Used after+ * a new sign-in, which may be another account or another server.+ */+ async restart(): Promise<GatewayConnectResult> {+ await this.disconnect();+ // A sign-in is a user-initiated connect: it gets a fresh auth_failed budget.+ this.authRecoveryAttempted = false;+ return this.startConnect();}+ /**+ * Close the personal and every workspace connection and invalidate whatever+ * was resolved for them: in-flight discovery is aborted and any attempt still+ * running resumes as stale, so a late answer can never reopen a socket — let+ * alone send this login's token to the previous server's gateway.+ */async disconnect(): Promise<{ success: boolean }> {+ this.invalidateAttempts();+ this.session = null;+ this.connectionError = null;+// A user-initiated disconnect turns the device off, so stop sampling too —// the page then shows no data rather than "running but unreachable". The// samples since the last upload are pushed first (bounded), while the// socket is still open.await this.stopMetricsSampler({ flushTimeoutMs: 3000 });- if (this.client) {- await this.client.disconnect();- this.client = null;- }+ const client = this.client;+ this.client = null;+ await client?.disconnect();// Take the workspace share connections down with the personal one (the// device goes fully offline), but keep the persisted enrollments — the next// connect restores them.- for (const workspaceId of this.workspaceClients.keys()) {- await this.closeWorkspaceClient(workspaceId);- }+ await this.closeAllWorkspaceClients();this.setStatus('disconnected');+ this.scheduleStatusBroadcast(this.status);return { success: true };}- private async doConnect(): Promise<{ error?: string; success: boolean }> {+ private startConnect(options?: { reuse?: GatewaySession }): Promise<GatewayConnectResult> {+ const attempt = this.doConnect(options).finally(() => {+ if (this.pendingConnect === attempt) this.pendingConnect = null;+ });+ this.pendingConnect = attempt;+ return attempt;+ }++ private invalidateAttempts(): number {+ this.generation += 1;+ this.discoveryAbort?.abort();+ this.discoveryAbort = null;+ this.pendingConnect = null;+ return this.generation;+ }++ private isStale(generation: number) {+ return generation !== this.generation;+ }++ /**+ * @param options.reuse Session of a connection being re-established (auth+ * refresh). Its endpoint is kept when the login is unchanged, like the+ * client's own short reconnects; a different server or account resolves+ * again.+ */+ private async doConnect({+ reuse,+ }: { reuse?: GatewaySession } = {}): Promise<GatewayConnectResult> {+ const generation = this.invalidateAttempts();+// Clean up any existing clientif (this.client) {- await this.client.disconnect();+ const previous = this.client;this.client = null;+ await previous.disconnect();}+ if (this.isStale(generation)) return CANCELLED;++ // Loading the server's config is part of connecting.+ this.connectionError = null;+ this.setStatus('connecting');- if (!this.tokenProvider) {+ if (!this.tokenProvider || !this.serverUrlProvider) {logger.warn('Cannot connect: no token provider configured');- return { error: 'No token provider configured', success: false };+ return this.failConnect(+ generation,+ { code: 'not_signed_in' },+ 'No token provider configured',+ );}- const token = await this.tokenProvider();+ const [serverUrl, token] = await Promise.all([this.serverUrlProvider(), this.tokenProvider()]);+ if (this.isStale(generation)) return CANCELLED;+if (!token) {logger.warn('Cannot connect: no access token');- return { error: 'No access token available', success: false };+ return this.failConnect(generation, { code: 'not_signed_in' }, 'No access token available');+ }++ const serverKey = serverUrl ? deviceGatewayServerKey(serverUrl) : undefined;+ if (!serverUrl || !serverKey) {+ logger.warn('Cannot connect: no remote server configured');+ return this.failConnect(generation, { code: 'not_signed_in' }, 'No remote server configured');}- const gatewayUrl = this.getGatewayUrl();const userId = this.extractUserIdFromToken(token);- logger.info(`Connecting to device gateway: ${gatewayUrl}, userId: ${userId || 'unknown'}`);+ const endpoint: DeviceGatewayResolutionWithDefault =+ reuse && reuse.serverKey === serverKey && reuse.userId === userId+ ? { endpoint: reuse.endpoint, ok: true }+ : await this.resolveEndpoint(serverUrl);+ if (this.isStale(generation)) return CANCELLED;++ // `in`, not `ok`: this project compiles without strictNullChecks, where a+ // boolean discriminant does not narrow.+ if ('reason' in endpoint) {+ const error = describeResolutionFailure(endpoint);+ logger.warn(+ `Cannot connect: device gateway for ${serverUrl} unresolved (${endpoint.reason}${endpoint.detail ? `: ${endpoint.detail}` : ''})`,+ );+ return this.failConnect(generation, error, `Device gateway unavailable: ${endpoint.reason}`);+ }++ const { url: gatewayUrl, source } = endpoint.endpoint;+ logger.info(+ `Connecting to device gateway: ${gatewayUrl} (${source}), server: ${serverUrl}, userId: ${userId || 'unknown'}`,+ );++ const session: GatewaySession = {+ accountKey: this.toAccountKey(serverUrl, userId),+ endpoint: endpoint.endpoint,+ serverKey,+ serverUrl,+ userId,+ };+ // Share connections are only kept across a reconnect of the same login to+ // the same gateway; anything else belongs to the previous session.+ if (this.session && !this.isSameSession(this.session, session)) {+ await this.closeAllWorkspaceClients();+ if (this.isStale(generation)) return CANCELLED;+ }+ this.session = session;// Resolve the stable, user-scoped device id and register with the server// registry before opening the WS, so the device row exists by the time the// gateway reports it online.if (userId) {const identity = await this.resolveDeviceIdentity(userId);- await this.deviceRegistrar?.({- architecture: os.arch(),- deviceId: identity.deviceId,- hostname: os.hostname(),- identitySource: identity.identitySource,- metadata: {- appVersion: app.getVersion(),- electron: process.versions.electron,- node: process.versions.node,- osRelease: os.release(),+ if (this.isStale(generation)) return CANCELLED;+ await this.deviceRegistrar?.(+ {+ architecture: os.arch(),+ deviceId: identity.deviceId,+ hostname: os.hostname(),+ identitySource: identity.identitySource,+ metadata: {+ appVersion: app.getVersion(),+ electron: process.versions.electron,+ node: process.versions.node,+ osRelease: os.release(),+ },+ platform: process.platform,},- platform: process.platform,- }).catch((err) => {+ { serverUrl, token },+ ).catch((err) => {logger.warn(`Device registration failed (non-fatal): ${(err as Error).message}`);});+ if (this.isStale(generation)) return CANCELLED;await this.startMetricsSampler(identity.deviceId);}const { GatewayClient } = await import('@lobechat/device-gateway-client');+ if (this.isStale(generation)) return CANCELLED;+const client = new GatewayClient({channel: isDev ? 'desktop-dev' : 'desktop',connectionId: this.getConnectionId(),deviceId: this.getDeviceId(),gatewayUrl,logger,+ serverUrl: session.serverUrl,token,userAgent: getDesktopUserAgent(),userId: userId || undefined,@@ -482,13 +717,27 @@ export default class GatewayConnectionService extends ServiceModule {// Re-open persisted workspace share connections once the personal// connection is up. Fire-and-forget: restore failures must never block or// fail the personal connect.- void this.restoreWorkspaceEnrollments().catch((err) => {+ void this.restoreWorkspaceEnrollments(session).catch((err) => {logger.warn('Workspace enrollment restore failed (non-fatal):', err);});return { success: true };}+ private failConnect(+ generation: number,+ error: GatewayConnectionError,+ message: string,+ ): GatewayConnectResult {+ if (this.isStale(generation)) return CANCELLED;+ this.connectionError = error;+ this.setStatus('disconnected');+ // The status may not have changed (e.g. failing before any socket), but+ // the reason did.+ this.scheduleStatusBroadcast(this.status);+ return { error: message, errorCode: error.code, success: false };+ }+/*** Bind the shared request handlers. All request routing (tool calls / RPCs /* agent runs / system info) is identical for the personal connection and a@@ -502,8 +751,10 @@ export default class GatewayConnectionService extends ServiceModule {logger.info(`Workspace ${scope.workspaceId} connection status: ${status}`);});} else {+ // A replaced client still reports its own teardown; only the current one+ // speaks for the device.client.on('status_changed', (status) => {- this.setStatus(status);+ if (this.client === client) this.setStatus(status);});}@@ -530,27 +781,28 @@ export default class GatewayConnectionService extends ServiceModule {client.on('auth_expired', () => {if (scope) {logger.warn(`Workspace ${scope.workspaceId} connect token expired, re-minting`);- void this.handleWorkspaceAuthExpired(scope.workspaceId);+ void this.handleWorkspaceAuthExpired(scope.workspaceId, client);} else {logger.warn('Received auth_expired, will reconnect with refreshed token');- void this.handleAuthExpired();+ void this.handleAuthExpired(client);}});client.on('auth_failed', (reason) => {if (scope) {- void this.handleWorkspaceAuthFailed(scope.workspaceId, reason);+ void this.handleWorkspaceAuthFailed(scope.workspaceId, client, reason);} else {- void this.handleAuthFailed(reason);+ void this.handleAuthFailed(client, 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.+ // retry guards: the next rejection gets a fresh single retry. A replaced+ // client's late success says nothing about the current one.if (scope) {this.workspaceAuthRetried.delete(client);- } else {+ } else if (this.client === client) {this.authRecoveryAttempted = false;}});@@ -586,8 +838,14 @@ export default class GatewayConnectionService extends ServiceModule {// existing enrollment (and ask for overwrite confirmation) without this// machine opening or persisting anything.if (params.identityOnly) return this.resolveWorkspaceDeviceIdentity(params.workspaceId);- const identity = await this.openWorkspaceClient(params.workspaceId, params.token);- this.persistWorkspaceEnrollment(params.workspaceId);++ // The RPC arrives over the personal connection, so the share joins its+ // session: same gateway, persisted for the same account.+ const session = this.session;+ if (!session) throw new Error('Device gateway is not connected');++ const identity = await this.openWorkspaceClient(params.workspaceId, params.token, session);+ if (session.accountKey) this.persistWorkspaceEnrollment(session.accountKey, params.workspaceId);logger.info(`Enrolled into workspace ${params.workspaceId} as device ${identity.deviceId}`);return identity;}@@ -599,7 +857,12 @@ export default class GatewayConnectionService extends ServiceModule {*/async unenrollWorkspace(params: UnenrollWorkspaceParams): Promise<{ success: boolean }> {await this.closeWorkspaceClient(params.workspaceId);- this.removePersistedWorkspaceEnrollment(params.workspaceId);+ if (this.session?.accountKey) {+ this.removePersistedWorkspaceEnrollment(this.session.accountKey, params.workspaceId);+ }+ // The workspace identity is per machine, so a revoke also settles a+ // pre-scoping record of the same workspace.+ this.removeLegacyWorkspaceEnrollment(params.workspaceId);logger.info(`Unenrolled from workspace ${params.workspaceId}`);return { success: true };}@@ -631,6 +894,7 @@ export default class GatewayConnectionService extends ServiceModule {private async openWorkspaceClient(workspaceId: string,token: string,+ session: GatewaySession,): Promise<EnrollWorkspaceResult> {// Re-enroll replaces the previous share connection instead of stacking one.await this.closeWorkspaceClient(workspaceId);@@ -638,6 +902,10 @@ export default class GatewayConnectionService extends ServiceModule {const identity = await this.resolveWorkspaceDeviceIdentity(workspaceId);const { GatewayClient } = await import('@lobechat/device-gateway-client');+ if (!this.isCurrentSession(session)) {+ throw new Error('Device gateway session changed while opening the share connection');+ }+const client = new GatewayClient({channel: isDev ? 'desktop-dev' : 'desktop',// Reuse the install's connectionId: the gateway dedupes stale sockets per@@ -645,8 +913,9 @@ export default class GatewayConnectionService extends ServiceModule {// predecessor, never the personal socket.connectionId: this.getConnectionId(),deviceId: identity.deviceId,- gatewayUrl: this.getGatewayUrl(),+ gatewayUrl: session.endpoint.url,logger,+ serverUrl: session.serverUrl,token,userAgent: getDesktopUserAgent(),userId: undefined,@@ -667,6 +936,12 @@ export default class GatewayConnectionService extends ServiceModule {await client.disconnect();}+ private async closeAllWorkspaceClients() {+ for (const workspaceId of this.workspaceClients.keys()) {+ await this.closeWorkspaceClient(workspaceId);+ }+ }+/*** Workspace share connections authenticate with a short-lived minted token,* not the user token — on expiry, re-mint via the injected provider and@@ -674,18 +949,23 @@ export default class GatewayConnectionService extends ServiceModule {* closes the socket but keeps the persisted enrollment: the next startup's* restore path settles it against the server row.*/- private async handleWorkspaceAuthExpired(workspaceId: string) {- const client = this.workspaceClients.get(workspaceId);- if (!client) return;+ private async handleWorkspaceAuthExpired(workspaceId: string, client: GatewayClient) {+ const session = this.session;+ if (!session || this.workspaceClients.get(workspaceId) !== client) return;try {- const token = await this.workspaceTokenProvider?.(workspaceId);+ const token = await this.workspaceTokenProvider?.(workspaceId, session.serverUrl);+ // Signed out, switched server or replaced meanwhile: nothing to re-key.+ if (!this.isCurrentSession(session) || this.workspaceClients.get(workspaceId) !== client)+ return;if (!token) throw new Error('no workspace connect token available');client.updateToken(token);await client.reconnect();} catch (error) {logger.warn(`Workspace ${workspaceId} token re-mint failed, closing share:`, error);- await this.closeWorkspaceClient(workspaceId);+ if (this.workspaceClients.get(workspaceId) === client) {+ await this.closeWorkspaceClient(workspaceId);+ }}}@@ -697,9 +977,13 @@ export default class GatewayConnectionService extends ServiceModule {* 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;+ private async handleWorkspaceAuthFailed(+ workspaceId: string,+ client: GatewayClient,+ reason: string,+ ) {+ // Closed, replaced or signed out meanwhile: not this share's verdict.+ if (this.workspaceClients.get(workspaceId) !== client) return;if (this.workspaceAuthRetried.has(client)) {logger.warn(@@ -713,44 +997,80 @@ export default class GatewayConnectionService extends ServiceModule {logger.warn(`Workspace ${workspaceId} authentication failed (${reason}), re-minting connect token`,);- await this.handleWorkspaceAuthExpired(workspaceId);+ await this.handleWorkspaceAuthExpired(workspaceId, client);}/**- * Re-open share connections persisted by a previous run. Before reconnecting,- * confirm the derived workspace deviceId still has a registered row — the- * share may have been revoked while the app was offline (the server can't- * deliver `unenrollWorkspace` to a dead socket), and reconnecting anyway- * would resurrect the device as a ghost in the workspace pool.+ * Re-open the share connections this account persisted in a previous run.+ * Before reconnecting, confirm the derived workspace deviceId still has a+ * registered row — the share may have been revoked while the app was offline+ * (the server can't deliver `unenrollWorkspace` to a dead socket), and+ * reconnecting anyway would resurrect the device as a ghost in the workspace+ * pool.+ *+ * Records from before enrollments were scoped carry no account. One is+ * adopted only when the server shows the signed-in user enrolled that row;+ * otherwise it is left alone, so another account's share is never reopened+ * under this login.*/- private async restoreWorkspaceEnrollments() {- if (this.workspaceRestoreInFlight) return;- this.workspaceRestoreInFlight = true;+ private async restoreWorkspaceEnrollments(session: GatewaySession) {+ const { accountKey } = session;+ if (!accountKey) return;+ if (this.workspaceRestoreFor && this.isSameSession(this.workspaceRestoreFor, session)) return;+ this.workspaceRestoreFor = session;try {- for (const workspaceId of this.getPersistedWorkspaceEnrollments()) {+ const owned = this.getPersistedWorkspaceEnrollments(accountKey);+ const candidates = [+ ...owned.map((workspaceId) => ({ legacy: false, workspaceId })),+ ...this.getLegacyWorkspaceEnrollments()+ .filter((workspaceId) => !owned.includes(workspaceId))+ .map((workspaceId) => ({ legacy: true, workspaceId })),+ ];++ for (const { legacy, workspaceId } of candidates) {+ if (!this.isCurrentSession(session)) return;// Already live (e.g. personal reconnect after auth refresh) — leave it.if (this.workspaceClients.has(workspaceId)) continue;try {const identity = await this.resolveWorkspaceDeviceIdentity(workspaceId);- const registered = await this.workspaceDeviceChecker?.(workspaceId, identity.deviceId);- if (registered === false) {+ const registration = await this.workspaceDeviceChecker?.(+ workspaceId,+ identity.deviceId,+ session.serverUrl,+ );+ if (!this.isCurrentSession(session)) return;++ if (legacy) {+ if (+ !registration?.registered ||+ !session.userId ||+ registration.enrollerUserId !== session.userId+ ) {+ logger.info(+ `Workspace share ${workspaceId} predates account scoping and is not this account's, leaving it untouched`,+ );+ continue;+ }+ this.adoptLegacyWorkspaceEnrollment(accountKey, workspaceId);+ } else if (registration?.registered === false) {logger.info(`Workspace share ${workspaceId} was revoked while offline, clearing local enrollment`,);- this.removePersistedWorkspaceEnrollment(workspaceId);+ this.removePersistedWorkspaceEnrollment(accountKey, workspaceId);continue;}- const token = await this.workspaceTokenProvider?.(workspaceId);+ const token = await this.workspaceTokenProvider?.(workspaceId, session.serverUrl);+ if (!this.isCurrentSession(session)) return;if (!token) {logger.warn(`No connect token for workspace ${workspaceId}, skipping restore`);continue;}- await this.openWorkspaceClient(workspaceId, token);+ await this.openWorkspaceClient(workspaceId, token, session);logger.info(`Restored workspace share connection: ${workspaceId}`);} catch (error) {// Degraded by design: keep the record and retry on the next connect@@ -759,45 +1079,86 @@ export default class GatewayConnectionService extends ServiceModule {}}} finally {- this.workspaceRestoreInFlight = false;+ if (this.workspaceRestoreFor === session) this.workspaceRestoreFor = null;}}// ─── Workspace Enrollment Persistence ───- private getPersistedWorkspaceEnrollments(): string[] {- const stored = this.app.storeManager.get('gatewayWorkspaceEnrollments') as string[] | undefined;+ private toAccountKey(serverUrl: string | undefined, userId: string | null | undefined) {+ const serverKey = serverUrl ? deviceGatewayServerKey(serverUrl) : undefined;+ return serverKey && userId ? `${serverKey}#${userId}` : undefined;+ }++ private getEnrollmentsByAccount(): Record<string, string[]> {+ const stored = this.app.storeManager.get('gatewayWorkspaceEnrollmentsByAccount');+ return stored && typeof stored === 'object' ? stored : {};+ }++ private getPersistedWorkspaceEnrollments(accountKey: string): string[] {+ const stored = this.getEnrollmentsByAccount()[accountKey];return Array.isArray(stored) ? stored.filter((id) => typeof id === 'string') : [];}- private persistWorkspaceEnrollment(workspaceId: string) {- const current = this.getPersistedWorkspaceEnrollments();+ private setPersistedWorkspaceEnrollments(accountKey: string, workspaceIds: string[]) {+ const { [accountKey]: _previous, ...rest } = this.getEnrollmentsByAccount();+ this.app.storeManager.set(+ 'gatewayWorkspaceEnrollmentsByAccount',+ workspaceIds.length > 0 ? { ...rest, [accountKey]: workspaceIds } : rest,+ );+ }++ private persistWorkspaceEnrollment(accountKey: string, workspaceId: string) {+ const current = this.getPersistedWorkspaceEnrollments(accountKey);if (current.includes(workspaceId)) return;- this.app.storeManager.set('gatewayWorkspaceEnrollments', [...current, workspaceId]);+ this.setPersistedWorkspaceEnrollments(accountKey, [...current, workspaceId]);}- private removePersistedWorkspaceEnrollment(workspaceId: string) {- const current = this.getPersistedWorkspaceEnrollments();+ private removePersistedWorkspaceEnrollment(accountKey: string, workspaceId: string) {+ const current = this.getPersistedWorkspaceEnrollments(accountKey);if (!current.includes(workspaceId)) return;- this.app.storeManager.set(- 'gatewayWorkspaceEnrollments',+ this.setPersistedWorkspaceEnrollments(+ accountKey,current.filter((id) => id !== workspaceId),);}+ private getLegacyWorkspaceEnrollments(): string[] {+ const stored = this.app.storeManager.get('gatewayWorkspaceEnrollments');+ return Array.isArray(stored) ? stored.filter((id) => typeof id === 'string') : [];+ }++ private removeLegacyWorkspaceEnrollment(workspaceId: string) {+ const current = this.getLegacyWorkspaceEnrollments();+ if (!current.includes(workspaceId)) return;+ const rest = current.filter((id) => id !== workspaceId);+ if (rest.length > 0) this.app.storeManager.set('gatewayWorkspaceEnrollments', rest);+ else this.app.storeManager.delete('gatewayWorkspaceEnrollments');+ }++ /** Move a pre-scoping record to the account the server confirmed owns it. */+ private adoptLegacyWorkspaceEnrollment(accountKey: string, workspaceId: string) {+ this.persistWorkspaceEnrollment(accountKey, workspaceId);+ this.removeLegacyWorkspaceEnrollment(workspaceId);+ }+// ─── Auth Expired / Failed Handling ───/**- * 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.+ * Refresh the user token and rebuild the personal connection for the same+ * login. A failed refresh settles on `disconnected` with the reason and waits+ * for the next user action or app start.*/- private async refreshTokenAndReconnect() {- // Disconnect the current client- if (this.client) {- await this.client.disconnect();- this.client = null;- }+ private async handleAuthExpired(client: GatewayClient) {+ if (this.client !== client) return;+ const generation = this.generation;+ const session = this.session;++ // Retire the expired client; its own teardown no longer speaks for the+ // device, which is reconnecting (a quick refresh stays hidden in the UI).+ this.client = null;+ this.setStatus('reconnecting');+ await client.disconnect();if (!this.tokenRefresher) {logger.error('No token refresher configured, cannot refresh the access token');@@ -807,20 +1168,20 @@ export default class GatewayConnectionService extends ServiceModule {logger.info('Attempting token refresh before reconnect');const result = await this.tokenRefresher();+ // Signed out, switched server or reconnected meanwhile: that path owns the+ // connection now.+ if (this.isStale(generation)) return;if (result.success) {logger.info('Token refreshed, reconnecting');- await this.doConnect();+ await this.startConnect({ reuse: session ?? undefined });} else {logger.error('Token refresh failed:', result.error);+ this.connectionError = { code: 'auth_failed', detail: result.error };this.setStatus('disconnected');}}- 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@@ -830,20 +1191,39 @@ export default class GatewayConnectionService extends ServiceModule {* 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.+ * that yields another rejected token (revoked grant, clock skew) from+ * looping; that second rejection is surfaced as a retryable error.*/- private async handleAuthFailed(reason: string) {+ private async handleAuthFailed(client: GatewayClient, reason: string) {+ // A replaced or signed-out client's late verdict: not this connection's.+ if (this.client !== client) return;+ logger.warn(`Device gateway rejected the credential: ${reason}`);+if (this.authRecoveryAttempted) {logger.error(`Authentication failed again after a token refresh (${reason}); staying disconnected until the next connect`,);+ this.connectionError = { code: 'auth_failed', detail: reason };this.setStatus('disconnected');return;}this.authRecoveryAttempted = true;- logger.warn(`Authentication failed: ${reason}. Attempting token refresh before reconnect...`);- await this.refreshTokenAndReconnect();+ logger.warn('Attempting token refresh before reconnect...');+ await this.handleAuthExpired(client);+ }++ private isSameSession(a: GatewaySession, b: GatewaySession) {+ return (+ a.serverKey === b.serverKey &&+ a.accountKey === b.accountKey &&+ a.endpoint.url === b.endpoint.url+ );+ }++ /** Whether work started for `session` may still act on the live connection. */+ private isCurrentSession(session: GatewaySession) {+ return this.session !== null && this.isSameSession(this.session, session);}// ─── System Info ───@@ -1172,21 +1552,69 @@ export default class GatewayConnectionService extends ServiceModule {}private broadcastStatus(status: GatewayConnectionStatus) {- if (this.displayedStatus === status) return;+ // The reason only means something once the attempt has ended.+ const error = status === 'disconnected' ? this.connectionError : null;+ if (this.displayedStatus === status && this.displayedError === error) return;this.displayedStatus = status;- this.app.browserManager.broadcastToAllWindows('gatewayConnectionStatusChanged', { status });+ this.displayedError = error;+ this.app.browserManager.broadcastToAllWindows(+ 'gatewayConnectionStatusChanged',+ this.getDisplayedState(),+ );}- // ─── Gateway URL ───+ // ─── Gateway Address ───- private getGatewayUrl(): string {- // Env override wins (dev: point at a local `wrangler dev` gateway), then the- // user-configured store value, then the production default.- return (- getDesktopEnv().DEVICE_GATEWAY_URL ||- this.app.storeManager.get('gatewayUrl') ||- DEFAULT_GATEWAY_URL- );+ /**+ * Resolve the gateway for `serverUrl`, first match wins:+ * 1. `DEVICE_GATEWAY_URL` (dev: a local `wrangler dev` gateway), whatever+ * its value+ * 2. the address saved in settings (`gatewayUrl`), unless it is the official+ * gateway itself+ * 3. the address this server advertises+ * 4. the official gateway, when the server answered without one+ * The server is asked only for 3–4. A failed discovery is reported, never+ * replaced by the default: that would send this server's token elsewhere.+ */+ private async resolveEndpoint(serverUrl: string): Promise<DeviceGatewayResolutionWithDefault> {+ const controller = new AbortController();+ this.discoveryAbort = controller;+ try {+ return await resolveDeviceGatewayEndpoint({+ discover: () => discoverDeviceGateway(serverUrl, controller.signal),+ manualUrl: this.getSavedGatewayUrl(),+ officialGatewayUrl: OFFICIAL_DEVICE_GATEWAY_URL,+ override: getDesktopEnv().DEVICE_GATEWAY_URL,+ });+ } finally {+ if (this.discoveryAbort === controller) this.discoveryAbort = null;+ }+ }++ /**+ * The address saved in settings, or `undefined` when none is. Older installs+ * persisted the official gateway as a default, so that exact value reads as+ * unset without rewriting the stored value: the server's own+ * address, then the official gateway, apply.+ */+ private getSavedGatewayUrl(): string | undefined {+ const saved = this.app.storeManager.get('gatewayUrl');+ if (typeof saved !== 'string' || saved.trim() === '') return undefined;+ return saved === OFFICIAL_DEVICE_GATEWAY_URL ? undefined : saved;+ }++ /** The current server, the address saved in settings, and what the live connection uses. */+ async getEndpointInfo(): Promise<GatewayEndpointInfo> {+ const serverUrl = await this.serverUrlProvider?.();+ const serverKey = serverUrl ? deviceGatewayServerKey(serverUrl) : undefined;+ if (!serverUrl || !serverKey) return { manualUrl: this.getSavedGatewayUrl() };++ const session = this.session?.serverKey === serverKey ? this.session : null;+ return {+ endpoint: session ? { ...session.endpoint } : undefined,+ manualUrl: this.getSavedGatewayUrl(),+ serverUrl,+ };}// ─── Token Helpers ───diff --git a/apps/desktop/src/main/services/gatewayDiscovery.ts b/apps/desktop/src/main/services/gatewayDiscovery.tsnew file mode 100644index 00000000000..23f130e14a4--- /dev/null+++ b/apps/desktop/src/main/services/gatewayDiscovery.ts@@ -0,0 +1,62 @@+import {+ type DeviceGatewayDiscovery,+ parseDeviceGatewayDiscovery,+} from '@lobechat/device-gateway-client/endpoint';++import { appendVercelCookie } from '@/utils/http-headers';+import { netFetch } from '@/utils/net-fetch';+import { setDesktopUserAgentHeader } from '@/utils/user-agent';++/** A config read that hangs must not hold the connection in "connecting" forever. */+const DISCOVERY_TIMEOUT_MS = 10_000;++/**+ * Ask `serverUrl` which Device Gateway its clients should use, through the+ * public `config.getGlobalConfig` query. Sent without credentials: the address+ * is public, and a token that is about to be refreshed must not turn into a+ * config error. Uses Electron's network stack so a self-hosted server behind a+ * system-trusted private CA works the same as it does for sign-in.+ *+ * Never throws — a failed request, a non-2xx answer and a body that is not a+ * global config all come back as `failed`, distinct from "nothing advertised".+ */+export const discoverDeviceGateway = async (+ serverUrl: string,+ signal: AbortSignal,+): Promise<DeviceGatewayDiscovery> => {+ const headers: Record<string, string> = { accept: 'application/json' };+ appendVercelCookie(headers);+ setDesktopUserAgentHeader(headers);++ let response: Response;+ try {+ response = await netFetch(+ `${serverUrl.replace(/\/+$/, '')}/trpc/lambda/config.getGlobalConfig`,+ {+ headers,+ method: 'GET',+ signal: AbortSignal.any([signal, AbortSignal.timeout(DISCOVERY_TIMEOUT_MS)]),+ },+ );+ } catch (error) {+ return {+ reason: signal.aborted+ ? 'cancelled'+ : `request failed: ${error instanceof Error ? error.message : String(error)}`,+ status: 'failed',+ };+ }++ if (!response.ok) return { reason: `HTTP ${response.status}`, status: 'failed' };++ let payload: unknown;+ try {+ payload = await response.json();+ } catch {+ return { reason: 'the response is not JSON', status: 'failed' };+ }++ // tRPC + superjson envelope: `{ result: { data: { json, meta? } } }`.+ const json = (payload as { result?: { data?: { json?: unknown } } } | null)?.result?.data?.json;+ return parseDeviceGatewayDiscovery(json);+};diff --git a/apps/desktop/src/main/types/store.ts b/apps/desktop/src/main/types/store.tsindex 3f5289ac009..f2e3f596d1e 100644--- a/apps/desktop/src/main/types/store.ts+++ b/apps/desktop/src/main/types/store.ts@@ -35,13 +35,25 @@ export interface ElectronMainStore {* can still sleep.*/gatewayKeepAwake: boolean;- gatewayUrl: string;+ /**+ * Device gateway address the user chose, used ahead of what the server+ * advertises. Absent by default. Older installs persisted the official+ * gateway here as a default, so that exact value reads as "not configured".+ */+ gatewayUrl?: string;+ /**+ * Legacy, account-less list of shared workspaces. An entry moves into+ * `gatewayWorkspaceEnrollmentsByAccount` once the server shows the signed-in+ * account enrolled it; until then it is kept but never restored.+ */+ gatewayWorkspaceEnrollments?: string[];/*** Workspaces this machine's personal gateway connection has been shared into- * (via the `enrollWorkspace` device RPC). Persisted so an app restart can- * re-open the workspace share connections without re-sharing from the web UI.+ * (via the `enrollWorkspace` device RPC), per `<serverKey>#<userId>`.+ * Persisted so an app restart can re-open the share connections without+ * re-sharing from the web UI — only for the account that shared them.*/- gatewayWorkspaceEnrollments: string[];+ gatewayWorkspaceEnrollmentsByAccount: Record<string, string[]>;/*** Developer toggle: when true, hetero-agent (CC / Codex) CLI raw streams are* traced to disk even in packaged production builds. Dev builds always tracediff --git a/docs/self-hosting/advanced/desktop.mdx b/docs/self-hosting/advanced/desktop.mdxindex 206677891ee..7ab743e2990 100644--- a/docs/self-hosting/advanced/desktop.mdx+++ b/docs/self-hosting/advanced/desktop.mdx@@ -67,6 +67,34 @@ If you are deploying LobeHub using one-click deployment methods (such as Vercel,4. Click the "Connect" button.5. You will be redirected to the login page; after completing the authorization, you can use your self-hosted configuration.+### Connecting the Device Gateway++The Device Gateway lets agents run tools on this computer. The desktop app and CLI connect to `<gateway address>/ws` with a token from the instance they are signed in to, so they must use that instance's gateway. In Docker Compose this is the `gateway` service on port `8788`. Never give clients the server-internal `DEVICE_GATEWAY_URL` (`http://gateway:8788`).++1. Publish port `8788` over HTTPS with WebSocket upgrades enabled. For example, in Nginx:++ ```nginx+ location / {+ proxy_pass http://127.0.0.1:8788;+ proxy_http_version 1.1;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection 'upgrade';+ proxy_set_header Host $host;+ }+ ```++ Running `curl https://device-gateway.example.com/health` on the client computer prints `OK`.++2. Optional: set [`DEVICE_GATEWAY_PUBLIC_URL`](/docs/self-hosting/environment-variables/basic#device_gateway_public_url) to this address so clients that support discovery get it from your instance. You can also leave it unset and give each client the address.++3. In the desktop app, click the **Device Gateway** icon in the title bar and turn on the switch. The app uses the first address it finds: its own `DEVICE_GATEWAY_URL` environment variable, an existing saved address other than `https://device-gateway.lobehub.com`, the address published by your instance, then `https://device-gateway.lobehub.com`.++ The desktop app only reads existing saved gateway addresses; it does not provide an address editor or write the discovered address to its settings. Configure `DEVICE_GATEWAY_PUBLIC_URL` on the server, or set `DEVICE_GATEWAY_URL` when starting the desktop app.++4. For the CLI, run `lh login --server https://lobe.example.com`, then `lh connect`. `lh` uses `--gateway <url>` (saved for later runs), the address saved for this instance, then the address published by your instance. If none exists, it asks for `--gateway <url>`.++<Callout>Clients without discovery support ignore the published address. Give them the address with the desktop `DEVICE_GATEWAY_URL` or `lh connect --gateway <url>`.</Callout>+## Frequently Asked Questions### 502 Bad Gateway@@ -95,6 +123,15 @@ proxy_busy_buffers_size 32k;Check if the `APP_URL` environment variable matches the URL you are accessing.+### Device Gateway Does Not Connect++**Issue:** The Device Gateway switch turns off right after you turn it on, or the connection keeps retrying.++**Solution:**++- If `lh status` prints `FAILED - Authentication failed: crypto/rsa: verification error`, the gateway does not trust the instance that issued the token. Use the gateway of the instance the client is signed in to, and check that the gateway's `JWKS_PUBLIC_KEY` matches your current `JWKS_KEY`. Without a published or configured address, the desktop app uses the LobeHub Cloud gateway, which rejects self-hosted tokens.+- If the connection times out, run the `/health` check above on the client computer, then check the reverse proxy's WebSocket settings and certificate.+### macOS Startup Hangs or Crashes**Issue:** On macOS, the application hangs for a long time or crashes after startup.diff --git a/docs/self-hosting/advanced/desktop.zh-CN.mdx b/docs/self-hosting/advanced/desktop.zh-CN.mdxindex e56f44e6c00..ee0cf039745 100644--- a/docs/self-hosting/advanced/desktop.zh-CN.mdx+++ b/docs/self-hosting/advanced/desktop.zh-CN.mdx@@ -65,6 +65,34 @@ LobeHub 桌面端可以与您自托管的 LobeHub 实例连接,以便您可以4. 点击 "连接" 按钮5. 您将被重定向到登录页面,完成授权后即可使用您的自托管配置+### 连接设备网关++设备网关让助理可以在这台电脑上运行工具。桌面端和 CLI 会使用当前登录实例签发的令牌连接 `<网关地址>/ws`,因此必须使用该实例的网关。在 Docker Compose 中,它是 `gateway` 服务的 `8788` 端口。不要把服务端内部使用的 `DEVICE_GATEWAY_URL`(`http://gateway:8788`)提供给客户端。++1. 通过 HTTPS 公开 `8788` 端口,并允许 WebSocket 升级。Nginx 示例:++ ```nginx+ location / {+ proxy_pass http://127.0.0.1:8788;+ proxy_http_version 1.1;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection 'upgrade';+ proxy_set_header Host $host;+ }+ ```++ 在客户端电脑上运行 `curl https://device-gateway.example.com/health`,应输出 `OK`。++2. 可选:将 [`DEVICE_GATEWAY_PUBLIC_URL`](/zh/docs/self-hosting/environment-variables/basic#device_gateway_public_url) 设置为该地址,支持自动发现的客户端即可从您的实例获取它。也可以不配置,为每个客户端自行提供地址。++3. 在桌面端点击标题栏中的 **设备网关** 图标并打开开关。桌面端按以下顺序使用找到的第一个地址:桌面端自己的 `DEVICE_GATEWAY_URL` 环境变量、已有且不是 `https://device-gateway.lobehub.com` 的保存地址、您的实例下发的地址,最后是 `https://device-gateway.lobehub.com`。++ 桌面端只读取已有的网关地址,不提供地址编辑入口,也不会把下发的地址写入设置。请在服务端配置 `DEVICE_GATEWAY_PUBLIC_URL`,或在启动桌面端时设置 `DEVICE_GATEWAY_URL`。++4. 使用 CLI 时,先运行 `lh login --server https://lobe.example.com`,再运行 `lh connect`。`lh` 依次使用 `--gateway <url>`(会保存供之后使用)、为当前实例保存的地址、您的实例下发的地址;都没有时会提示提供 `--gateway <url>`。++<Callout>不支持自动发现的客户端会忽略实例下发的地址,请通过桌面端的 `DEVICE_GATEWAY_URL` 或 `lh connect --gateway <url>` 提供地址。</Callout>+## 常见问题### 502 Bad Gateway@@ -93,6 +121,15 @@ proxy_busy_buffers_size 32k;检查 `APP_URL` 环境变量是否与您访问的 URL 一致+### 设备网关无法连接++**问题:** 打开设备网关开关后立即恢复关闭,或连接一直在重试。++**解决方案:**++- 如果 `lh status` 输出 `FAILED - Authentication failed: crypto/rsa: verification error`,说明网关不信任签发令牌的实例。请使用客户端所登录实例的网关,并确认网关的 `JWKS_PUBLIC_KEY` 与当前 `JWKS_KEY` 匹配。没有下发或配置地址时,桌面端会使用 LobeHub Cloud 网关,它会拒绝自托管实例的令牌。+- 如果连接超时,请在客户端电脑上运行上文的 `/health` 检查,再检查反向代理的 WebSocket 设置和证书。+### macOS 启动卡住或闪退**问题:** 在 macOS 上,应用启动后长时间卡住或闪退。diff --git a/locales/en-US/electron.json b/locales/en-US/electron.jsonindex 1c06bbb46c1..d305e40432f 100644--- a/locales/en-US/electron.json+++ b/locales/en-US/electron.json@@ -1,6 +1,11 @@{"gateway.enableConnection": "Connect to Gateway",+ "gateway.error.authRejected": "Device Gateway rejected this sign-in. Retry or sign in again. If it persists, ask your server administrator to check the gateway configuration.",+ "gateway.error.configUnavailable": "Couldn't load this server's configuration. Check your connection and retry.",+ "gateway.error.invalidAddress": "The Device Gateway address is invalid. Check the desktop environment or existing configuration, or ask your server administrator to check the gateway address.",+ "gateway.error.notSignedIn": "Sign in to connect this device.","gateway.manageDevices": "Manage devices",+ "gateway.retry": "Retry","gateway.statusConnected": "This device is connected to Gateway","gateway.statusConnectedConnections_one": "Online · {{count}} connection","gateway.statusConnectedConnections_other": "Online · {{count}} connections",diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.jsonindex 2a3f861f744..d63e02d7c77 100644--- a/locales/zh-CN/electron.json+++ b/locales/zh-CN/electron.json@@ -1,6 +1,11 @@{"gateway.enableConnection": "连接到网关",+ "gateway.error.authRejected": "设备网关拒绝了当前登录凭证。请重试或重新登录;若仍有问题,请联系服务器管理员检查网关配置。",+ "gateway.error.configUnavailable": "无法读取当前服务器的配置。请检查网络后重试。",+ "gateway.error.invalidAddress": "设备网关地址无效。请检查桌面端的环境变量或已有配置,或联系服务器管理员检查网关地址。",+ "gateway.error.notSignedIn": "登录后即可连接此设备。","gateway.manageDevices": "管理设备",+ "gateway.retry": "重试","gateway.statusConnected": "本机已连接设备网关","gateway.statusConnectedConnections_one": "在线 · {{count}} 个连接","gateway.statusConnectedConnections_other": "在线 · {{count}} 个连接",diff --git a/packages/device-gateway-client/package.json b/packages/device-gateway-client/package.jsonindex 782a3ff31b0..128045db3b8 100644--- a/packages/device-gateway-client/package.json+++ b/packages/device-gateway-client/package.json@@ -3,7 +3,8 @@"version": "1.0.0","private": true,"exports": {- ".": "./src/index.ts"+ ".": "./src/index.ts",+ "./endpoint": "./src/endpoint.ts"},"main": "./src/index.ts","scripts": {diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.tsindex c08f6a280eb..f6e4aaeafbb 100644--- a/packages/device-gateway-client/src/client.test.ts+++ b/packages/device-gateway-client/src/client.test.ts@@ -185,6 +185,20 @@ describe('GatewayClient', () => {c.disconnect();});+ it('should keep a public path prefix and ignore a trailing slash', () => {+ const c = new GatewayClient({+ autoReconnect: false,+ gatewayUrl: 'https://edge.example.com/device-gateway/',+ token: 'tok',+ });+ c.connect();+ const ws = new URL((c as any).ws.url);+ expect(`${ws.protocol}//${ws.host}${ws.pathname}`).toBe(+ 'wss://edge.example.com/device-gateway/ws',+ );+ c.disconnect();+ });+it('should include user agent header when provided', () => {const c = new GatewayClient({autoReconnect: false,diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.tsindex 96b1af56bf6..c9a1e58768a 100644--- a/packages/device-gateway-client/src/client.ts+++ b/packages/device-gateway-client/src/client.ts@@ -5,6 +5,7 @@ import os from 'node:os';import type { DeviceMetricSample } from '@lobechat/types';import WebSocket from 'ws';+import { toDeviceGatewayWebSocketUrl } from './endpoint';import { DeviceTunnelHost } from './tunnel';import type {AgentRunAckMessage,@@ -341,8 +342,9 @@ export class GatewayClient extends EventEmitter {}private buildWsUrl(): string {- const wsProtocol = this.gatewayUrl.startsWith('https') ? 'wss' : 'ws';- const host = this.gatewayUrl.replace(/^https?:\/\//, '');+ // Keeps a path prefix (`https://host/gw` → `wss://host/gw/ws`) and tolerates+ // a trailing slash in a hand-entered address.+ const url = toDeviceGatewayWebSocketUrl(this.gatewayUrl);const params = new URLSearchParams({connectionId: this.connectionId,deviceId: this.deviceId,@@ -363,7 +365,8 @@ export class GatewayClient extends EventEmitter {params.set('userId', this.userId);}- return `${wsProtocol}://${host}/ws?${params.toString()}`;+ url.search = params.toString();+ return url.toString();}/**diff --git a/packages/device-gateway-client/src/endpoint.test.ts b/packages/device-gateway-client/src/endpoint.test.tsnew file mode 100644index 00000000000..cf32330ffd6--- /dev/null+++ b/packages/device-gateway-client/src/endpoint.test.ts@@ -0,0 +1,212 @@+import { describe, expect, it, vi } from 'vitest';++import {+ deviceGatewayServerKey,+ normalizeDeviceGatewayUrl,+ parseDeviceGatewayDiscovery,+ resolveDeviceGatewayEndpoint,+ toDeviceGatewayWebSocketUrl,+} from './endpoint';++const OFFICIAL = 'https://device-gateway.lobehub.com';++describe('normalizeDeviceGatewayUrl', () => {+ it('keeps a path prefix and drops trailing slashes', () => {+ expect(normalizeDeviceGatewayUrl(' https://Gateway.example.com:443/edge/gw// ')).toBe(+ 'https://gateway.example.com/edge/gw',+ );+ expect(normalizeDeviceGatewayUrl('http://localhost:8788/')).toBe('http://localhost:8788');+ });++ it.each([+ ['empty', ''],+ ['blank', ' '],+ ['null', null],+ ['not a URL', 'device-gateway'],+ ['websocket scheme', 'wss://gateway.example.com'],+ ['credentials', 'https://user:[email protected]'],+ ['query', 'https://gateway.example.com/?token=abc'],+ ['empty query', 'https://gateway.example.com/?'],+ ['fragment', 'https://gateway.example.com/#x'],+ ])('rejects %s', (_label, value) => {+ expect(normalizeDeviceGatewayUrl(value)).toBeUndefined();+ });+});++describe('deviceGatewayServerKey', () => {+ it('treats trailing slashes and default ports as the same server', () => {+ expect(deviceGatewayServerKey('https://lobe.example.com:443/')).toBe(+ deviceGatewayServerKey('https://lobe.example.com'),+ );+ });++ it('keeps distinct hosts and ports apart', () => {+ expect(deviceGatewayServerKey('http://localhost:3010')).not.toBe(+ deviceGatewayServerKey('http://localhost:3020'),+ );+ });+});++describe('toDeviceGatewayWebSocketUrl', () => {+ it('appends /ws under the path prefix', () => {+ expect(toDeviceGatewayWebSocketUrl('https://example.com/edge/gw').toString()).toBe(+ 'wss://example.com/edge/gw/ws',+ );+ expect(toDeviceGatewayWebSocketUrl('http://localhost:8788/').toString()).toBe(+ 'ws://localhost:8788/ws',+ );+ });+});++describe('parseDeviceGatewayDiscovery', () => {+ it('reads an advertised address', () => {+ expect(+ parseDeviceGatewayDiscovery({+ serverConfig: { deviceGatewayUrl: 'https://gw.example.com/' },+ }),+ ).toEqual({ status: 'advertised', url: 'https://gw.example.com' });+ });++ it('treats an omitted field as absent', () => {+ expect(+ parseDeviceGatewayDiscovery({ serverConfig: { enableUploadFileToServer: true } }),+ ).toEqual({ status: 'absent' });+ });++ it.each([+ ['null', null],+ ['empty string', ''],+ ['non-http scheme', 'ftp://gw.example.com'],+ ['number', 42],+ ])('flags a %s advertisement as invalid instead of absent', (_label, value) => {+ expect(parseDeviceGatewayDiscovery({ serverConfig: { deviceGatewayUrl: value } }).status).toBe(+ 'invalid',+ );+ });++ it.each([+ ['undefined', undefined],+ ['an HTML error page', '<html>404</html>'],+ ['a body without serverConfig', { billboard: null }],+ ])('flags %s as a failed discovery', (_label, value) => {+ expect(parseDeviceGatewayDiscovery(value).status).toBe('failed');+ });+});++describe('resolveDeviceGatewayEndpoint', () => {+ const advertised = async () => ({ status: 'advertised', url: 'https://gw.example.com' }) as const;++ it('uses an explicit override without asking the server', async () => {+ const discover = vi.fn(advertised);++ await expect(+ resolveDeviceGatewayEndpoint({+ discover,+ manualUrl: 'https://gw.saved.example',+ officialGatewayUrl: OFFICIAL,+ override: 'http://localhost:8787/',+ }),+ ).resolves.toEqual({+ endpoint: { source: 'override', url: 'http://localhost:8787' },+ ok: true,+ });+ expect(discover).not.toHaveBeenCalled();+ });++ it('rejects an invalid override instead of falling through', async () => {+ const discover = vi.fn(advertised);++ await expect(+ resolveDeviceGatewayEndpoint({+ discover,+ manualUrl: 'https://gw.saved.example',+ override: 'wss://gw.example.com',+ }),+ ).resolves.toMatchObject({ ok: false, reason: 'invalid_override' });+ expect(discover).not.toHaveBeenCalled();+ });++ it('prefers the address saved for this server over the advertised one, without asking', async () => {+ const discover = vi.fn(advertised);++ await expect(+ resolveDeviceGatewayEndpoint({+ discover,+ manualUrl: 'https://gw.saved.example/',+ officialGatewayUrl: OFFICIAL,+ }),+ ).resolves.toEqual({+ endpoint: { source: 'manual', url: 'https://gw.saved.example' },+ ok: true,+ });+ expect(discover).not.toHaveBeenCalled();+ });++ it('keeps a saved address that equals the official gateway as the saved choice', async () => {+ const discover = vi.fn(advertised);++ await expect(+ resolveDeviceGatewayEndpoint({ discover, manualUrl: OFFICIAL, officialGatewayUrl: OFFICIAL }),+ ).resolves.toEqual({ endpoint: { source: 'manual', url: OFFICIAL }, ok: true });+ expect(discover).not.toHaveBeenCalled();+ });++ it('reports an invalid saved address instead of discovering around it', async () => {+ const discover = vi.fn(advertised);++ await expect(+ resolveDeviceGatewayEndpoint({+ discover,+ manualUrl: 'ftp://gw',+ officialGatewayUrl: OFFICIAL,+ }),+ ).resolves.toMatchObject({ ok: false, reason: 'invalid_manual' });+ expect(discover).not.toHaveBeenCalled();+ });++ it('uses the advertised address when nothing is configured', async () => {+ await expect(+ resolveDeviceGatewayEndpoint({+ discover: async () => ({ status: 'advertised', url: 'https://gw.example.com/prefix' }),+ manualUrl: ' ',+ officialGatewayUrl: OFFICIAL,+ }),+ ).resolves.toEqual({+ endpoint: { source: 'server', url: 'https://gw.example.com/prefix' },+ ok: true,+ });+ });++ it('defaults to the official gateway only when the server answered without one', async () => {+ await expect(+ resolveDeviceGatewayEndpoint({+ discover: async () => ({ status: 'absent' }),+ officialGatewayUrl: OFFICIAL,+ }),+ ).resolves.toEqual({ endpoint: { source: 'official', url: OFFICIAL }, ok: true });+ });++ it('reports not_configured when the caller has no default for an unadvertised server', async () => {+ await expect(+ resolveDeviceGatewayEndpoint({ discover: async () => ({ status: 'absent' }) }),+ ).resolves.toEqual({ ok: false, reason: 'not_configured' });+ });++ it('does not fall back to the default when discovery failed', async () => {+ await expect(+ resolveDeviceGatewayEndpoint({+ discover: async () => ({ reason: 'HTTP 500', status: 'failed' }),+ officialGatewayUrl: OFFICIAL,+ }),+ ).resolves.toEqual({ detail: 'HTTP 500', ok: false, reason: 'discovery_failed' });+ });++ it('does not fall back to the default when the advertised value is invalid', async () => {+ await expect(+ resolveDeviceGatewayEndpoint({+ discover: async () => ({ reason: 'bad', status: 'invalid' }),+ officialGatewayUrl: OFFICIAL,+ }),+ ).resolves.toMatchObject({ ok: false, reason: 'invalid_advertised_url' });+ });+});diff --git a/packages/device-gateway-client/src/endpoint.ts b/packages/device-gateway-client/src/endpoint.tsnew file mode 100644index 00000000000..09b85f2d99b--- /dev/null+++ b/packages/device-gateway-client/src/endpoint.ts@@ -0,0 +1,184 @@+/**+ * Device Gateway address discovery, shared by the desktop main process and the+ * CLI. Pure: callers own the I/O (how the server's global config is fetched,+ * where per-server addresses are stored) and pass the results in, so both+ * clients apply one precedence and one validation rule.+ *+ * Precedence for a new connection:+ * 1. an explicit override for this run (desktop `DEVICE_GATEWAY_URL`, CLI `--gateway`)+ * 2. the address the user saved for the current server+ * 3. the address the current server advertises (`serverConfig.deviceGatewayUrl`)+ * 4. the official gateway, when the server answered without advertising one+ * and the caller allows that default+ *+ * The server is only asked when neither 1 nor 2 applies. A failed or malformed+ * discovery is an error, never "nothing advertised": falling through would hand+ * this server's token to a gateway it never chose.+ */++export type DeviceGatewayUrlSource = 'manual' | 'official' | 'override' | 'server';++export interface DeviceGatewayEndpoint {+ source: DeviceGatewayUrlSource;+ url: string;+}++export type DeviceGatewayDiscovery =+ | { status: 'absent' }+ | { status: 'advertised'; url: string }+ /** The request failed, answered non-2xx, or the body is not a global config. */+ | { reason: string; status: 'failed' }+ /** The server advertised a value that is not a usable gateway base URL. */+ | { reason: string; status: 'invalid' };++export type DeviceGatewayResolutionFailure =+ | 'discovery_failed'+ | 'invalid_advertised_url'+ | 'invalid_manual'+ | 'invalid_override'+ /** The server advertises nothing and the caller has no default for it. */+ | 'not_configured';++export type DeviceGatewayResolution<+ Failure extends DeviceGatewayResolutionFailure = DeviceGatewayResolutionFailure,+> = { endpoint: DeviceGatewayEndpoint; ok: true } | { detail?: string; ok: false; reason: Failure };++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const parseHttpUrl = (value: unknown): URL | undefined => {+ if (typeof value !== 'string') return undefined;+ const trimmed = value.trim();+ if (!trimmed) return undefined;++ try {+ const url = new URL(trimmed);+ return url.protocol === 'http:' || url.protocol === 'https:' ? url : undefined;+ } catch {+ return undefined;+ }+};++const stripTrailingSlashes = (pathname: string) => pathname.replace(/\/+$/, '');++/**+ * Normalize a Device Gateway base URL, or `undefined` when it is unusable.+ * Same rule the server applies to `DEVICE_GATEWAY_PUBLIC_URL`: http(s), no+ * credentials, query or fragment; a path prefix is kept, trailing `/` dropped.+ */+export const normalizeDeviceGatewayUrl = (value: unknown): string | undefined => {+ const url = parseHttpUrl(value);+ if (!url) return undefined;+ if (url.username || url.password || /[?#]/.test((value as string).trim())) return undefined;++ return `${url.origin}${stripTrailingSlashes(url.pathname)}`;+};++/**+ * Stable key for "this server", used to bind per-server state (a saved gateway+ * address, workspace enrollments) so it never leaks to another instance.+ */+export const deviceGatewayServerKey = (serverUrl: string): string | undefined => {+ const url = parseHttpUrl(serverUrl);+ return url ? `${url.origin}${stripTrailingSlashes(url.pathname)}` : undefined;+};++/** WebSocket endpoint for a gateway base URL: `ws(s)://<host><prefix>/ws`. */+export const toDeviceGatewayWebSocketUrl = (gatewayUrl: string): URL => {+ const url = new URL(gatewayUrl);+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';+ url.pathname = `${stripTrailingSlashes(url.pathname)}/ws`;+ url.search = '';+ url.hash = '';+ return url;+};++/**+ * Read the advertised address out of a `config.getGlobalConfig` result. An+ * omitted field is the only "absent"; anything else that is not a usable URL+ * (including `null` or an empty string) is `invalid`.+ */+export const parseDeviceGatewayDiscovery = (globalConfig: unknown): DeviceGatewayDiscovery => {+ if (!isRecord(globalConfig) || !isRecord(globalConfig.serverConfig))+ return { reason: 'the server response is not a global config', status: 'failed' };++ const { serverConfig } = globalConfig;+ if (!('deviceGatewayUrl' in serverConfig) || serverConfig.deviceGatewayUrl === undefined)+ return { status: 'absent' };++ const url = normalizeDeviceGatewayUrl(serverConfig.deviceGatewayUrl);+ return url+ ? { status: 'advertised', url }+ : { reason: 'the advertised device gateway URL is not a valid http(s) URL', status: 'invalid' };+};++const INVALID_ADDRESS_DETAIL = 'not a valid http(s) URL without credentials, query or fragment';++const explicitEndpoint = (+ value: string | undefined,+ source: 'manual' | 'override',+): DeviceGatewayResolution | undefined => {+ if (value === undefined || value.trim() === '') return undefined;++ const url = normalizeDeviceGatewayUrl(value);+ if (url) return { endpoint: { source, url }, ok: true };++ return {+ detail: `the ${source === 'override' ? 'override' : 'saved address'} is ${INVALID_ADDRESS_DETAIL}`,+ ok: false,+ reason: source === 'override' ? 'invalid_override' : 'invalid_manual',+ };+};++export interface ResolveDeviceGatewayEndpointParams {+ /** Fetch and parse the current server's global config. Must not throw. */+ discover: () => Promise<DeviceGatewayDiscovery>;+ /** Address the user saved for the current server. Beats the advertisement. */+ manualUrl?: string;+ /**+ * Used when the server answers without advertising an address. Omit it to+ * report `not_configured` instead.+ */+ officialGatewayUrl?: string;+ /** Explicit address for this run; beats everything else. */+ override?: string;+}++/** What a caller that always supplies the official default can get back. */+export type DeviceGatewayResolutionWithDefault = DeviceGatewayResolution<+ Exclude<DeviceGatewayResolutionFailure, 'not_configured'>+>;++export function resolveDeviceGatewayEndpoint(+ params: ResolveDeviceGatewayEndpointParams & { officialGatewayUrl: string },+): Promise<DeviceGatewayResolutionWithDefault>;+export function resolveDeviceGatewayEndpoint(+ params: ResolveDeviceGatewayEndpointParams,+): Promise<DeviceGatewayResolution>;+export async function resolveDeviceGatewayEndpoint({+ discover,+ manualUrl,+ officialGatewayUrl,+ override,+}: ResolveDeviceGatewayEndpointParams): Promise<DeviceGatewayResolution> {+ const explicit = explicitEndpoint(override, 'override') ?? explicitEndpoint(manualUrl, 'manual');+ if (explicit) return explicit;++ const discovery = await discover();+ switch (discovery.status) {+ case 'advertised': {+ return { endpoint: { source: 'server', url: discovery.url }, ok: true };+ }+ case 'failed': {+ return { detail: discovery.reason, ok: false, reason: 'discovery_failed' };+ }+ case 'invalid': {+ return { detail: discovery.reason, ok: false, reason: 'invalid_advertised_url' };+ }+ case 'absent': {+ return officialGatewayUrl+ ? { endpoint: { source: 'official', url: officialGatewayUrl }, ok: true }+ : { ok: false, reason: 'not_configured' };+ }+ }+}diff --git a/packages/device-gateway-client/src/index.ts b/packages/device-gateway-client/src/index.tsindex 0b9ad17a0f0..3e4f78fd221 100644--- a/packages/device-gateway-client/src/index.ts+++ b/packages/device-gateway-client/src/index.ts@@ -10,6 +10,7 @@ export {describeGatewayResponseFailure,DeviceTransportErrorCode,} from './deviceTransportError';+export * from './endpoint';export type {DeviceMessageApiResult,DeviceRpcResult,diff --git a/packages/electron-client-ipc/src/events/gatewayConnection.ts b/packages/electron-client-ipc/src/events/gatewayConnection.tsindex c1ed4fb3581..c53b6733084 100644--- a/packages/electron-client-ipc/src/events/gatewayConnection.ts+++ b/packages/electron-client-ipc/src/events/gatewayConnection.ts@@ -1,10 +1,47 @@export type GatewayConnectionStatus =- | 'connected'- | 'connecting'- | 'disconnected'- | 'reconnecting'- | 'authenticating';+ 'connected' | 'connecting' | 'disconnected' | 'reconnecting' | 'authenticating';++/**+ * Why the last connection attempt ended. Cleared when a new attempt starts or+ * the user turns the connection off.+ */+export type GatewayConnectionErrorCode =+ /** The gateway rejected this login's credential. */+ | 'auth_failed'+ /** The current server's configuration could not be loaded. */+ | 'config_unavailable'+ /** The saved, advertised or overridden gateway address is not a usable URL. */+ | 'invalid_gateway_url'+ | 'not_signed_in';++export interface GatewayConnectionError {+ code: GatewayConnectionErrorCode;+ /** Diagnostic detail for logs and tooltips; user-facing copy comes from `code`. */+ detail?: string;+}++export interface GatewayConnectionState {+ error?: GatewayConnectionError;+ status: GatewayConnectionStatus;+}++export interface GatewayConnectResult {+ error?: string;+ errorCode?: GatewayConnectionErrorCode;+ success: boolean;+}++export type GatewayEndpointSource = 'manual' | 'official' | 'override' | 'server';++export interface GatewayEndpointInfo {+ /** Address of the current connection, once one has been resolved. */+ endpoint?: { source: GatewayEndpointSource; url: string };+ /** Address saved in settings; it beats the server's own. */+ manualUrl?: string;+ /** The server the desktop is signed in to, when there is one. */+ serverUrl?: string;+}export interface GatewayConnectionBroadcastEvents {- gatewayConnectionStatusChanged: (params: { status: GatewayConnectionStatus }) => void;+ gatewayConnectionStatusChanged: (params: GatewayConnectionState) => void;}diff --git a/packages/electron-client-ipc/src/events/index.ts b/packages/electron-client-ipc/src/events/index.tsindex 51ff744c971..949f267fd19 100644--- a/packages/electron-client-ipc/src/events/index.ts+++ b/packages/electron-client-ipc/src/events/index.ts@@ -38,7 +38,15 @@ export type MainBroadcastParams<T extends MainBroadcastEventKey> = Parameters<MainBroadcastEvents[T]>[0];-export type { GatewayConnectionStatus } from './gatewayConnection';+export type {+ GatewayConnectionError,+ GatewayConnectionErrorCode,+ GatewayConnectionState,+ GatewayConnectionStatus,+ GatewayConnectResult,+ GatewayEndpointInfo,+ GatewayEndpointSource,+} from './gatewayConnection';export type {DetectAppsResult,DetectedApp,diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.tsindex 3fab9641eb2..ad80d338252 100644--- a/packages/locales/src/default/electron.ts+++ b/packages/locales/src/default/electron.ts@@ -114,6 +114,14 @@ export default {'proxy.validation.typeRequired': 'Proxy type is required when proxy is enabled','proxy.validation.usernameRequired': 'Username is required when authentication is enabled','gateway.enableConnection': 'Connect to Gateway',+ 'gateway.error.authRejected':+ 'Device Gateway rejected this sign-in. Retry or sign in again. If it persists, ask your server administrator to check the gateway configuration.',+ 'gateway.error.configUnavailable':+ "Couldn't load this server's configuration. Check your connection and retry.",+ 'gateway.error.invalidAddress':+ 'The Device Gateway address is invalid. Check the desktop environment or existing configuration, or ask your server administrator to check the gateway address.',+ 'gateway.error.notSignedIn': 'Sign in to connect this device.',+ 'gateway.retry': 'Retry','gateway.manageDevices': 'Manage devices','gateway.statusConnected': 'This device is connected to Gateway','gateway.statusConnectedConnections_one': 'Online · {{count}} connection',diff --git a/src/features/Electron/connection/DeviceGateway.tsx b/src/features/Electron/connection/DeviceGateway.tsxindex 2c4e10b0ca5..37224e3b7c6 100644--- a/src/features/Electron/connection/DeviceGateway.tsx+++ b/src/features/Electron/connection/DeviceGateway.tsx@@ -1,5 +1,5 @@-import { useWatchBroadcast } from '@lobechat/electron-client-ipc';-import { ActionIcon, createStaticStyles, Flexbox, Popover, Switch } from '@lobehub/ui';+import { type GatewayConnectionErrorCode, useWatchBroadcast } from '@lobechat/electron-client-ipc';+import { ActionIcon, Button, createStaticStyles, Flexbox, Popover, Switch } from '@lobehub/ui';import { HardDrive, SettingsIcon } from 'lucide-react';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -14,7 +14,32 @@ import { useDeviceList } from '@/store/device';import { useElectronStore } from '@/store/electron';import { electronSyncSelectors } from '@/store/electron/selectors';+/** Why the last attempt ended, phrased with the next step. */+const ERROR_MESSAGE_KEYS = {+ auth_failed: 'gateway.error.authRejected',+ config_unavailable: 'gateway.error.configUnavailable',+ invalid_gateway_url: 'gateway.error.invalidAddress',+ not_signed_in: 'gateway.error.notSignedIn',+} as const satisfies Record<GatewayConnectionErrorCode, string>;+const styles = createStaticStyles(({ css, cssVar }) => ({+ errorDot: css`+ position: absolute;+ inset-block-end: 0;+ inset-inline-end: 0;++ width: 8px;+ height: 8px;+ border: 1.5px solid ${cssVar.colorBgContainer};+ border-radius: 50%;++ background: ${cssVar.colorError};+ `,+ errorHint: css`+ font-size: 12px;+ line-height: 1.5;+ color: ${cssVar.colorError};+ `,greenDot: css`position: absolute;inset-block-end: 0;@@ -52,15 +77,17 @@ const DeviceGateway = memo<DeviceGatewayProps>(({ workspaceScoped }) => {const navigate = useWorkspaceAwareNavigate();const [gatewayStatus,+ gatewayError,connectGateway,disconnectGateway,- setGatewayConnectionStatus,+ setGatewayConnectionState,useFetchGatewayStatus,] = useElectronStore((s) => [s.gatewayConnectionStatus,+ s.gatewayConnectionError,s.connectGateway,s.disconnectGateway,- s.setGatewayConnectionStatus,+ s.setGatewayConnectionState,s.useFetchGatewayStatus,]);@@ -70,9 +97,7 @@ const DeviceGateway = memo<DeviceGatewayProps>(({ workspaceScoped }) => {const deviceList = useDeviceList();const devices = deviceList.data;- useWatchBroadcast('gatewayConnectionStatusChanged', ({ status }) => {- setGatewayConnectionStatus(status);- });+ useWatchBroadcast('gatewayConnectionStatusChanged', setGatewayConnectionState);const isConnected = gatewayStatus === 'connected';const isConnecting =@@ -80,8 +105,16 @@ const DeviceGateway = memo<DeviceGatewayProps>(({ workspaceScoped }) => {gatewayStatus === 'connecting' ||gatewayStatus === 'reconnecting';+ // Only the personal connection is toggled from here; workspace rows have their own status.+ const failure = !workspaceScoped && !isConnected && !isConnecting ? gatewayError : undefined;+const [open, setOpen] = useState(false);+ const openDeviceSettings = () => {+ setOpen(false);+ navigate('/settings/devices');+ };+const handleSwitchChange = useCallback(async (checked: boolean) => {if (checked) {@@ -124,10 +157,7 @@ const DeviceGateway = memo<DeviceGatewayProps>(({ workspaceScoped }) => {icon={SettingsIcon}size="small"title={t('gateway.manageDevices')}- onClick={() => {- setOpen(false);- navigate('/settings/devices');- }}+ onClick={openDeviceSettings}/>{!workspaceScoped && (<Switch@@ -141,6 +171,20 @@ const DeviceGateway = memo<DeviceGatewayProps>(({ workspaceScoped }) => {</Flexbox></Flexbox><span className={styles.scopeHint}>{connectionHint}</span>+ {failure && (+ <Flexbox align="flex-start" gap={4}>+ <span className={styles.errorHint} title={failure.detail}>+ {t(ERROR_MESSAGE_KEYS[failure.code])}+ </span>+ <Flexbox horizontal gap={4}>+ {failure.code !== 'not_signed_in' && failure.code !== 'invalid_gateway_url' && (+ <Button outdent size="small" type="text" onClick={() => void connectGateway()}>+ {t('gateway.retry')}+ </Button>+ )}+ </Flexbox>+ </Flexbox>+ )}</Flexbox>);@@ -162,7 +206,11 @@ const DeviceGateway = memo<DeviceGatewayProps>(({ workspaceScoped }) => {title={t('gateway.title')}tooltipProps={{ placement: 'bottomRight' }}/>- {scopeConnected && <div className={styles.greenDot} />}+ {scopeConnected ? (+ <div className={styles.greenDot} />+ ) : (+ failure && <div className={styles.errorDot} />+ )}</div></Popover>);diff --git a/src/features/Settings/devices/KeepAwake.tsx b/src/features/Settings/devices/ThisComputer.tsxsimilarity index 80%rename from src/features/Settings/devices/KeepAwake.tsxrename to src/features/Settings/devices/ThisComputer.tsxindex f130f5fbd0f..79418bca618 100644--- a/src/features/Settings/devices/KeepAwake.tsx+++ b/src/features/Settings/devices/ThisComputer.tsx@@ -8,11 +8,8 @@ import { useTranslation } from 'react-i18next';import { FORM_STYLE } from '@/const/layoutTokens';import { useGatewayKeepAwake } from '@/features/Electron/connection/useGatewayKeepAwake';-/**- * Desktop-only: keep this computer from idle-sleeping while it is connected as- * a device, so remote runs can still reach it after the user walks away.- */-const KeepAwake = memo(() => {+/** Desktop-only keep-awake setting for this computer as a device. */+const ThisComputer = memo(() => {const { t } = useTranslation('setting');const { enabled, isLoading, setKeepAwake } = useGatewayKeepAwake();const form = useForm();@@ -47,6 +44,6 @@ const KeepAwake = memo(() => {);});-KeepAwake.displayName = 'KeepAwake';+ThisComputer.displayName = 'ThisComputer';-export default KeepAwake;+export default ThisComputer;diff --git a/src/features/Settings/devices/index.tsx b/src/features/Settings/devices/index.tsxindex da1ebb198c1..e0cbf8fdee4 100644--- a/src/features/Settings/devices/index.tsx+++ b/src/features/Settings/devices/index.tsx@@ -10,7 +10,7 @@ import { DeviceConnectModal, DeviceDetailPage, DeviceManager } from '@/features/import NavHeader from '@/features/NavHeader';import SettingContainer from '@/features/Setting/SettingContainer';-import KeepAwake from './KeepAwake';+import ThisComputer from './ThisComputer';interface PageProps {mobile?: boolean;@@ -47,7 +47,7 @@ const Page = memo<PageProps>(({ mobile }) => {onConnect={handleConnect}onOpenDevice={openDevice}/>- {isDesktop && <KeepAwake />}+ {isDesktop && <ThisComputer />}</Flexbox>);diff --git a/src/store/electron/actions/__tests__/gateway.test.ts b/src/store/electron/actions/__tests__/gateway.test.tsindex ec3b97341ab..10cb48a08e4 100644--- a/src/store/electron/actions/__tests__/gateway.test.ts+++ b/src/store/electron/actions/__tests__/gateway.test.ts@@ -1,8 +1,16 @@+import { act } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { gatewayConnectionService } from '@/services/electron/gatewayConnection';import { useElectronStore } from '@/store/electron';-const service = vi.hoisted(() => ({ getDeviceInfo: vi.fn(), getStableDeviceId: vi.fn() }));+const service = vi.hoisted(() => ({+ getDeviceInfo: vi.fn(),+ getStableDeviceId: vi.fn(),+ connect: vi.fn(),+ disconnect: vi.fn(),+ getConnectionStatus: vi.fn(),+}));vi.mock('@lobechat/const', async (importOriginal) => ({...(await importOriginal<object>()),@@ -50,3 +58,70 @@ describe('resolveGatewayDeviceId', () => {await expect(useElectronStore.getState().resolveGatewayDeviceId()).resolves.toBeUndefined();});});++describe('ElectronGatewayActionImpl', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useElectronStore.setState({+ gatewayConnectionError: undefined,+ gatewayConnectionStatus: 'disconnected',+ });+ });++ it('keeps the reason a failed attempt ended with, as the main process reports it', async () => {+ vi.mocked(gatewayConnectionService.connect).mockResolvedValue({+ errorCode: 'invalid_gateway_url',+ success: false,+ });+ vi.mocked(gatewayConnectionService.getConnectionStatus).mockResolvedValue({+ error: { code: 'invalid_gateway_url' },+ status: 'disconnected',+ });++ await act(() => useElectronStore.getState().connectGateway());++ expect(useElectronStore.getState()).toMatchObject({+ gatewayConnectionError: { code: 'invalid_gateway_url' },+ gatewayConnectionStatus: 'disconnected',+ });+ });++ it('clears the previous reason when retrying', async () => {+ useElectronStore.setState({ gatewayConnectionError: { code: 'auth_failed' } });+ let finish!: (value: { success: boolean }) => void;+ vi.mocked(gatewayConnectionService.connect).mockReturnValue(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );++ const attempt = useElectronStore.getState().connectGateway();++ expect(useElectronStore.getState()).toMatchObject({+ gatewayConnectionError: undefined,+ gatewayConnectionStatus: 'connecting',+ });+ finish({ success: true });+ await act(() => attempt);+ });++ it('applies broadcast state, error included', () => {+ act(() => {+ useElectronStore.getState().setGatewayConnectionState({+ error: { code: 'config_unavailable', detail: 'HTTP 502' },+ status: 'disconnected',+ });+ });++ expect(useElectronStore.getState().gatewayConnectionError).toEqual({+ code: 'config_unavailable',+ detail: 'HTTP 502',+ });++ act(() => {+ useElectronStore.getState().setGatewayConnectionState({ status: 'connected' });+ });++ expect(useElectronStore.getState().gatewayConnectionError).toBeUndefined();+ });+});diff --git a/src/store/electron/actions/gateway.ts b/src/store/electron/actions/gateway.tsindex ab2878d610d..a55a570f4e2 100644--- a/src/store/electron/actions/gateway.ts+++ b/src/store/electron/actions/gateway.ts@@ -1,5 +1,5 @@import { isDesktop } from '@lobechat/const';-import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';+import type { GatewayConnectionState } from '@lobechat/electron-client-ipc';import { type SWRResponse } from 'swr';import useSWR from 'swr';@@ -30,11 +30,13 @@ export class ElectronGatewayActionImpl {}connectGateway = async (): Promise<void> => {- this.#set({ gatewayConnectionStatus: 'connecting' });+ this.#set({ gatewayConnectionError: undefined, gatewayConnectionStatus: 'connecting' });try {const result = await gatewayConnectionService.connect();if (!result.success) {- this.#set({ gatewayConnectionStatus: 'disconnected' });+ // The main process owns the outcome (and its reason); a superseded+ // attempt may already be connecting again, so take its state as is.+ this.setGatewayConnectionState(await gatewayConnectionService.getConnectionStatus());}} catch (error) {console.error('Gateway connect failed:', error);@@ -45,14 +47,18 @@ export class ElectronGatewayActionImpl {disconnectGateway = async (): Promise<void> => {try {await gatewayConnectionService.disconnect();- this.#set({ gatewayConnectionStatus: 'disconnected' });+ this.#set({ gatewayConnectionError: undefined, gatewayConnectionStatus: 'disconnected' });} catch (error) {console.error('Gateway disconnect failed:', error);}};- setGatewayConnectionStatus = (status: GatewayConnectionStatus): void => {- this.#set({ gatewayConnectionStatus: status }, false, 'setGatewayConnectionStatus');+ setGatewayConnectionState = ({ error, status }: GatewayConnectionState): void => {+ this.#set(+ { gatewayConnectionError: error, gatewayConnectionStatus: status },+ false,+ 'setGatewayConnectionState',+ );};/**@@ -94,15 +100,11 @@ export class ElectronGatewayActionImpl {);};- useFetchGatewayStatus = (): SWRResponse<{ status: GatewayConnectionStatus }> => {- return useSWR<{ status: GatewayConnectionStatus }>(+ useFetchGatewayStatus = (): SWRResponse<GatewayConnectionState> => {+ return useSWR<GatewayConnectionState>(isDesktop ? 'electron:getGatewayConnectionStatus' : null,async () => gatewayConnectionService.getConnectionStatus(),- {- onSuccess: (data) => {- this.#set({ gatewayConnectionStatus: data.status }, false, 'setGatewayConnectionStatus');- },- },+ { onSuccess: (data) => this.setGatewayConnectionState(data) },);};}diff --git a/src/store/electron/initialState.ts b/src/store/electron/initialState.tsindex 00e8f2a88e1..dc789045afb 100644--- a/src/store/electron/initialState.ts+++ b/src/store/electron/initialState.ts@@ -1,6 +1,7 @@import {type DataSyncConfig,type ElectronAppState,+ type GatewayConnectionError,type GatewayConnectionStatus,type NetworkProxySettings,} from '@lobechat/electron-client-ipc';@@ -29,6 +30,8 @@ export interface ElectronState extends CurrentRouteMetaState, RecentPagesState,appTrayVisible: boolean;dataSyncConfig: DataSyncConfig;desktopHotkeys: Record<string, string>;+ /** Why the last connection attempt ended, as reported by the main process. */+ gatewayConnectionError?: GatewayConnectionError;gatewayConnectionStatus: GatewayConnectionStatus;gatewayDeviceInfo?: GatewayDeviceInfo;isAppStateInit?: boolean;