π€― 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
β»οΈrefactor(cli): add connect system service management (#16629)
Rylan Cai28548b7b775e
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex b04bcd8078d..ef9b527fc3e 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -41,16 +41,27 @@ import {resolveDeviceIdentity,resolveWorkspaceDeviceIdentity,} from '../device/register';+import {+ installConnectService,+ readConnectServiceStatus,+ restartConnectService,+ startConnectService,+ stopConnectService,+ uninstallConnectService,+} from '../service/connect';import { loadOrCreateConnectionId, loadSettings, normalizeUrl, saveSettings } from '../settings';import { executeToolCall } from '../tools';import { cleanupAllProcesses } from '../tools/shell';import { log, setVerbose } from '../utils/logger';+const CONNECT_SERVICE_NAME = 'lobehub-connect.service';+interface ConnectOptions {daemon?: boolean;daemonChild?: boolean;deviceId?: string;gateway?: string;+ serviceChild?: boolean;token?: string;verbose?: boolean;/** Enroll this machine as a device of the given workspace (admin only). */@@ -68,6 +79,7 @@ export function registerConnectCommand(program: Command) {.option('-v, --verbose', 'Enable verbose logging').option('-d, --daemon', 'Run as a background daemon process').option('--daemon-child', 'Internal: runs as the daemon child process')+ .option('--service-child', 'Internal: runs as the system service child process').action(async (options: ConnectOptions) => {if (options.verbose) setVerbose(true);@@ -76,8 +88,9 @@ export function registerConnectCommand(program: Command) {return handleDaemonStart(options);}- // --daemon-child: running inside daemon, redirect logging- const isDaemonChild = options.daemonChild || process.env.LOBEHUB_DAEMON === '1';+ const isServiceChild = options.serviceChild || process.env.LOBEHUB_CONNECT_SERVICE === '1';+ const isDaemonChild =+ options.daemonChild || isServiceChild || process.env.LOBEHUB_DAEMON === '1';await runConnect(options, isDaemonChild);});@@ -148,6 +161,75 @@ export function registerConnectCommand(program: Command) {handleDaemonStart({ ...options, daemon: true });});+ const serviceCmd = connectCmd+ .command('service')+ .description('Manage the Linux user systemd connect service');++ serviceCmd+ .command('install')+ .description('Install and start the Linux user systemd connect service')+ .action(() => {+ installConnectService();+ log.info(`Installed and started ${CONNECT_SERVICE_NAME}.`);+ log.info("Run 'lh connect service status' to inspect the service.");+ });++ serviceCmd+ .command('uninstall')+ .description('Remove the Linux user systemd connect service')+ .action(() => {+ const removed = uninstallConnectService();+ if (removed) log.info(`Uninstalled ${CONNECT_SERVICE_NAME}.`);+ else log.warn('No connect service is installed.');+ });++ serviceCmd.command('start').description('Start the installed connect service').action(() => {+ const started = startConnectService();+ if (started) log.info(`Started ${CONNECT_SERVICE_NAME}.`);+ else log.warn('No connect service is installed.');+ });++ serviceCmd.command('stop').description('Stop the installed connect service').action(() => {+ const stopped = stopConnectService();+ if (stopped) log.info(`Stopped ${CONNECT_SERVICE_NAME}.`);+ else log.warn('No connect service is installed.');+ });++ serviceCmd.command('restart').description('Restart the installed connect service').action(() => {+ const restarted = restartConnectService();+ if (restarted) log.info(`Restarted ${CONNECT_SERVICE_NAME}.`);+ else log.warn('No connect service is installed.');+ });++ serviceCmd+ .command('status')+ .description('Show the installed connect service status')+ .action(() => {+ const serviceStatus = readConnectServiceStatus();+ if (!serviceStatus) {+ log.info('No connect service is installed.');+ return;+ }++ const status = readStatus();+ log.info('βββ Connect Service Status βββ');+ log.info(` Service : ${serviceStatus.serviceName}`);+ log.info(` Installed : yes`);+ log.info(` Enabled : ${serviceStatus.enabled ? 'yes' : 'no'}`);+ log.info(` Active : ${serviceStatus.active ? 'yes' : 'no'}`);+ log.info(` Sub-state : ${serviceStatus.subState || 'unknown'}`);+ if (serviceStatus.mainPid !== null) {+ log.info(` PID : ${serviceStatus.mainPid}`);+ }+ if (status) {+ log.info(` Connection : ${status.connectionStatus}`);+ log.info(` Gateway : ${status.gatewayUrl}`);+ const uptime = formatUptime(new Date(status.startedAt));+ log.info(` Uptime : ${uptime}`);+ }+ log.info('ββββββββββββββββββββββββββββββ');+ });+// Top-level alias for `connect stop`. Users who run `lh connect` naturally// reach for `lh disconnect` to undo it; the nested `connect stop` is not// discoverable enough on its own.diff --git a/apps/cli/src/service/connect.test.ts b/apps/cli/src/service/connect.test.tsnew file mode 100644index 00000000000..2190c741910--- /dev/null+++ b/apps/cli/src/service/connect.test.ts@@ -0,0 +1,161 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const tmpDir = path.join(os.tmpdir(), `lobehub-connect-service-test-${process.pid}`);+const unitDir = path.join(tmpDir, 'systemd-user');+const entryPath = path.join(tmpDir, 'lh.js');++const execFileSyncMock = vi.hoisted(() => vi.fn());+const getRunningDaemonPidMock = vi.hoisted(() => vi.fn());+const loadCredentialsMock = vi.hoisted(() => vi.fn());++vi.mock('node:child_process', async (importOriginal) => {+ const actual = await importOriginal<Record<string, any>>();+ return { ...actual, execFileSync: execFileSyncMock };+});++vi.mock('node:os', async (importOriginal) => {+ const actual = await importOriginal<Record<string, any>>();+ return {+ ...actual,+ default: {+ ...actual.default,+ homedir: () => tmpDir,+ },+ };+});++vi.mock('../auth/credentials', () => ({+ loadCredentials: loadCredentialsMock,+}));++vi.mock('../daemon/manager', () => ({+ getRunningDaemonPid: getRunningDaemonPidMock,+}));++// eslint-disable-next-line import-x/first+import { installConnectService, readConnectServiceStatus, startConnectService } from './connect';++describe('connect service', () => {+ const originalArgv1 = process.argv[1];+ const originalEnv = { ...process.env };+ let systemctlCalls: string[][];++ beforeEach(() => {+ systemctlCalls = [];+ fs.rmSync(tmpDir, { force: true, recursive: true });+ fs.mkdirSync(tmpDir, { recursive: true });+ fs.writeFileSync(entryPath, '');++ process.argv[1] = entryPath;+ process.env = {+ ...originalEnv,+ HOME: tmpDir,+ LOBEHUB_CONNECT_SERVICE_UNIT_DIR: unitDir,+ };+ delete process.env.LOBEHUB_CLI_HOME;+ delete process.env.LOBEHUB_CLI_API_KEY;+ delete process.env.LOBEHUB_JWT;++ getRunningDaemonPidMock.mockReturnValue(null);+ loadCredentialsMock.mockReturnValue({ accessToken: 'jwt' });+ execFileSyncMock.mockImplementation((command: string, args: string[]) => {+ if (command !== 'systemctl') throw new Error(`unexpected command: ${command}`);++ systemctlCalls.push(args);+ if (args[0] === '--version') return 'systemd 255';+ if (args[0] !== '--user') return '';++ const systemctlArgs = args.slice(1);+ if (systemctlArgs[0] === 'show-environment') return '';+ if (systemctlArgs[0] === 'show') {+ const propertyArg = systemctlArgs.find((arg) => arg.startsWith('--property='));+ const property = propertyArg?.replace('--property=', '');+ if (property === 'ActiveState') return 'active';+ if (property === 'UnitFileState') return 'enabled';+ if (property === 'SubState') return 'running';+ if (property === 'MainPID') return '1234';+ }++ return '';+ });+ });++ afterEach(() => {+ process.argv[1] = originalArgv1;+ process.env = { ...originalEnv };+ fs.rmSync(tmpDir, { force: true, recursive: true });+ vi.clearAllMocks();+ });++ it('installs and starts the user systemd service', () => {+ installConnectService();++ const unitPath = path.join(unitDir, 'lobehub-connect.service');+ expect(fs.existsSync(unitPath)).toBe(true);+ expect(fs.readFileSync(unitPath, 'utf8')).toContain(+ `"${process.execPath}" "${entryPath}" "connect" "--service-child"`,+ );+ expect(systemctlCalls).toContainEqual(['--user', 'daemon-reload']);+ expect(systemctlCalls).toContainEqual(['--user', 'enable', '--now', 'lobehub-connect.service']);+ });++ it('does not install when a managed connect daemon is already running', () => {+ getRunningDaemonPidMock.mockReturnValue(12345);++ expect(() => installConnectService()).toThrow(+ 'Background connect daemon is already running (PID 12345).',+ );+ expect(fs.existsSync(path.join(unitDir, 'lobehub-connect.service'))).toBe(false);+ expect(systemctlCalls).not.toContainEqual([+ '--user',+ 'enable',+ '--now',+ 'lobehub-connect.service',+ ]);+ });++ it('does not install when no auth is available', () => {+ loadCredentialsMock.mockReturnValue(null);++ expect(() => installConnectService()).toThrow("No authentication found. Run 'lh login' first");+ expect(fs.existsSync(path.join(unitDir, 'lobehub-connect.service'))).toBe(false);+ expect(systemctlCalls).not.toContainEqual([+ '--user',+ 'enable',+ '--now',+ 'lobehub-connect.service',+ ]);+ });++ it('imports the current environment by name and clears stale service env', () => {+ process.env.LOBEHUB_CLI_API_KEY = 'test-key';+ delete process.env.LOBEHUB_CLI_HOME;++ installConnectService();++ expect(systemctlCalls).toContainEqual(+ expect.arrayContaining(['--user', 'unset-environment', 'LOBEHUB_CLI_HOME']),+ );+ expect(systemctlCalls).toContainEqual(+ expect.arrayContaining(['--user', 'import-environment', 'LOBEHUB_CLI_API_KEY']),+ );+ expect(systemctlCalls).not.toContainEqual(['--user', 'import-environment']);+ });++ it('returns null status when the unit file is not installed', () => {+ expect(readConnectServiceStatus()).toBeNull();+ });++ it('starts an installed service after preflight checks pass', () => {+ installConnectService();+ systemctlCalls = [];++ expect(startConnectService()).toBe(true);++ expect(systemctlCalls).toContainEqual(['--user', 'start', 'lobehub-connect.service']);+ });+});diff --git a/apps/cli/src/service/connect.ts b/apps/cli/src/service/connect.tsnew file mode 100644index 00000000000..8bd03e3bb69--- /dev/null+++ b/apps/cli/src/service/connect.ts@@ -0,0 +1,245 @@+import { execFileSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { loadCredentials } from '../auth/credentials';+import { CLI_API_KEY_ENV } from '../constants/auth';+import { getRunningDaemonPid } from '../daemon/manager';++const SERVICE_NAME = 'lobehub-connect.service';+const ENV_NAME_PATTERN = /^[A-Z_]\w*$/i;+const SERVICE_ENV_NAMES = [+ 'AGENT_GATEWAY_URL',+ 'DEBUG',+ 'LH_GATEWAY_URL',+ 'LOBEHUB_CLI_CHANNEL',+ 'LOBEHUB_CLI_HOME',+ CLI_API_KEY_ENV,+ 'LOBEHUB_JWT',+ 'LOBEHUB_SERVER',+];++export interface ConnectServiceStatus {+ active: boolean;+ enabled: boolean;+ installed: boolean;+ mainPid: number | null;+ serviceName: string;+ subState: string | null;+ unitFileState: string | null;+}++function systemctl(args: string[], stdio: 'pipe' | 'inherit' = 'pipe'): string {+ const output = execFileSync('systemctl', ['--user', ...args], {+ encoding: 'utf8',+ stdio: ['ignore', stdio, stdio === 'pipe' ? 'pipe' : 'inherit'],+ });++ return typeof output === 'string' ? output.trim() : '';+}++function getUserServiceDir(): string {+ return (+ process.env.LOBEHUB_CONNECT_SERVICE_UNIT_DIR ||+ path.join(os.homedir(), '.config', 'systemd', 'user')+ );+}++function getExecErrorMessage(error: unknown): string {+ const stderr =+ error && typeof error === 'object' && 'stderr' in error+ ? String((error as { stderr?: Buffer | string }).stderr || '').trim()+ : '';+ if (stderr) return stderr;+ return error instanceof Error ? error.message : String(error);+}++function renderUnit(): string {+ const quoteSystemdValue = (value: string): string =>+ `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;+ const escapeSystemdEnvValue = (value: string): string =>+ value.replaceAll('\\', '\\\\').replaceAll('"', '\\"');+ const homeDir = os.homedir();+ const cliHomeDir = path.join(homeDir, process.env.LOBEHUB_CLI_HOME || '.lobehub');+ const logPath = path.join(cliHomeDir, 'daemon.log');+ const scriptPath = fs.realpathSync(process.argv[1]!);+ const execStart = [process.execPath, scriptPath, 'connect', '--service-child']+ .map(quoteSystemdValue)+ .join(' ');++ return [+ '[Unit]',+ 'Description=LobeHub CLI connect service',+ 'After=network-online.target',+ 'Wants=network-online.target',+ 'StartLimitIntervalSec=60',+ 'StartLimitBurst=10',+ '',+ '[Service]',+ 'Type=simple',+ `WorkingDirectory=${homeDir}`,+ `Environment=HOME=${escapeSystemdEnvValue(homeDir)}`,+ 'Environment=LOBEHUB_CONNECT_SERVICE=1',+ `ExecStart=${execStart}`,+ `StandardOutput=append:${logPath}`,+ `StandardError=append:${logPath}`,+ 'Restart=on-failure',+ 'SuccessExitStatus=0 1 2',+ 'RestartSec=1',+ 'TimeoutStopSec=20',+ '',+ '[Install]',+ 'WantedBy=default.target',+ '',+ ].join('\n');+}++function requireLinuxSystemd() {+ if (process.platform !== 'linux') {+ throw new Error('Connect service install is currently Linux-only.');+ }+ try {+ execFileSync('systemctl', ['--version'], { stdio: ['ignore', 'pipe', 'pipe'] });+ } catch (error) {+ throw new Error(`systemctl is not available on this system: ${getExecErrorMessage(error)}`, {+ cause: error,+ });+ }+ try {+ systemctl(['show-environment']);+ } catch (error) {+ throw new Error(+ [+ 'Linux user systemd is not available.',+ 'Make sure `systemctl --user ...` works for this user.',+ 'On Debian/Ubuntu minimal systems, install `libpam-systemd` and `dbus-user-session`, then start a user session or enable linger.',+ getExecErrorMessage(error),+ ].join(' '),+ { cause: error },+ );+ }+}++function importServiceEnvironment(): void {+ const staleServiceEnvNames = SERVICE_ENV_NAMES.filter((name) => process.env[name] === undefined);+ if (staleServiceEnvNames.length > 0) {+ systemctl(['unset-environment', ...staleServiceEnvNames], 'inherit');+ }++ const environmentNames = Object.keys(process.env).filter((name) => ENV_NAME_PATTERN.test(name));+ if (environmentNames.length > 0) {+ systemctl(['import-environment', ...environmentNames], 'inherit');+ }+}++function assertNoConnectDaemonRunning(): void {+ const daemonPid = getRunningDaemonPid();+ if (daemonPid === null) return;++ throw new Error(+ [+ `Background connect daemon is already running (PID ${daemonPid}).`,+ 'Stop it before starting the systemd service.',+ 'Run `lh connect stop`, then retry this command.',+ ].join(' '),+ );+}++function assertConnectServiceAuthAvailable(): void {+ if (process.env.LOBEHUB_JWT || process.env[CLI_API_KEY_ENV] || loadCredentials()) return;++ throw new Error(+ `No authentication found. Run 'lh login' first, or set ${CLI_API_KEY_ENV} before starting the connect service.`,+ );+}++export function installConnectService(): void {+ requireLinuxSystemd();+ assertNoConnectDaemonRunning();+ assertConnectServiceAuthAvailable();++ fs.mkdirSync(path.join(os.homedir(), process.env.LOBEHUB_CLI_HOME || '.lobehub'), {+ mode: 0o700,+ recursive: true,+ });+ fs.mkdirSync(getUserServiceDir(), { mode: 0o700, recursive: true });+ fs.writeFileSync(path.join(getUserServiceDir(), SERVICE_NAME), renderUnit(), { mode: 0o644 });++ importServiceEnvironment();+ systemctl(['daemon-reload'], 'inherit');+ systemctl(['enable', '--now', SERVICE_NAME], 'inherit');+}++export function uninstallConnectService(): boolean {+ const unitPath = path.join(getUserServiceDir(), SERVICE_NAME);+ if (!fs.existsSync(unitPath)) return false;++ requireLinuxSystemd();++ try {+ systemctl(['disable', '--now', SERVICE_NAME], 'inherit');+ } catch {+ // Best effort: remove the unit file even when the service is already stopped.+ }++ fs.unlinkSync(unitPath);+ systemctl(['daemon-reload'], 'inherit');++ return true;+}++export function startConnectService(): boolean {+ if (!fs.existsSync(path.join(getUserServiceDir(), SERVICE_NAME))) return false;+ requireLinuxSystemd();+ assertNoConnectDaemonRunning();+ assertConnectServiceAuthAvailable();+ importServiceEnvironment();+ systemctl(['start', SERVICE_NAME], 'inherit');+ return true;+}++export function stopConnectService(): boolean {+ if (!fs.existsSync(path.join(getUserServiceDir(), SERVICE_NAME))) return false;+ requireLinuxSystemd();+ systemctl(['stop', SERVICE_NAME], 'inherit');+ return true;+}++export function restartConnectService(): boolean {+ if (!fs.existsSync(path.join(getUserServiceDir(), SERVICE_NAME))) return false;+ requireLinuxSystemd();+ assertNoConnectDaemonRunning();+ assertConnectServiceAuthAvailable();+ importServiceEnvironment();+ systemctl(['restart', SERVICE_NAME], 'inherit');+ return true;+}++export function readConnectServiceStatus(): ConnectServiceStatus | null {+ if (!fs.existsSync(path.join(getUserServiceDir(), SERVICE_NAME))) return null;++ requireLinuxSystemd();++ const getShowValue = (property: string): string | null => {+ try {+ return systemctl(['show', SERVICE_NAME, `--property=${property}`, '--value']);+ } catch {+ return null;+ }+ };+ const activeState = getShowValue('ActiveState');+ const unitFileState = getShowValue('UnitFileState');+ const subState = getShowValue('SubState');+ const mainPidRaw = getShowValue('MainPID');++ return {+ active: activeState === 'active',+ enabled: unitFileState === 'enabled',+ installed: true,+ mainPid: mainPidRaw && mainPidRaw !== '0' ? Number.parseInt(mainPidRaw, 10) : null,+ serviceName: SERVICE_NAME,+ subState,+ unitFileState,+ };+}