π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(cli): keep workspace packages inside the embedded CLI bundle (#19391)
Arvin Xu9dfe9242ec61
diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 073307f449e..532f7b3437f 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -17,7 +17,7 @@"man"],"scripts": {- "build": "tsdown",+ "build": "bun scripts/ensureWorkspaceLinks.ts && tsdown","cli:link": "bun link","cli:unlink": "bun unlink","dev": "LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts",diff --git a/apps/cli/scripts/ensureWorkspaceLinks.test.ts b/apps/cli/scripts/ensureWorkspaceLinks.test.tsnew file mode 100644index 00000000000..98e1c17abed--- /dev/null+++ b/apps/cli/scripts/ensureWorkspaceLinks.test.ts@@ -0,0 +1,102 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { ensureWorkspaceLinks } from './ensureWorkspaceLinks';++let workspace: string | undefined;++/**+ * Lays out a repo the way pnpm sees it: `packages/<name>` next to the CLI, with+ * the CLI declaring workspace dependencies on them.+ */+const createWorkspace = (dependencies: Record<string, string>) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-workspace-links-'));+ workspace = root;++ const cliDir = path.join(root, 'apps', 'cli');+ fs.mkdirSync(path.join(cliDir, 'node_modules', '@lobechat'), { recursive: true });+ fs.writeFileSync(+ path.join(cliDir, 'package.json'),+ JSON.stringify({ devDependencies: dependencies, name: '@lobehub/cli' }),+ );++ return { cliDir, root };+};++const createPackage = (root: string, name: string) => {+ const packageDir = path.join(root, 'packages', name.replace('@lobechat/', ''));+ fs.mkdirSync(packageDir, { recursive: true });+ fs.writeFileSync(path.join(packageDir, 'package.json'), JSON.stringify({ name }));++ return packageDir;+};++afterEach(() => {+ if (workspace) fs.rmSync(workspace, { force: true, recursive: true });+ workspace = undefined;+});++describe('ensureWorkspaceLinks', () => {+ it('repoints a dangling link so the bundler can resolve the package', () => {+ const { cliDir, root } = createWorkspace({ '@lobechat/device-control': 'workspace:*' });+ const packageDir = createPackage(root, '@lobechat/device-control');++ // pnpm 12 writes this link with two extra `../` segments when apps/cli is+ // installed from a workspace root that lives elsewhere.+ const linkPath = path.join(cliDir, 'node_modules', '@lobechat', 'device-control');+ fs.symlinkSync('../../../../../../packages/device-control', linkPath, 'dir');+ expect(fs.existsSync(path.join(linkPath, 'package.json'))).toBe(false);++ const result = ensureWorkspaceLinks(cliDir);++ expect(result).toEqual({ missing: [], repaired: ['@lobechat/device-control'] });+ expect(fs.realpathSync(linkPath)).toBe(fs.realpathSync(packageDir));+ });++ it('creates a link that was never written', () => {+ const { cliDir, root } = createWorkspace({ '@lobechat/device-identity': 'workspace:*' });+ const packageDir = createPackage(root, '@lobechat/device-identity');++ const result = ensureWorkspaceLinks(cliDir);++ expect(result.repaired).toEqual(['@lobechat/device-identity']);+ expect(fs.realpathSync(path.join(cliDir, 'node_modules', '@lobechat', 'device-identity'))).toBe(+ fs.realpathSync(packageDir),+ );+ });++ it('leaves healthy links untouched and ignores registry dependencies', () => {+ const { cliDir, root } = createWorkspace({ '@lobechat/utils': 'workspace:*', 'ws': '^8.21.0' });+ const packageDir = createPackage(root, '@lobechat/utils');++ const linkPath = path.join(cliDir, 'node_modules', '@lobechat', 'utils');+ fs.symlinkSync(path.relative(path.dirname(linkPath), packageDir), linkPath, 'dir');++ expect(ensureWorkspaceLinks(cliDir)).toEqual({ missing: [], repaired: [] });+ expect(fs.lstatSync(linkPath).isSymbolicLink()).toBe(true);+ });++ it('reports a workspace dependency that has no package directory', () => {+ const { cliDir } = createWorkspace({ '@lobechat/gone': 'workspace:*' });++ expect(ensureWorkspaceLinks(cliDir)).toEqual({ missing: ['@lobechat/gone'], repaired: [] });+ });++ it('finds nested packages such as business/const', () => {+ const { cliDir, root } = createWorkspace({ '@lobechat/business-const': 'workspace:*' });+ const packageDir = path.join(root, 'packages', 'business', 'const');+ fs.mkdirSync(packageDir, { recursive: true });+ fs.writeFileSync(+ path.join(packageDir, 'package.json'),+ JSON.stringify({ name: '@lobechat/business-const' }),+ );++ expect(ensureWorkspaceLinks(cliDir).repaired).toEqual(['@lobechat/business-const']);+ expect(fs.realpathSync(path.join(cliDir, 'node_modules', '@lobechat', 'business-const'))).toBe(+ fs.realpathSync(packageDir),+ );+ });+});diff --git a/apps/cli/scripts/ensureWorkspaceLinks.ts b/apps/cli/scripts/ensureWorkspaceLinks.tsnew file mode 100644index 00000000000..810c95d71f5--- /dev/null+++ b/apps/cli/scripts/ensureWorkspaceLinks.ts@@ -0,0 +1,132 @@+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++/**+ * pnpm 12 writes `node_modules` links with too many `../` segments for+ * workspace members that live outside the install root. The desktop app+ * installs `apps/cli` as such a member (`../cli` in its workspace) and then+ * builds the CLI bundle from it, so `apps/cli/node_modules/@lobechat/*` ends up+ * dangling. Rolldown cannot resolve those imports, keeps them external, and the+ * embedded CLI dies at startup with ERR_MODULE_NOT_FOUND.+ *+ * Repointing the dangling links keeps the bundle buildable from any install+ * root until pnpm resolves the paths correctly again.+ */+const readPackageName = (dir: string): string | undefined => {+ try {+ const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));+ return typeof manifest.name === 'string' ? manifest.name : undefined;+ } catch {+ return undefined;+ }+};++/** Maps every package name under `packages/` to its directory, `business/*` included. */+const collectWorkspacePackages = (packagesDir: string): Map<string, string> => {+ const packages = new Map<string, string>();++ const visit = (dir: string, depth: number) => {+ let entries: fs.Dirent[];+ try {+ entries = fs.readdirSync(dir, { withFileTypes: true });+ } catch {+ return;+ }++ for (const entry of entries) {+ if (!entry.isDirectory() || entry.name === 'node_modules') continue;++ const packageDir = path.join(dir, entry.name);+ const name = readPackageName(packageDir);++ if (name) {+ packages.set(name, packageDir);+ } else if (depth > 0) {+ visit(packageDir, depth - 1);+ }+ }+ };++ visit(packagesDir, 1);++ return packages;+};++const workspaceDependencies = (packageJsonPath: string): string[] => {+ const manifest = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));+ const declared: Record<string, string> = {+ ...manifest.dependencies,+ ...manifest.devDependencies,+ };++ return Object.entries(declared)+ .filter(([, version]) => version.startsWith('workspace:'))+ .map(([name]) => name);+};++const linkPackage = (linkPath: string, targetDir: string) => {+ fs.rmSync(linkPath, { force: true, recursive: true });+ fs.mkdirSync(path.dirname(linkPath), { recursive: true });++ // Junctions need an absolute target; they are the only link type Windows+ // grants without developer mode.+ if (process.platform === 'win32') {+ fs.symlinkSync(targetDir, linkPath, 'junction');+ return;+ }++ fs.symlinkSync(path.relative(path.dirname(linkPath), targetDir), linkPath, 'dir');+};++export interface EnsureWorkspaceLinksResult {+ /** Declared workspace dependencies with no matching package directory. */+ missing: string[];+ /** Packages whose link was dangling or absent and has been recreated. */+ repaired: string[];+}++export const ensureWorkspaceLinks = (packageDir: string): EnsureWorkspaceLinksResult => {+ const repoRoot = path.resolve(packageDir, '../..');+ const packages = collectWorkspacePackages(path.join(repoRoot, 'packages'));++ const missing: string[] = [];+ const repaired: string[] = [];++ for (const name of workspaceDependencies(path.join(packageDir, 'package.json'))) {+ const targetDir = packages.get(name);++ if (!targetDir) {+ missing.push(name);+ continue;+ }++ const linkPath = path.join(packageDir, 'node_modules', name);++ // `existsSync` follows symlinks, so a dangling link reads as missing.+ if (fs.existsSync(linkPath)) continue;++ linkPackage(linkPath, targetDir);+ repaired.push(name);+ }++ return { missing, repaired };+};++const isEntrypoint =+ process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);++if (isEntrypoint) {+ const { missing, repaired } = ensureWorkspaceLinks(+ path.resolve(fileURLToPath(import.meta.url), '../..'),+ );++ if (repaired.length > 0) {+ console.info(`β Repaired ${repaired.length} workspace link(s): ${repaired.join(', ')}`);+ }++ if (missing.length > 0) {+ console.error(`β No workspace package found for: ${missing.join(', ')}`);+ process.exit(1);+ }+}diff --git a/apps/cli/tsdown.config.test.ts b/apps/cli/tsdown.config.test.tsindex 15bda81b077..6c974914080 100644--- a/apps/cli/tsdown.config.test.ts+++ b/apps/cli/tsdown.config.test.ts@@ -1,7 +1,18 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import config from './tsdown.config';+const resolveInputOptions = async () => {+ const { inputOptions } = config as {+ inputOptions: (options: Record<string, any>, ...rest: any[]) => Promise<any> | any;+ };++ const options: Record<string, any> = {};+ await inputOptions(options, 'esm', { cjsDts: false });++ return options;+};+describe('CLI build configuration', () => {it('bundles ws so the desktop-embedded CLI runs without node_modules', () => {expect(config).toEqual(@@ -10,4 +21,29 @@ describe('CLI build configuration', () => {}),);});++ it('fails the build instead of externalizing an unresolved import', async () => {+ const { onLog } = await resolveInputOptions();++ expect(() =>+ onLog(+ 'warn',+ {+ code: 'UNRESOLVED_IMPORT',+ message: `Could not resolve '@lobechat/device-control' in src/commands/connect.ts`,+ },+ vi.fn(),+ ),+ ).toThrow('@lobechat/device-control');+ });++ it('forwards every other log to the default handler', async () => {+ const { onLog } = await resolveInputOptions();+ const defaultHandler = vi.fn();+ const log = { code: 'INEFFECTIVE_DYNAMIC_IMPORT', message: 'dynamic import will not move' };++ onLog('warn', log, defaultHandler);++ expect(defaultHandler).toHaveBeenCalledWith('warn', log);+ });});diff --git a/apps/cli/tsdown.config.ts b/apps/cli/tsdown.config.tsindex d23a3acad7c..fde41b8b2bb 100644--- a/apps/cli/tsdown.config.ts+++ b/apps/cli/tsdown.config.ts@@ -13,6 +13,24 @@ export default defineConfig({entry: ['src/index.ts'],fixedExtension: false,format: ['esm'],+ inputOptions(options) {+ // Rolldown downgrades an unresolvable import to an external dependency and+ // still reports a successful build, so a workspace package that fails to+ // resolve (a broken `node_modules` link, a renamed package) silently ships+ // a bundle that dies at startup with ERR_MODULE_NOT_FOUND. Nothing the CLI+ // imports is expected to be external, so treat it as a build failure.+ options.onLog = (level, log, defaultHandler) => {+ if (log.code === 'UNRESOLVED_IMPORT') {+ throw new Error(+ `Unresolved import in the CLI bundle: ${log.message}. The embedded CLI has no node_modules at runtime, so every import must be bundled.`,+ );+ }++ defaultHandler(level, log);+ };++ return options;+ },minify: !!process.env.MINIFY,outputOptions: {codeSplitting: false,