🤯 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(desktop): bundle LobeHub Computer Use.app in macOS builds (#20780)
Nekoca2b24cfdf22
diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjsindex 17a5bc5a2f3..dc68f5cd9a5 100644--- a/apps/desktop/electron-builder.mjs+++ b/apps/desktop/electron-builder.mjs@@ -14,6 +14,13 @@ import {getAsarUnpackPatterns,getNativeModulesFilesConfig,} from './native-deps.config.mjs';+import {+ COMPUTER_USE_HELPER_BUNDLE_PATH,+ COMPUTER_USE_HELPER_SIGN_IGNORE,+ embedComputerUseHelper,+ resolveComputerUseHelperVersion,+ verifyComputerUseHelper,+} from './scripts/computerUseHelper.mjs';import { packBuiltinCore } from './scripts/packBuiltinCore.mjs';import { toSparkleBuildVersion } from './scripts/sparkleBuildVersion.mjs';import { resolveSparklePackaging } from './scripts/sparklePackaging.mjs';@@ -25,6 +32,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const packageJSON = JSON.parse(await fs.readFile(path.join(__dirname, 'package.json'), 'utf8'));+const computerUseHelperVersion = resolveComputerUseHelperVersion(packageJSON);+const channel = process.env.UPDATE_CHANNEL;const arch = os.arch();const hasAppleCertificate = Boolean(process.env.CSC_LINK);@@ -220,12 +229,19 @@ const config = {return;}- const resourcesPath = path.join(- context.appOutDir,- `${context.packager.appInfo.productFilename}.app`,- 'Contents',- 'Resources',- );+ const appPath = path.join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`);+ const resourcesPath = path.join(appPath, 'Contents', 'Resources');++ // The Mac App Store sandbox cannot register the helper's LaunchAgent.+ if (context.electronPlatformName === 'darwin') {+ await embedComputerUseHelper({+ appPath,+ arch: arch === 'arm64' ? 'arm64' : 'x64',+ cacheDir: path.join(__dirname, 'node_modules', '.cache', 'lobehub-computer-use'),+ version: computerUseHelperVersion,+ });+ }+const iconFileName = getIconFileName();const assetsCarSource = path.join(__dirname, 'build', `${iconFileName}.Assets.car`);const assetsCarDest = path.join(resourcesPath, 'Assets.car');@@ -240,7 +256,21 @@ const config = {console.info(`⏭️ Skipping Assets.car (not found or copy failed)`);}},- afterSign: verifyFontListSignature,+ afterSign: async (context) => {+ await verifyFontListSignature(context);++ if (context.electronPlatformName === 'darwin') {+ verifyComputerUseHelper(+ path.join(+ context.appOutDir,+ `${context.packager.appInfo.productFilename}.app`,+ COMPUTER_USE_HELPER_BUNDLE_PATH,+ ),+ { version: computerUseHelperVersion },+ );+ console.info('✅ Computer Use helper kept its notarized signature');+ }+ },appId: macAppId,appImage: {artifactName: '${productName}-${version}.${ext}',@@ -349,6 +379,8 @@ const config = {},gatekeeperAssess: false,hardenedRuntime: hasAppleCertificate,+ // Ship the notarized helper as built; re-signing drops its stapled ticket.+ signIgnore: [COMPUTER_USE_HELPER_SIGN_IGNORE],notarize: hasAppleCertificate,...(hasAppleCertificate ? {} : { identity: null }),target: [diff --git a/apps/desktop/scripts/__tests__/computerUseHelper.test.mjs b/apps/desktop/scripts/__tests__/computerUseHelper.test.mjsnew file mode 100644index 00000000000..b024114e45d--- /dev/null+++ b/apps/desktop/scripts/__tests__/computerUseHelper.test.mjs@@ -0,0 +1,160 @@+import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ COMPUTER_USE_HELPER_SIGN_IGNORE,+ downloadComputerUseHelper,+ embedComputerUseHelper,+ resolveComputerUseHelperAsset,+ resolveComputerUseHelperVersion,+ verifyComputerUseHelper,+} from '../computerUseHelper.mjs';++const SIGNATURE = [+ 'Executable=/x/LobeHub Computer Use.app/Contents/MacOS/auv-device-helper-macos',+ 'Identifier=com.lobehub.lobehub-desktop.computer-use',+ 'TeamIdentifier=4684H589ZU',+].join('\n');++const createExecute = ({ signature = SIGNATURE, version = '0.0.33' } = {}) =>+ vi.fn((command, args) => {+ if (command === 'codesign' && args[0] === '--display') {+ return { status: 0, stderr: signature, stdout: '' };+ }+ if (command === 'plutil') return { status: 0, stderr: '', stdout: `${version}\n` };+ return { status: 0, stderr: '', stdout: '' };+ });++const archive = Buffer.from('helper zip');+const checksum = createHash('sha256').update(archive).digest('hex');++const createFetch = ({ body = archive, sum = checksum } = {}) =>+ vi.fn(async (url) => {+ const payload = url.endsWith('.sha256') ? Buffer.from(`${sum} helper.zip\n`) : body;+ return { arrayBuffer: async () => payload, ok: true, status: 200 };+ });++const logger = { info: vi.fn() };++describe('Computer Use helper packaging', () => {+ let cacheDir;++ beforeEach(async () => {+ cacheDir = await fs.mkdtemp(path.join(os.tmpdir(), 'computer-use-test-'));+ });++ afterEach(async () => {+ await fs.rm(cacheDir, { force: true, recursive: true });+ });++ it('selects the helper release matching the pinned AUV CLI', () => {+ const version = resolveComputerUseHelperVersion({ dependencies: { '@auv-js/cli': '0.0.33' } });+ expect(resolveComputerUseHelperAsset({ arch: 'arm64', version })).toEqual({+ checksumUrl:+ 'https://github.com/lobehub/lobehub-auv/releases/download/v0.0.33/LobeHub-Computer-Use-0.0.33-arm64.zip.sha256',+ name: 'LobeHub-Computer-Use-0.0.33-arm64.zip',+ url: 'https://github.com/lobehub/lobehub-auv/releases/download/v0.0.33/LobeHub-Computer-Use-0.0.33-arm64.zip',+ });+ expect(() =>+ resolveComputerUseHelperVersion({ dependencies: { '@auv-js/cli': '^0.0.33' } }),+ ).toThrow(/exact version/);+ expect(() => resolveComputerUseHelperAsset({ arch: 'ia32', version })).toThrow();+ });++ it('keeps electron-builder from re-signing anything inside the helper bundle', () => {+ const pattern = new RegExp(COMPUTER_USE_HELPER_SIGN_IGNORE);+ const helper = '/out/LobeHub.app/Contents/Library/Helpers/LobeHub Computer Use.app';+ expect(pattern.test(helper)).toBe(true);+ expect(pattern.test(`${helper}/Contents/MacOS/auv-device-helper-macos`)).toBe(true);+ expect(pattern.test('/out/LobeHub.app')).toBe(false);+ expect(pattern.test('/out/LobeHub.app/Contents/Resources/bin/auv')).toBe(false);+ });++ it('downloads once and reuses the cached zip while its checksum matches', async () => {+ const fetchImpl = createFetch();+ const first = await downloadComputerUseHelper({+ arch: 'x64',+ cacheDir,+ fetchImpl,+ logger,+ version: '0.0.33',+ });+ await expect(fs.readFile(first)).resolves.toEqual(archive);+ expect(fetchImpl).toHaveBeenCalledTimes(2);++ await downloadComputerUseHelper({+ arch: 'x64',+ cacheDir,+ fetchImpl,+ logger,+ version: '0.0.33',+ });+ // Only the checksum is fetched again.+ expect(fetchImpl).toHaveBeenCalledTimes(3);+ });++ it('rejects a zip that does not match the published checksum', async () => {+ await expect(+ downloadComputerUseHelper({+ arch: 'arm64',+ cacheDir,+ fetchImpl: createFetch({ body: Buffer.from('tampered') }),+ logger,+ version: '0.0.33',+ }),+ ).rejects.toThrow(/Checksum mismatch/);+ });++ it('accepts only the notarized LobeHub identity at the expected version', () => {+ const appPath = '/x/LobeHub Computer Use.app';+ const execute = createExecute();+ verifyComputerUseHelper(appPath, { execute, version: '0.0.33' });+ expect(execute.mock.calls.map(([command, args]) => [command, args[0]])).toEqual([+ ['codesign', '--verify'],+ ['codesign', '--display'],+ ['xcrun', 'stapler'],+ ['plutil', '-extract'],+ ]);++ expect(() =>+ verifyComputerUseHelper(appPath, {+ execute: createExecute({ signature: SIGNATURE.replace('4684H589ZU', 'OTHERTEAM1') }),+ }),+ ).toThrow(/Unexpected Computer Use helper signature/);+ expect(() =>+ verifyComputerUseHelper(appPath, {+ execute: createExecute({ version: '0.0.32' }),+ version: '0.0.33',+ }),+ ).toThrow(/expected 0.0.33/);+ });++ it('copies the verified helper into Contents/Library/Helpers with ditto', async () => {+ const execute = createExecute();+ const appPath = path.join(cacheDir, 'LobeHub.app');+ const destination = await embedComputerUseHelper({+ appPath,+ arch: 'arm64',+ cacheDir,+ execute,+ fetchImpl: createFetch(),+ logger,+ version: '0.0.33',+ });++ expect(destination).toBe(+ path.join(appPath, 'Contents', 'Library', 'Helpers', 'LobeHub Computer Use.app'),+ );+ const dittoCalls = execute.mock.calls.filter(([command]) => command === 'ditto');+ expect(dittoCalls[0][1].slice(0, 3)).toEqual([+ '-x',+ '-k',+ path.join(cacheDir, 'LobeHub-Computer-Use-0.0.33-arm64.zip'),+ ]);+ expect(dittoCalls[1][1][1]).toBe(destination);+ });+});diff --git a/apps/desktop/scripts/computerUseHelper.mjs b/apps/desktop/scripts/computerUseHelper.mjsnew file mode 100644index 00000000000..e3521b0a9a0--- /dev/null+++ b/apps/desktop/scripts/computerUseHelper.mjs@@ -0,0 +1,173 @@+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++/**+ * LobeHub Computer Use.app is the LobeHub-branded AUV macOS helper, built,+ * signed and notarized by https://github.com/lobehub/lobehub-auv. It ships+ * inside LobeHub.app untouched: re-signing it would discard its stapled+ * notarization ticket and change the identity that the AUV daemon trusts.+ */+export const COMPUTER_USE_HELPER_APP_NAME = 'LobeHub Computer Use.app';+export const COMPUTER_USE_HELPER_BUNDLE_ID = 'com.lobehub.lobehub-desktop.computer-use';+export const COMPUTER_USE_HELPER_TEAM_ID = '4684H589ZU';+export const COMPUTER_USE_HELPER_RELEASE_REPO = 'lobehub/lobehub-auv';++/** Location inside LobeHub.app, relative to the bundle root. */+export const COMPUTER_USE_HELPER_BUNDLE_PATH = path.posix.join(+ 'Contents',+ 'Library',+ 'Helpers',+ COMPUTER_USE_HELPER_APP_NAME,+);++/** electron-builder `mac.signIgnore` pattern that keeps the helper's own signature. */+export const COMPUTER_USE_HELPER_SIGN_IGNORE =+ '/Contents/Library/Helpers/LobeHub Computer Use\\.app(/|$)';++const EXACT_VERSION = /^\d+\.\d+\.\d+$/;++/**+ * The helper release shares its version with AUV, so the pinned `@auv-js/cli`+ * version selects the matching helper.+ */+export const resolveComputerUseHelperVersion = (packageJSON) => {+ const version = packageJSON.dependencies?.['@auv-js/cli'];+ if (!version || !EXACT_VERSION.test(version)) {+ throw new Error(+ `@auv-js/cli must be pinned to an exact version to select the Computer Use helper, got: ${version}`,+ );+ }+ return version;+};++export const resolveComputerUseHelperAsset = ({ arch, version }) => {+ if (arch !== 'arm64' && arch !== 'x64') {+ throw new Error(`Unsupported macOS architecture for the Computer Use helper: ${arch}`);+ }+ const name = `LobeHub-Computer-Use-${version}-${arch}.zip`;+ const url = `https://github.com/${COMPUTER_USE_HELPER_RELEASE_REPO}/releases/download/v${version}/${name}`;+ return { checksumUrl: `${url}.sha256`, name, url };+};++const run = (execute, command, args) => {+ const result = execute(command, args, { encoding: 'utf8' });+ if (result.error) throw result.error;+ if (result.status !== 0) {+ throw new Error(+ `${command} ${args.join(' ')} exited with ${result.status}: ${(result.stderr || result.stdout || '').trim()}`,+ );+ }+ return result;+};++const sha256 = (buffer) => createHash('sha256').update(buffer).digest('hex');++const download = async (fetchImpl, url) => {+ const response = await fetchImpl(url);+ if (!response.ok) throw new Error(`Failed to download ${url}: HTTP ${response.status}`);+ return Buffer.from(await response.arrayBuffer());+};++/**+ * Checks that an unpacked helper is the notarized LobeHub build of `version`.+ * Run before embedding and again after LobeHub.app is signed, which proves+ * electron-builder left the helper's signature and ticket alone.+ */+export const verifyComputerUseHelper = (appPath, { execute = spawnSync, version } = {}) => {+ run(execute, 'codesign', ['--verify', '--strict', '--deep', '--verbose=2', appPath]);++ // codesign prints the signing details on stderr.+ const details = run(execute, 'codesign', ['--display', '--verbose=2', appPath]).stderr || '';+ const identifier = /^Identifier=(.+)$/m.exec(details)?.[1]?.trim();+ const teamId = /^TeamIdentifier=(.+)$/m.exec(details)?.[1]?.trim();+ if (identifier !== COMPUTER_USE_HELPER_BUNDLE_ID || teamId !== COMPUTER_USE_HELPER_TEAM_ID) {+ throw new Error(+ `Unexpected Computer Use helper signature: identifier=${identifier}, team=${teamId}`,+ );+ }++ run(execute, 'xcrun', ['stapler', 'validate', appPath]);++ if (version) {+ const infoPlist = path.join(appPath, 'Contents', 'Info.plist');+ const bundleVersion = run(execute, 'plutil', [+ '-extract',+ 'CFBundleShortVersionString',+ 'raw',+ infoPlist,+ ]).stdout.trim();+ if (bundleVersion !== version) {+ throw new Error(`Computer Use helper is ${bundleVersion}, expected ${version}`);+ }+ }+};++/**+ * Downloads the helper zip for this build (cached by version and architecture),+ * checks its published SHA-256, and returns the local zip path.+ */+export const downloadComputerUseHelper = async ({+ arch,+ cacheDir,+ fetchImpl = fetch,+ logger = console,+ version,+}) => {+ const asset = resolveComputerUseHelperAsset({ arch, version });+ const zipPath = path.join(cacheDir, asset.name);++ const expected = (await download(fetchImpl, asset.checksumUrl)).toString('utf8').split(/\s+/)[0];+ if (!/^[\da-f]{64}$/i.test(expected)) {+ throw new Error(`Invalid checksum file for ${asset.name}`);+ }++ const cached = await fs.readFile(zipPath).catch(() => null);+ if (cached && sha256(cached) === expected.toLowerCase()) {+ logger.info(`Using cached ${asset.name}`);+ return zipPath;+ }++ logger.info(`Downloading ${asset.url}`);+ const archive = await download(fetchImpl, asset.url);+ if (sha256(archive) !== expected.toLowerCase()) {+ throw new Error(`Checksum mismatch for ${asset.name}`);+ }+ await fs.mkdir(cacheDir, { recursive: true });+ await fs.writeFile(zipPath, archive);+ return zipPath;+};++/**+ * Places the verified helper at `Contents/Library/Helpers` of the packaged app.+ * `ditto` keeps the bundle byte-for-byte, so its signature stays valid.+ */+export const embedComputerUseHelper = async ({+ appPath,+ arch,+ cacheDir,+ execute = spawnSync,+ fetchImpl = fetch,+ logger = console,+ version,+}) => {+ const zipPath = await downloadComputerUseHelper({ arch, cacheDir, fetchImpl, logger, version });++ const staging = await fs.mkdtemp(path.join(os.tmpdir(), 'lobehub-computer-use-'));+ try {+ run(execute, 'ditto', ['-x', '-k', zipPath, staging]);+ const stagedApp = path.join(staging, COMPUTER_USE_HELPER_APP_NAME);+ verifyComputerUseHelper(stagedApp, { execute, version });++ const destination = path.join(appPath, COMPUTER_USE_HELPER_BUNDLE_PATH);+ await fs.rm(destination, { force: true, recursive: true });+ await fs.mkdir(path.dirname(destination), { recursive: true });+ run(execute, 'ditto', [stagedApp, destination]);+ logger.info(`✅ Embedded ${COMPUTER_USE_HELPER_APP_NAME} ${version} (${arch})`);+ return destination;+ } finally {+ await fs.rm(staging, { force: true, recursive: true });+ }+};