Skip to content

🀯 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.

πŸ› fix(desktop): stop crashing the main process when a user folder cannot be resolved (#19598)

Innei101c110474ed
diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.ts
index 390f3fc213b..14241e29a49 100644
--- a/apps/desktop/src/main/controllers/SystemCtr.ts
+++ b/apps/desktop/src/main/controllers/SystemCtr.ts
@@ -17,6 +17,7 @@ import {
} from '@/utils/permissions';
import * as electronIs from '@/utils/platform';
import { getSystemLanguage, resolveUILocale } from '@/utils/system-language';
+import { safeGetPath } from '@/utils/user-path';
import { ControllerModule, IpcMethod } from './index';
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
@@ -65,12 +66,12 @@ export default class SystemController extends ControllerModule {
// User Paths (ensure keys match UserPathData / DesktopAppState interface)
desktop: app.getPath('desktop'),
documents: app.getPath('documents'),
- downloads: app.getPath('downloads'),
+ downloads: safeGetPath('downloads'),
home: app.getPath('home'),
- music: app.getPath('music'),
- pictures: app.getPath('pictures'),
+ music: safeGetPath('music'),
+ pictures: safeGetPath('pictures'),
userData: app.getPath('userData'),
- videos: app.getPath('videos'),
+ videos: safeGetPath('videos'),
},
};
}
diff --git a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
index 562d07adfb7..8d711053e6f 100644
--- a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
@@ -175,6 +175,25 @@ describe('SystemController', () => {
},
});
});
+
+ it('omits user folders that Electron cannot resolve instead of throwing', async () => {
+ const { app } = await import('electron');
+ const getPath = vi.mocked(app.getPath);
+ const original = getPath.getMockImplementation();
+ getPath.mockImplementation((name: string) => {
+ if (name === 'pictures') throw new Error("Failed to get 'pictures' path");
+ return `/mock/path/${name}`;
+ });
+
+ try {
+ const result = await invokeIpc('system.getAppState');
+
+ expect(result.userPath.pictures).toBeUndefined();
+ expect(result.userPath.home).toBe('/mock/path/home');
+ } finally {
+ getPath.mockImplementation(original!);
+ }
+ });
});
describe('desktop onboarding', () => {
diff --git a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts
new file mode 100644
index 00000000000..53167fc1dfb
--- /dev/null
+++ b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts
@@ -0,0 +1,93 @@
+import type { GatewayClient } from '@lobechat/device-gateway-client';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import GatewayConnectionService from '../gatewayConnectionSrv';
+
+const { getShellInfoMock } = vi.hoisted(() => ({ getShellInfoMock: vi.fn() }));
+
+vi.mock('electron', () => ({
+ app: {
+ getPath: vi.fn((name: string) => `/mock/path/${name}`),
+ getVersion: vi.fn(() => '0.0.0-test'),
+ },
+ powerSaveBlocker: { start: vi.fn(), stop: vi.fn() },
+}));
+
+vi.mock('@lobechat/local-file-shell/shell', () => ({ getShellInfo: getShellInfoMock }));
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),
+}));
+
+const createClient = () =>
+ ({ sendSystemInfoResponse: vi.fn() }) as unknown as GatewayClient & {
+ sendSystemInfoResponse: ReturnType<typeof vi.fn>;
+ };
+
+describe('GatewayConnectionService system_info_request', () => {
+ let service: GatewayConnectionService;
+
+ beforeEach(() => {
+ getShellInfoMock.mockReset();
+ service = new GatewayConnectionService({} as App);
+ });
+
+ it('answers with the collected system info', async () => {
+ getShellInfoMock.mockResolvedValue({ displayName: 'zsh' });
+ const client = createClient();
+
+ await (service as any).handleSystemInfoRequest(client, { requestId: 'req-1' });
+
+ expect(client.sendSystemInfoResponse).toHaveBeenCalledWith({
+ requestId: 'req-1',
+ result: {
+ success: true,
+ systemInfo: expect.objectContaining({
+ defaultShell: 'zsh',
+ homePath: '/mock/path/home',
+ picturesPath: '/mock/path/pictures',
+ }),
+ },
+ });
+ });
+
+ it('omits an optional folder Electron cannot resolve and still answers successfully', async () => {
+ getShellInfoMock.mockResolvedValue({ displayName: 'pwsh' });
+ const { app } = await import('electron');
+ const getPath = vi.mocked(app.getPath);
+ const original = getPath.getMockImplementation();
+ getPath.mockImplementation((name: string) => {
+ if (name === 'pictures') throw new Error("Failed to get 'pictures' path");
+ return `/mock/path/${name}`;
+ });
+ const client = createClient();
+
+ try {
+ await (service as any).handleSystemInfoRequest(client, { requestId: 'req-3' });
+ } finally {
+ getPath.mockImplementation(original!);
+ }
+
+ const [response] = client.sendSystemInfoResponse.mock.calls[0];
+ expect(response.requestId).toBe('req-3');
+ expect(response.result.success).toBe(true);
+ expect(response.result.systemInfo.picturesPath).toBeUndefined();
+ expect(response.result.systemInfo.homePath).toBe('/mock/path/home');
+ });
+
+ it('still answers with a failure when collecting system info rejects', async () => {
+ getShellInfoMock.mockRejectedValue(new Error('shell probe failed'));
+ const client = createClient();
+
+ await expect(
+ (service as any).handleSystemInfoRequest(client, { requestId: 'req-2' }),
+ ).resolves.toBeUndefined();
+
+ expect(client.sendSystemInfoResponse).toHaveBeenCalledWith({
+ requestId: 'req-2',
+ result: { success: false },
+ });
+ });
+});
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 61a2a09c80e..2a5647b743f 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -9,6 +9,7 @@ import type {
} from '@lobechat/device-control';
import type {
AgentRunRequestMessage,
+ DeviceSystemInfo,
GatewayClient,
GatewayMcpParams,
MessageApiRequestMessage,
@@ -25,6 +26,7 @@ import { isDev } from '@/const/env';
import { getDesktopEnv } from '@/env';
import { createLogger } from '@/utils/logger';
import { getDesktopUserAgent } from '@/utils/user-agent';
+import { safeGetPath } from '@/utils/user-path';
import { ServiceModule } from './index';
@@ -444,7 +446,7 @@ export default class GatewayConnectionService extends ServiceModule {
});
client.on('system_info_request', (request) => {
- this.handleSystemInfoRequest(client, request);
+ void this.handleSystemInfoRequest(client, request);
});
client.on('rpc_request', (request) => {
@@ -697,28 +699,36 @@ export default class GatewayConnectionService extends ServiceModule {
*/
private async handleSystemInfoRequest(client: GatewayClient, request: SystemInfoRequestMessage) {
logger.info(`Received system_info_request: requestId=${request.requestId}`);
+ try {
+ client.sendSystemInfoResponse({
+ requestId: request.requestId,
+ result: { success: true, systemInfo: await this.collectSystemInfo() },
+ });
+ } catch (error) {
+ // The gateway keeps the agent run parked until a correlated reply arrives,
+ // so a failed collection must still answer instead of only logging.
+ logger.error(`system_info_request failed: requestId=${request.requestId}`, error);
+ client.sendSystemInfoResponse({ requestId: request.requestId, result: { success: false } });
+ }
+ }
+
+ private async collectSystemInfo(): Promise<DeviceSystemInfo> {
const { getShellInfo } = await import('@lobechat/local-file-shell/shell');
- client.sendSystemInfoResponse({
- requestId: request.requestId,
- result: {
- success: true,
- systemInfo: {
- supportedTools: ['lobe-computer-use'],
- arch: os.arch(),
- // Tell the server-side prompt builder which shell runCommand spawns here.
- defaultShell: (await getShellInfo()).displayName,
- desktopPath: app.getPath('desktop'),
- documentsPath: app.getPath('documents'),
- downloadsPath: app.getPath('downloads'),
- homePath: app.getPath('home'),
- musicPath: app.getPath('music'),
- picturesPath: app.getPath('pictures'),
- userDataPath: app.getPath('userData'),
- videosPath: app.getPath('videos'),
- workingDirectory: process.cwd(),
- },
- },
- });
+ return {
+ supportedTools: ['lobe-computer-use'],
+ arch: os.arch(),
+ // Tell the server-side prompt builder which shell runCommand spawns here.
+ defaultShell: (await getShellInfo()).displayName,
+ desktopPath: app.getPath('desktop'),
+ documentsPath: app.getPath('documents'),
+ downloadsPath: safeGetPath('downloads'),
+ homePath: app.getPath('home'),
+ musicPath: safeGetPath('music'),
+ picturesPath: safeGetPath('pictures'),
+ userDataPath: app.getPath('userData'),
+ videosPath: safeGetPath('videos'),
+ workingDirectory: process.cwd(),
+ };
}
// ─── Generic Device RPC ───
diff --git a/apps/desktop/src/main/utils/user-path.test.ts b/apps/desktop/src/main/utils/user-path.test.ts
new file mode 100644
index 00000000000..34b0739df72
--- /dev/null
+++ b/apps/desktop/src/main/utils/user-path.test.ts
@@ -0,0 +1,25 @@
+import { app } from 'electron';
+import { describe, expect, it, vi } from 'vitest';
+
+import { safeGetPath } from './user-path';
+
+vi.mock('electron', () => ({ app: { getPath: vi.fn() } }));
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({ warn: vi.fn() }),
+}));
+
+describe('safeGetPath', () => {
+ it('returns the resolved path', () => {
+ vi.mocked(app.getPath).mockReturnValue('/home/u/Pictures');
+
+ expect(safeGetPath('pictures')).toBe('/home/u/Pictures');
+ });
+
+ it('returns undefined instead of throwing when the folder cannot be resolved', () => {
+ vi.mocked(app.getPath).mockImplementation(() => {
+ throw new Error("Failed to get 'pictures' path");
+ });
+
+ expect(safeGetPath('pictures')).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/utils/user-path.ts b/apps/desktop/src/main/utils/user-path.ts
new file mode 100644
index 00000000000..c9609d61a0e
--- /dev/null
+++ b/apps/desktop/src/main/utils/user-path.ts
@@ -0,0 +1,19 @@
+import { app } from 'electron';
+
+import { createLogger } from '@/utils/logger';
+
+const logger = createLogger('utils:user-path');
+
+type UserPathName = Parameters<typeof app.getPath>[0];
+
+// Windows resolves these through Known Folders; a redirected or missing
+// folder (e.g. OneDrive "Pictures") makes app.getPath throw instead of
+// returning a fallback.
+export const safeGetPath = (name: UserPathName): string | undefined => {
+ try {
+ return app.getPath(name);
+ } catch (error) {
+ logger.warn(`app.getPath('${name}') failed:`, error);
+ return undefined;
+ }
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index 1458d29a952..f877319b6aa 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -411,7 +411,9 @@ export const prepareOperation = async (
// instead of the new PowerShell default.
const defaultShell =
systemInfo.defaultShell ?? (device?.platform === 'win32' ? 'cmd.exe' : '/bin/sh');
- return {
+ // Optional folders the device could not resolve must stay absent so the
+ // template falls back to '(not reported)' instead of rendering undefined.
+ const reported = {
arch: systemInfo.arch,
defaultShell,
desktopPath: systemInfo.desktopPath,
@@ -433,6 +435,9 @@ export const prepareOperation = async (
// persisted device row in resolveWorkspaceInit and written onto
// deviceSystemInfo.workingDirectory at the call site below.
};
+ return Object.fromEntries(
+ Object.entries(reported).filter(([, value]) => value !== undefined),
+ ) as Record<string, string>;
} catch (error) {
log('execAgent: failed to fetch device system info: %O', error);
return {};
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 5e5dbfc6f39..13a557c8e7e 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -771,6 +771,16 @@ describe('GatewayHttpClient', () => {
expect(result).toEqual({ success: false });
});
+ it('bounds the read with a timeout', async () => {
+ mockFetch({ json: vi.fn().mockResolvedValue({ success: true, systemInfo: {} }), ok: true });
+
+ await client.getDeviceSystemInfo('user-1', 'device-1');
+
+ // Without a deadline an unanswered device would park the agent run for
+ // as long as the socket stays open instead of degrading to no system info.
+ expect(vi.mocked(fetch).mock.calls[0][1]).toMatchObject({ signal: expect.anything() });
+ });
+
it('should handle missing success field', async () => {
mockFetch({
json: vi.fn().mockResolvedValue({}),
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index ed3fd24fe18..50197717081 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -355,7 +355,11 @@ export class GatewayHttpClient {
deviceId: string,
workspaceId?: string,
): Promise<{ success: boolean; systemInfo?: DeviceSystemInfo }> {
- const res = await this.post('/api/device/system-info', { deviceId, userId, workspaceId });
+ const res = await this.post(
+ '/api/device/system-info',
+ { deviceId, userId, workspaceId },
+ { timeout: DEVICE_QUERY_TIMEOUT_MS },
+ );
if (!res.ok) {
return { success: false };
}
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index dcb9d504c8f..55cab48be48 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -34,14 +34,14 @@ export interface DeviceSystemInfo {
defaultShell?: string;
desktopPath: string;
documentsPath: string;
- downloadsPath: string;
+ downloadsPath?: string;
homePath: string;
- musicPath: string;
- picturesPath: string;
+ musicPath?: string;
+ picturesPath?: string;
/** Opt-in tool identifiers supported by this client; absent on older clients. */
supportedTools?: string[];
userDataPath: string;
- videosPath: string;
+ videosPath?: string;
workingDirectory: string;
}
@@ -193,7 +193,7 @@ export interface SystemInfoResponseMessage {
requestId: string;
result: {
success: boolean;
- systemInfo: DeviceSystemInfo;
+ systemInfo?: DeviceSystemInfo;
};
type: 'system_info_response';
}