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.

✨ feat(desktop): let a distribution set its own app identity (#21890)

LiJian337e7d4b3c10
diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjs
index 36a59b54b59..ed06f7a32be 100644
--- a/apps/desktop/electron-builder.mjs
+++ b/apps/desktop/electron-builder.mjs
@@ -39,7 +39,22 @@ const channel = process.env.UPDATE_CHANNEL;
const arch = os.arch();
const hasAppleCertificate = Boolean(process.env.CSC_LINK);
-const macAppId = 'com.lobehub.lobehub-desktop';
+/**
+ * Distribution identity. A downstream build (private deployment, white-label)
+ * sets these through env instead of forking this file; unset keeps upstream's
+ * values.
+ *
+ * `appId` is not cosmetic: the updater and the OS key the installed app's
+ * identity off it, so a distribution must pick one before its first release and
+ * never change it. The packaged `productName` (which names the per-user data
+ * directory) is stamped into package.json by
+ * `scripts/electronWorkflow/setDesktopVersion.ts` from the same
+ * DESKTOP_PRODUCT_NAME; `brandName` here is the channel-less form for
+ * user-facing strings.
+ */
+const appId = process.env.DESKTOP_APP_ID || 'com.lobehub.lobehub-desktop';
+const brandName = process.env.DESKTOP_PRODUCT_NAME || 'LobeHub';
+const executableName = process.env.DESKTOP_EXECUTABLE_NAME || 'LobeHub';
// Communication notifications need the restricted
// `com.apple.developer.usernotifications.communication` entitlement, and
// macOS refuses to launch an app carrying it without a provisioning profile
@@ -65,7 +80,7 @@ if (macCommunicationEntitlements) {
);
const communicationKeys = [
' <key>com.apple.application-identifier</key>',
- ` <string>${macTeamId}.${macAppId}</string>`,
+ ` <string>${macTeamId}.${appId}</string>`,
' <key>com.apple.developer.team-identifier</key>',
` <string>${macTeamId}</string>`,
' <key>com.apple.developer.usernotifications.communication</key>',
@@ -133,6 +148,22 @@ if (!hasAppleCertificate) {
// 根据版本类型确定协议 scheme
const getProtocolScheme = () => {
+ // Schemes are registered OS-wide, so a distribution needs its own: two builds
+ // claiming `lobehub://` on one machine race for the handler, and the loser's
+ // deep links and OAuth handoffs open the other app. Must match the value the
+ // main process is built with (see vite.main.config.ts).
+ const scheme = process.env.DESKTOP_PROTOCOL_SCHEME;
+ if (scheme) {
+ // URL parsing lowercases schemes, so the main process can only ever match a
+ // lowercase one — fail the build rather than ship an app that drops its own
+ // deep links.
+ if (!/^[a-z][\d+.a-z-]*$/.test(scheme)) {
+ throw new Error(
+ `DESKTOP_PROTOCOL_SCHEME "${scheme}" must be a lowercase URL scheme (a-z, then a-z, 0-9, "+", "-", ".")`,
+ );
+ }
+ return scheme;
+ }
if (isCanary) return 'lobehub-canary';
if (isNightly) return 'lobehub-nightly';
return 'lobehub';
@@ -295,7 +326,7 @@ const config = {
}
}
},
- appId: macAppId,
+ appId,
appImage: {
artifactName: '${productName}-${version}.${ext}',
},
@@ -383,7 +414,7 @@ const config = {
CFBundleIconName: 'AppIcon',
CFBundleURLTypes: [
{
- CFBundleURLName: 'LobeHub Protocol',
+ CFBundleURLName: `${brandName} Protocol`,
CFBundleURLSchemes: [protocolScheme],
},
],
@@ -394,8 +425,7 @@ const config = {
"Application requests access to the user's Documents folder.",
NSDownloadsFolderUsageDescription:
"Application requests access to the user's Downloads folder.",
- NSLocalNetworkUsageDescription:
- 'LobeHub connects to self-hosted servers, model providers, and other services on your local network.',
+ NSLocalNetworkUsageDescription: `${brandName} connects to self-hosted servers, model providers, and other services on your local network.`,
NSMicrophoneUsageDescription: "Application requests access to the device's microphone.",
NSScreenCaptureUsageDescription:
'Application requests access to record and analyze screen content for AI assistance.',
@@ -427,7 +457,7 @@ const config = {
},
protocols: [
{
- name: 'LobeHub Protocol',
+ name: `${brandName} Protocol`,
schemes: [protocolScheme],
},
],
@@ -490,7 +520,7 @@ const config = {
],
win: {
- executableName: 'LobeHub',
+ executableName,
},
};
diff --git a/apps/desktop/src/main/controllers/NotificationCtr.ts b/apps/desktop/src/main/controllers/NotificationCtr.ts
index 00c7009fdae..1d44c2feae7 100644
--- a/apps/desktop/src/main/controllers/NotificationCtr.ts
+++ b/apps/desktop/src/main/controllers/NotificationCtr.ts
@@ -4,6 +4,7 @@ import type {
} from '@lobechat/electron-client-ipc';
import { app, Notification } from 'electron';
+import { getDesktopEnv } from '@/env';
import { createLogger } from '@/utils/logger';
import * as electronIs from '@/utils/platform';
@@ -59,7 +60,7 @@ export default class NotificationCtr extends ControllerModule {
}
if (electronIs.windows()) {
- app.setAppUserModelId('com.lobehub.chat');
+ app.setAppUserModelId(getDesktopEnv().DESKTOP_APP_ID || 'com.lobehub.chat');
logger.debug('Set Windows App User Model ID for notifications');
}
diff --git a/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts
index 60cb6fdaff4..8bcfdaefec5 100644
--- a/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts
@@ -5,7 +5,8 @@ import type { App } from '@/core/App';
import NotificationCtr from '../NotificationCtr';
-const { ipcMainHandleMock, loggerMock } = vi.hoisted(() => ({
+const { desktopEnv, ipcMainHandleMock, loggerMock } = vi.hoisted(() => ({
+ desktopEnv: { DESKTOP_APP_ID: undefined as string | undefined },
ipcMainHandleMock: vi.fn(),
loggerMock: {
debug: vi.fn(),
@@ -15,6 +16,8 @@ const { ipcMainHandleMock, loggerMock } = vi.hoisted(() => ({
},
}));
+vi.mock('@/env', () => ({ getDesktopEnv: () => desktopEnv }));
+
vi.mock('@/utils/logger', () => ({
createLogger: () => loggerMock,
}));
@@ -123,6 +126,21 @@ describe('NotificationCtr', () => {
vi.mocked(windows).mockReturnValue(false);
});
+
+ it("should use the distribution's app ID on Windows when one is configured", async () => {
+ const { windows } = await import('@/utils/platform');
+ const { app, Notification } = await import('electron');
+ vi.mocked(windows).mockReturnValue(true);
+ vi.mocked(Notification.isSupported).mockReturnValue(true);
+ desktopEnv.DESKTOP_APP_ID = 'com.acme.work';
+
+ controller.afterAppReady();
+
+ expect(app.setAppUserModelId).toHaveBeenCalledWith('com.acme.work');
+
+ desktopEnv.DESKTOP_APP_ID = undefined;
+ vi.mocked(windows).mockReturnValue(false);
+ });
});
describe('showDesktopNotification', () => {
diff --git a/apps/desktop/src/main/env.ts b/apps/desktop/src/main/env.ts
index 349256f2498..e46745153cb 100644
--- a/apps/desktop/src/main/env.ts
+++ b/apps/desktop/src/main/env.ts
@@ -53,8 +53,10 @@ const envNumber = (defaultValue: number) =>
const getRuntimeEnv = () => ({
...process.env,
+ DESKTOP_APP_ID: process.env.DESKTOP_APP_ID,
DESKTOP_BACKEND_PROXY_RETHROW_ERRORS: process.env.DESKTOP_BACKEND_PROXY_RETHROW_ERRORS,
DESKTOP_EXTERNAL_NAVIGATION_HOSTS: process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS,
+ DESKTOP_PROTOCOL_SCHEME: process.env.DESKTOP_PROTOCOL_SCHEME,
UPDATE_CHANNEL: process.env.UPDATE_CHANNEL,
UPDATE_SERVER_URL: process.env.UPDATE_SERVER_URL,
});
@@ -83,8 +85,17 @@ export const getDesktopEnv = memoize(() =>
// main-process exceptions so Electron's default dialog can be reproduced.
DESKTOP_BACKEND_PROXY_RETHROW_ERRORS: envBoolean(false),
+ // Distribution identity, baked in at build time (vite.main.config.ts) and
+ // read by electron-builder.mjs too — the two must agree.
+ // Windows AppUserModelID; unset keeps upstream's.
+ DESKTOP_APP_ID: z.string().optional(),
+
DESKTOP_EXTERNAL_NAVIGATION_HOSTS: z.string().optional().default(''),
+ // Deep-link / OAuth-handoff scheme the OS routes to this app; unset keeps
+ // the channel-derived `lobehub*` scheme.
+ DESKTOP_PROTOCOL_SCHEME: z.string().optional(),
+
// device gateway url override (dev: point at a local `wrangler dev` instance,
// e.g. http://localhost:8787). Falls back to the stored value, then the
// production gateway.
diff --git a/apps/desktop/src/main/utils/__tests__/protocol.test.ts b/apps/desktop/src/main/utils/__tests__/protocol.test.ts
index facc00b2733..8b52c6f2400 100644
--- a/apps/desktop/src/main/utils/__tests__/protocol.test.ts
+++ b/apps/desktop/src/main/utils/__tests__/protocol.test.ts
@@ -1,7 +1,17 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import type { McpSchema } from '../../types/protocol';
-import { generateRFCProtocolUrl, parseProtocolUrl } from '../protocol';
+import { generateRFCProtocolUrl, getProtocolScheme, parseProtocolUrl } from '../protocol';
+
+const desktopEnv = vi.hoisted(() => ({
+ DESKTOP_PROTOCOL_SCHEME: undefined as string | undefined,
+}));
+
+vi.mock('@/env', () => ({ getDesktopEnv: () => desktopEnv }));
+
+afterEach(() => {
+ desktopEnv.DESKTOP_PROTOCOL_SCHEME = undefined;
+});
describe('Protocol', () => {
describe('generateRFCProtocolUrl', () => {
@@ -200,4 +210,35 @@ describe('Protocol', () => {
});
});
});
+
+ describe('distribution scheme override', () => {
+ it('uses the configured scheme instead of the channel heuristics', () => {
+ desktopEnv.DESKTOP_PROTOCOL_SCHEME = 'acme';
+
+ expect(getProtocolScheme()).toBe('acme');
+ });
+
+ it('accepts deep links on the configured scheme', () => {
+ desktopEnv.DESKTOP_PROTOCOL_SCHEME = 'acme';
+
+ expect(parseProtocolUrl('acme://plugin/install?id=figma')).toMatchObject({
+ action: 'install',
+ urlType: 'plugin',
+ });
+ });
+
+ it('matches a mixed-case override against the lowercased scheme URL parsing yields', () => {
+ desktopEnv.DESKTOP_PROTOCOL_SCHEME = 'Acme';
+
+ expect(getProtocolScheme()).toBe('acme');
+ expect(parseProtocolUrl('Acme://plugin/install?id=figma')).toMatchObject({
+ action: 'install',
+ urlType: 'plugin',
+ });
+ });
+
+ it('still rejects schemes that are neither upstream nor configured', () => {
+ expect(parseProtocolUrl('acme://plugin/install?id=figma')).toBeNull();
+ });
+ });
});
diff --git a/apps/desktop/src/main/utils/protocol.ts b/apps/desktop/src/main/utils/protocol.ts
index 42dfe8b1446..fc3385bf691 100644
--- a/apps/desktop/src/main/utils/protocol.ts
+++ b/apps/desktop/src/main/utils/protocol.ts
@@ -1,10 +1,26 @@
import { app } from 'electron';
+import { getDesktopEnv } from '@/env';
+
import type { McpSchema, ProtocolUrlParsed } from '../types/protocol';
export type AppChannel = 'stable' | 'beta' | 'nightly';
+/**
+ * The distribution's scheme, lowercased: `new URL()` lowercases the scheme it
+ * parses, so a mixed-case value would never match an incoming link. The build
+ * rejects non-lowercase values (electron-builder.mjs); this keeps the runtime
+ * consistent even if one slips through.
+ */
+const getSchemeOverride = () => getDesktopEnv().DESKTOP_PROTOCOL_SCHEME?.toLowerCase();
+
export const getProtocolScheme = (): string => {
+ // A distribution owns its scheme outright. The heuristics below only know
+ // upstream's names, so a renamed build would fall through to `lobehub` and
+ // fight an official install on the same machine for its deep links.
+ const override = getSchemeOverride();
+ if (override) return override;
+
// In Electron environment, version can be determined in multiple ways
const bundleId = app.name;
const appPath = app.getPath('exe');
@@ -99,6 +115,8 @@ export const parseProtocolUrl = (url: string): ProtocolUrlParsed | null => {
// Support multiple protocol schemes
const validProtocols = ['lobehub:', 'lobehub-dev:', 'lobehub-nightly:', 'lobehub-beta:'];
+ const override = getSchemeOverride();
+ if (override) validProtocols.push(`${override}:`);
if (!validProtocols.includes(parsedUrl.protocol)) {
return null;
}
diff --git a/apps/desktop/vite.main.config.ts b/apps/desktop/vite.main.config.ts
index 1aed6bdc70a..a34deaef91e 100644
--- a/apps/desktop/vite.main.config.ts
+++ b/apps/desktop/vite.main.config.ts
@@ -116,6 +116,12 @@ export default defineConfig(async (env) => {
},
define: {
...processEnvDefine,
+ // Distribution identity. A packaged app has no shell env to inherit, so
+ // these must be baked in; electron-builder.mjs reads the same variables
+ // for the OS-level registration, and a mismatch leaves the app listening
+ // on a scheme the OS never routes to it.
+ 'process.env.DESKTOP_APP_ID': JSON.stringify(process.env.DESKTOP_APP_ID),
+ 'process.env.DESKTOP_PROTOCOL_SCHEME': JSON.stringify(process.env.DESKTOP_PROTOCOL_SCHEME),
'process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS': JSON.stringify(externalNavigationHosts),
'process.env.RENDERER_OTA_PUBLIC_KEY': JSON.stringify(process.env.RENDERER_OTA_PUBLIC_KEY),
'process.env.UPDATE_CHANNEL': JSON.stringify(process.env.UPDATE_CHANNEL),
diff --git a/scripts/electronWorkflow/setDesktopVersion.ts b/scripts/electronWorkflow/setDesktopVersion.ts
index 4b430f0fd9a..5297341aa4b 100644
--- a/scripts/electronWorkflow/setDesktopVersion.ts
+++ b/scripts/electronWorkflow/setDesktopVersion.ts
@@ -28,6 +28,40 @@ const rootDir = path.resolve(__dirname, '../..');
// Path to the desktop app package.json
const desktopPackageJsonPath = path.join(rootDir, 'apps/desktop/package.json');
+
+/**
+ * Distribution identity (white-label / private builds); unset keeps upstream's.
+ *
+ * `productName` is what Electron names the per-user data directory after, and
+ * the shell reads that directory before any app code runs — so it has to be
+ * right in the packaged manifest, which is this file. Same permanence as
+ * DESKTOP_APP_ID: changing it after a release leaves existing installs on an
+ * empty profile.
+ *
+ * `name` reaches Linux packages (deb/rpm package name, WM_CLASS), so it is
+ * derived from the product name unless DESKTOP_PACKAGE_NAME pins it.
+ */
+const distributionName = process.env.DESKTOP_PRODUCT_NAME?.trim();
+const brandName = distributionName || 'LobeHub';
+
+const resolvePackageBaseName = () => {
+ if (process.env.DESKTOP_PACKAGE_NAME) return process.env.DESKTOP_PACKAGE_NAME;
+ if (!distributionName) return 'lobehub-desktop';
+
+ const slug = distributionName
+ .toLowerCase()
+ .replaceAll(/[^\da-z]+/g, '-')
+ .replaceAll(/^-|-$/g, '');
+ if (!slug) {
+ console.error(
+ `❌ DESKTOP_PRODUCT_NAME "${distributionName}" has no ASCII letters or digits to derive a package name from; set DESKTOP_PACKAGE_NAME.`,
+ );
+ process.exit(1);
+ }
+ return `${slug}-desktop`;
+};
+
+const packageBaseName = resolvePackageBaseName();
const buildDir = path.join(rootDir, 'apps/desktop/build');
// Update app icon
@@ -76,28 +110,28 @@ function updatePackageJson() {
// Modify other fields based on releaseType
switch (releaseType) {
case 'stable': {
- packageJson.productName = 'LobeHub';
- packageJson.name = 'lobehub-desktop';
+ packageJson.productName = brandName;
+ packageJson.name = packageBaseName;
console.log('🌟 Setting as Stable version.');
break;
}
case 'beta': {
- packageJson.productName = 'LobeHub-Beta'; // Or 'LobeHub-Beta' if preferred
- packageJson.name = 'lobehub-desktop-beta'; // Or 'lobehub-desktop' if preferred
+ packageJson.productName = `${brandName}-Beta`;
+ packageJson.name = `${packageBaseName}-beta`;
console.log('🧪 Setting as Beta version.');
updateAppIcon('beta');
break;
}
case 'nightly': {
- packageJson.productName = 'LobeHub-Nightly'; // Or 'LobeHub-Nightly'
- packageJson.name = 'lobehub-desktop-nightly'; // Or 'lobehub-desktop-nightly'
+ packageJson.productName = `${brandName}-Nightly`;
+ packageJson.name = `${packageBaseName}-nightly`;
console.log('🌙 Setting as Nightly version.');
updateAppIcon('nightly');
break;
}
case 'canary': {
- packageJson.productName = 'LobeHub';
- packageJson.name = 'lobehub-desktop-canary';
+ packageJson.productName = brandName;
+ packageJson.name = `${packageBaseName}-canary`;
console.log('🐤 Setting as Canary version (same app name and icon as stable).');
break;
}