🤯 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(cli): update and restart systemd connect services remotely (#22165)
AmAzing-158ceea097ae
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex 83f072f0d26..ce5d3106dca 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -521,7 +521,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {daemon:!!options.daemonChild && !options.serviceChild && process.env.LOBEHUB_CONNECT_SERVICE !== '1',restartArgs: buildDaemonArgs(options).slice(1),- shutdown: () => shutdown(),+ shutdown: (exitCode) => shutdown(exitCode),});const deviceControlDeps: DeviceControlDeps = {@@ -918,17 +918,17 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {// A clean stop pushes the health samples taken since the last upload// (bounded) before the socket closes, so the device page doesn't show the// final minutes as "not running".- const shutdown = async () => {+ const shutdown = async (exitCode = 0) => {await Promise.all([metricsSampler?.stop({ flushTimeoutMs: SHUTDOWN_METRICS_FLUSH_MS }),closeBrowserSessions(browser),]);cleanup();- process.exit(0);+ process.exit(exitCode);};- process.on('SIGINT', shutdown);- process.on('SIGTERM', shutdown);+ process.on('SIGINT', () => shutdown());+ process.on('SIGTERM', () => shutdown());// Register this device in the server registry before opening the WS, so the// row exists by the time the gateway reports it online. `lh login` alreadydiff --git a/apps/cli/src/daemon/maintenance.test.ts b/apps/cli/src/daemon/maintenance.test.tsindex c2061bf2133..55625093fe4 100644--- a/apps/cli/src/daemon/maintenance.test.ts+++ b/apps/cli/src/daemon/maintenance.test.ts@@ -6,10 +6,13 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type * as ServiceStatusModule from '../service/status';+import type { ConnectServiceStatus } from '../service/status';import { CliMaintenance } from './maintenance';-const { spawn, child } = vi.hoisted(() => {+const { spawn, child, readConnectServices } = vi.hoisted(() => {return {+ readConnectServices: vi.fn(),child: {value: undefined as unknown as EventEmitter & {connected: boolean;@@ -24,6 +27,10 @@ vi.mock('node:child_process', async (original) => ({...(await original<typeof ChildProcessModule>()),spawn,}));+vi.mock('../service/status', async (original) => ({+ ...(await original<typeof ServiceStatusModule>()),+ readConnectServices,+}));let home: string;let originalArgv: string[];@@ -42,6 +49,7 @@ beforeEach(async () => {unref: vi.fn(),});spawn.mockReturnValue(child.value);+ readConnectServices.mockResolvedValue({ services: [], unavailableScopes: [] });});afterEach(async () => {process.argv = originalArgv;@@ -49,13 +57,31 @@ afterEach(async () => {vi.clearAllMocks();await rm(home, { force: true, recursive: true });});-const create = (activeTasks = () => 0, daemon = true) =>+const create = (activeTasks = () => 0, daemon = true, shutdown = vi.fn()) =>new CliMaintenance({activeTasks,daemon,restartArgs: ['connect', '--workspace', 'workspace-a', '--public'],- shutdown: vi.fn(),+ shutdown,});+const service = (overrides: Partial<ConnectServiceStatus> = {}): ConnectServiceStatus => ({+ active: true,+ enabled: true,+ fragmentPath: '/etc/systemd/system/lobehub-connect.service',+ mainPid: process.pid,+ restart: 'on-failure',+ restartPreventExitStatus: [],+ scope: 'system',+ serviceName: 'lobehub-connect.service',+ subState: 'running',+ successExitStatus: ['0', '1', '2'],+ user: 'ubuntu',+ ...overrides,+});+const readConfig = async () =>+ JSON.parse(+ await readFile(path.join(home, '.lobehub/cli-maintenance', `${id}.config.json`), 'utf8'),+ );describe('CLI maintenance admission', () => {it('makes historical operations recoverable after a manual version change', async () => {@@ -131,3 +157,64 @@ describe('CLI maintenance admission', () => {expect(spawn).not.toHaveBeenCalled();});});++describe('CLI maintenance under systemd', () => {+ it('lets a restarting service hand the restart to systemd with a failure exit status', async () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');+ readConnectServices.mockResolvedValue({ services: [service()], unavailableScopes: [] });+ const shutdown = vi.fn().mockResolvedValue(undefined);+ const maintenance = create(undefined, false, shutdown);++ expect((await maintenance.getState()).supported).toBe(true);+ await maintenance.restart({ requestId: id, update: false });+ // The worker must not start a second connector next to the one systemd starts.+ expect((await readConfig()).restartArgs).toBeUndefined();+ child.value.emit('message', { type: 'ready-to-restart' });+ expect(shutdown).toHaveBeenCalledWith(75);+ });++ it('keeps daemon restarts on a clean exit with relaunch arguments', async () => {+ const shutdown = vi.fn().mockResolvedValue(undefined);+ const maintenance = create(undefined, true, shutdown);+ await maintenance.restart({ requestId: id, update: false });+ expect((await readConfig()).restartArgs).toEqual([+ 'connect',+ '--workspace',+ 'workspace-a',+ '--public',+ ]);+ child.value.emit('message', { type: 'ready-to-restart' });+ expect(shutdown).toHaveBeenCalledWith(0);+ expect(readConnectServices).not.toHaveBeenCalled();+ });++ it('refuses services systemd would not start again and foreground runs beside a service', async () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');+ readConnectServices.mockResolvedValue({+ services: [service({ restart: 'no' })],+ unavailableScopes: [],+ });+ expect((await create(undefined, false).getState()).supported).toBe(false);++ readConnectServices.mockResolvedValue({+ services: [service({ mainPid: process.pid + 1 })],+ unavailableScopes: [],+ });+ const foreground = create(undefined, false);+ await expect(foreground.restart({ requestId: id, update: false })).rejects.toThrow(+ 'systemd connect service',+ );+ expect(spawn).not.toHaveBeenCalled();+ });++ it('checks again after a service manager could not be read', async () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');+ readConnectServices.mockResolvedValueOnce({ services: [], unavailableScopes: ['system'] });+ readConnectServices.mockResolvedValueOnce({ services: [service()], unavailableScopes: [] });+ const maintenance = create(undefined, false);+ expect((await maintenance.getState()).supported).toBe(false);+ expect((await maintenance.getState()).supported).toBe(true);+ expect((await maintenance.getState()).supported).toBe(true);+ expect(readConnectServices).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/cli/src/daemon/maintenance.ts b/apps/cli/src/daemon/maintenance.tsindex af8f9e15d60..7f34eceee3d 100644--- a/apps/cli/src/daemon/maintenance.ts+++ b/apps/cli/src/daemon/maintenance.ts@@ -19,11 +19,19 @@ import {} from '../commands/update';import { CLI_CONFIG_DIR_NAME } from '../constants/identity';import { cliPackageName, cliVersion } from '../pkg';+import { CONNECT_RETRYABLE_EXIT_CODE } from '../service/connect';+import { readConnectServices, serviceRestartsAfterExit } from '../service/status';import { type MaintenanceConfig, writeMaintenanceState } from './maintenanceWorker';import { getLogPath } from './manager';const MAINTENANCE_MESSAGE = 'The CLI is updating or restarting. Retry after it reconnects.';+/**+ * Who starts the replacement process: the maintenance worker relaunches a CLI daemon, while a+ * systemd service exits with a failure status and lets its `Restart=` policy start the new code.+ */+type MaintenanceMode = 'daemon' | 'service';+/** One gate shared by every workspace connection owned by this process. */export class CliMaintenance {private readonly instanceId = randomUUID();@@ -34,13 +42,14 @@ export class CliMaintenance {private child?: ChildProcess;private acknowledged = false;private latestVersion?: string;+ private mode?: Promise<MaintenanceMode | undefined>;constructor(private readonly options: {activeTasks: () => number;daemon: boolean;restartArgs: string[];- shutdown: () => Promise<void>;+ shutdown: (exitCode: number) => Promise<void>;},) {}@@ -72,8 +81,26 @@ export class CliMaintenance {return worker;}+ /** The unit's MainPID and restart policy are fixed for this process, so resolve them once. */+ private resolveMode(): Promise<MaintenanceMode | undefined> {+ this.mode ??= (async () => {+ if (process.platform === 'win32') return undefined;+ if (this.options.daemon) return 'daemon';+ const { services, unavailableScopes } = await readConnectServices();+ const managed = services.some(+ (service) =>+ service.mainPid === process.pid &&+ serviceRestartsAfterExit(service, CONNECT_RETRYABLE_EXIT_CODE),+ );+ // An unreadable manager may still own this process; check again on the next request.+ if (!managed && unavailableScopes.length > 0) this.mode = undefined;+ return managed ? 'service' : undefined;+ })();+ return this.mode;+ }+getState = async (): Promise<DeviceCliUpdateState> => {- let supported = this.options.daemon && process.platform !== 'win32';+ let supported = (await this.resolveMode()) !== undefined;try {if (supported) await this.workerPath();} catch {@@ -104,7 +131,7 @@ export class CliMaintenance {supported,unsupportedReason: supported? undefined- : 'Use an installed CLI with lh connect --daemon on macOS or Linux. Foreground and system-service connections must be maintained on the device.',+ : 'Use an installed CLI with lh connect --daemon on macOS or Linux, or a systemd connect service that restarts on failure. Foreground connections must be maintained on the device.',};};@@ -145,6 +172,7 @@ export class CliMaintenance {throw new Error('This device has active tasks. Wait for them to finish before restarting.');if (update && !this.latestVersion)throw new Error('Check for updates before updating this CLI.');+ const mode = await this.resolveMode();const operation: DeviceCliUpdateOperation = {fromInstanceId: this.instanceId,id: requestId,@@ -168,7 +196,7 @@ export class CliMaintenance {operation,parentPid: process.pid,receiptPath: receipt,- restartArgs: this.options.restartArgs,+ restartArgs: mode === 'daemon' ? this.options.restartArgs : undefined,statePath: this.statePath,};await writeFile(configPath, JSON.stringify(config), { mode: 0o600 });@@ -211,7 +239,10 @@ export class CliMaintenance {const child = this.child;child.on('message', (message: { type: string }) => {if (message.type === 'ready-to-restart') {- void this.options.shutdown().catch((error) => console.error('CLI restart failed', error));+ const exitCode = mode === 'service' ? CONNECT_RETRYABLE_EXIT_CODE : 0;+ void this.options+ .shutdown(exitCode)+ .catch((error) => console.error('CLI restart failed', error));}});child.unref();diff --git a/apps/cli/src/daemon/maintenanceWorker.test.ts b/apps/cli/src/daemon/maintenanceWorker.test.tsindex 855acabb4fb..d5e5ff0c5a4 100644--- a/apps/cli/src/daemon/maintenanceWorker.test.ts+++ b/apps/cli/src/daemon/maintenanceWorker.test.ts@@ -97,4 +97,20 @@ describe('independent CLI maintenance worker', () => {if (old.exitCode === null && old.signalCode === null) old.kill('SIGTERM');}});++ it('leaves the replacement to systemd when there are no daemon relaunch arguments', async () => {+ const old = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)']);+ await once(old, 'spawn');+ config.parentPid = old.pid!;+ config.restartArgs = undefined;+ try {+ await runMaintenanceWorker(config, () => old.kill('SIGTERM'));+ await expect(readFile(path.join(directory, 'args.json'))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ expect(JSON.parse(await readFile(config.statePath, 'utf8')).stage).toBe('restarting');+ } finally {+ if (old.exitCode === null && old.signalCode === null) old.kill('SIGTERM');+ }+ });});diff --git a/apps/cli/src/daemon/maintenanceWorker.ts b/apps/cli/src/daemon/maintenanceWorker.tsindex 888b1434e63..1b26fe8f65e 100644--- a/apps/cli/src/daemon/maintenanceWorker.ts+++ b/apps/cli/src/daemon/maintenanceWorker.ts@@ -1,4 +1,5 @@import { execFile, spawn } from 'node:child_process';+import { rmSync } from 'node:fs';import { readFile, rename, rm, writeFile } from 'node:fs/promises';import { setTimeout as delay } from 'node:timers/promises';import { promisify } from 'node:util';@@ -12,7 +13,8 @@ export interface MaintenanceConfig {operation: DeviceCliUpdateOperation;parentPid: number;receiptPath: string;- restartArgs: string[];+ /** Daemon only. A systemd service is started again by its manager after the parent exits. */+ restartArgs?: string[];statePath: string;}@@ -72,6 +74,7 @@ export async function runMaintenanceWorker(config: MaintenanceConfig, ready: ()throw new Error('The previous CLI did not stop. No second daemon was started.');await delay(100);}+ if (!config.restartArgs) return;// The normal daemon launcher waits for startup preflight and writes its own PID.// Preserve argv as an array: paths and workspace flags never pass through a shell.await run(executable, [entry, ...config.restartArgs, '--daemon'], 45_000);@@ -109,6 +112,11 @@ if (process.argv[2] === '--maintenance-config') {await rm(process.argv[1], { force: true });});});+ // Stopping a service also stops the rest of its control group, including this worker.+ process.once('SIGTERM', () => {+ rmSync(process.argv[1], { force: true });+ process.exit(143);+ });// A parent disappearing before it acknowledges the request must not leave an idle helper.process.once('disconnect', () => {clearTimeout(timeout);diff --git a/apps/cli/src/service/status.test.ts b/apps/cli/src/service/status.test.tsindex dd4b15f46af..ee1fbab7a8c 100644--- a/apps/cli/src/service/status.test.ts+++ b/apps/cli/src/service/status.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { getServiceRestartCommand, readConnectServices } from './status';+import { getServiceRestartCommand, readConnectServices, serviceRestartsAfterExit } from './status';const state = vi.hoisted(() => ({errorScopes: new Set<string>(),@@ -79,6 +79,30 @@ describe('connect service discovery', () => {});});+ it('reads whether systemd restarts the unit after a failure exit', async () => {+ state.output = {+ system: `${loaded}\nRestart=on-failure\nRestartPreventExitStatus=\nSuccessExitStatus=0 1 2`,+ user: 'LoadState=not-found',+ };+ const [service] = (await readConnectServices()).services;+ expect(service).toMatchObject({+ restart: 'on-failure',+ restartPreventExitStatus: [],+ successExitStatus: ['0', '1', '2'],+ });+ expect(serviceRestartsAfterExit(service, 75)).toBe(true);+ expect(serviceRestartsAfterExit({ ...service, restart: 'always' }, 75)).toBe(true);+ expect(serviceRestartsAfterExit({ ...service, restart: 'no' }, 75)).toBe(false);+ expect(serviceRestartsAfterExit({ ...service, restart: 'on-abnormal' }, 75)).toBe(false);+ expect(serviceRestartsAfterExit({ ...service, successExitStatus: ['75'] }, 75)).toBe(false);+ expect(+ serviceRestartsAfterExit(+ { ...service, restart: 'always', restartPreventExitStatus: ['75'] },+ 75,+ ),+ ).toBe(false);+ });+it('does not invoke systemctl on other platforms', async () => {vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');expect(await readConnectServices()).toEqual({ services: [], unavailableScopes: [] });diff --git a/apps/cli/src/service/status.ts b/apps/cli/src/service/status.tsindex 8dc2cb6ea82..132ef9a08d5 100644--- a/apps/cli/src/service/status.ts+++ b/apps/cli/src/service/status.ts@@ -9,12 +9,18 @@ export interface ConnectServiceStatus {enabled: boolean;fragmentPath: string | null;mainPid: number | null;+ /** systemd `Restart=` policy, plus the exit statuses that override it. */+ restart: string | null;+ restartPreventExitStatus: string[];scope: ServiceScope;serviceName: string;subState: string | null;+ successExitStatus: string[];user: string | null;}+const splitStatuses = (value: string | undefined) => value?.split(/\s+/).filter(Boolean) ?? [];+/** Read both managers independently: an unavailable user bus does not hide a system service. */export async function readConnectServices() {if (process.platform !== 'linux') return { services: [], unavailableScopes: [] };@@ -30,7 +36,7 @@ export async function readConnectServices() {`--${scope}`,'show',CLI_CONNECT_SERVICE_NAME,- '--property=LoadState,ActiveState,SubState,UnitFileState,MainPID,FragmentPath,User',+ '--property=LoadState,ActiveState,SubState,UnitFileState,MainPID,FragmentPath,User,Restart,RestartPreventExitStatus,SuccessExitStatus',],{ encoding: 'utf8', timeout: 3000 },(error, output) => {@@ -57,9 +63,12 @@ export async function readConnectServices() {enabled: values.UnitFileState === 'enabled',fragmentPath: values.FragmentPath || null,mainPid: Number.isSafeInteger(pid) && pid > 0 ? pid : null,+ restart: values.Restart || null,+ restartPreventExitStatus: splitStatuses(values.RestartPreventExitStatus),scope,serviceName: CLI_CONNECT_SERVICE_NAME,subState: values.SubState || null,+ successExitStatus: splitStatuses(values.SuccessExitStatus),user: values.User || (scope === 'system' ? 'root' : null),} satisfies ConnectServiceStatus;}),@@ -74,6 +83,14 @@ export async function readConnectServices() {return { services, unavailableScopes };}+/** Whether systemd starts the unit again after its main process exits with `code`. */+export function serviceRestartsAfterExit(service: ConnectServiceStatus, code: number): boolean {+ const status = String(code);+ if (service.restartPreventExitStatus.includes(status)) return false;+ if (service.restart === 'always') return true;+ return service.restart === 'on-failure' && !service.successExitStatus.includes(status);+}+export function getServiceRestartCommand(service: ConnectServiceStatus): string {const manager = service.scope === 'system' ? 'sudo systemctl' : 'systemctl --user';// A terminal opened through the connector belongs to the service too. Queue the restart