π€― 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): detect system services and clarify upgrade restarts (#21869)
AmAzing-4c1a1a1cd936
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.tsindex f0501833883..2526a1e6de0 100644--- a/apps/cli/src/commands/connect.test.ts+++ b/apps/cli/src/commands/connect.test.ts@@ -14,12 +14,36 @@ import { resolveToken } from '../auth/resolveToken';import { removeStatus, spawnDaemon, stopDaemon, writeStatus } from '../daemon/manager';import type * as DeviceRegister from '../device/register';import type * as SystemInfoModule from '../device/systemInfo';+import { cliVersion } from '../pkg';+import type * as ServiceStatusModule from '../service/status';import { loadDeviceGatewayUrl, saveDeviceGatewayUrl } from '../settings';import { executeToolCall } from '../tools';import { cleanupAllProcesses } from '../tools/shell';import { log, setVerbose } from '../utils/logger';import { registerConnectCommand } from './connect';+const systemService = vi.hoisted(() => ({ enabled: false }));+vi.mock('../service/status', async (importOriginal) => ({+ ...(await importOriginal<typeof ServiceStatusModule>()),+ readConnectServices: async () => ({+ services: systemService.enabled+ ? [+ {+ active: true,+ enabled: true,+ fragmentPath: '/etc/systemd/system/lobehub-connect.service',+ mainPid: 4567,+ scope: 'system',+ serviceName: 'lobehub-connect.service',+ subState: 'running',+ user: 'ubuntu',+ },+ ]+ : [],+ unavailableScopes: [],+ }),+}));+// Native runtime probing spawns Codex; connect.nativeRuntimes.test.ts covers it.vi.mock('../device/systemInfo', async (importOriginal) => ({...(await importOriginal<typeof SystemInfoModule>()),@@ -235,7 +259,11 @@ describe('connect command', () => {await program.parseAsync(['node', 'test', 'connect', '--daemon-child']);expect(writeStatus).toHaveBeenCalledWith(- expect.objectContaining({ connectionStatus: 'connecting', deviceId: 'mock-device-id' }),+ expect.objectContaining({+ cliVersion,+ connectionStatus: 'connecting',+ deviceId: 'mock-device-id',+ }),);clientEventHandlers.connected?.();@@ -966,11 +994,31 @@ describe('connect command', () => {});describe('connect status', () => {+ it.each([['status'], ['service', 'status']])(+ 'finds a system-level connector through %j',+ async (...command) => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');+ systemService.enabled = true;+ try {+ await createProgram().parseAsync(['node', 'test', 'connect', ...command]);+ const output = vi.mocked(log.info).mock.calls.flat().join('\n');+ expect(output).toContain('system');+ expect(output).toContain('4567');+ expect(output).toContain('ubuntu');+ expect(output).toContain('sudo systemctl --no-block restart lobehub-connect.service');+ expect(output).not.toContain('No connect service is installed');+ expect(output).not.toContain('No daemon is running');+ } finally {+ systemService.enabled = false;+ }+ },+ );+it('should show no daemon running', async () => {const program = createProgram();await program.parseAsync(['node', 'test', 'connect', 'status']);- expect(log.info).toHaveBeenCalledWith(expect.stringContaining('No daemon'));+ expect(log.info).toHaveBeenCalledWith(expect.stringContaining('No managed connect'));});it('should show daemon status', async () => {@@ -992,6 +1040,24 @@ describe('connect command', () => {});describe('connect restart', () => {+ it.each([['--daemon'], ['restart']])(+ 'does not create a competing daemon through %j',+ async (...command) => {+ systemService.enabled = true;+ const exitCode = process.exitCode;+ try {+ await createProgram().parseAsync(['node', 'test', 'connect', ...command]);+ expect(spawnDaemon).not.toHaveBeenCalled();+ expect(log.error).toHaveBeenCalledWith(+ expect.stringContaining('sudo systemctl --no-block restart lobehub-connect.service'),+ );+ expect(process.exitCode).toBe(1);+ } finally {+ systemService.enabled = false;+ process.exitCode = exitCode;+ }+ },+ );it('should stop and start daemon', async () => {mockRunningPid = 12345;diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex 55b0b5744b0..83f072f0d26 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -39,7 +39,6 @@ import {getLogPath,getRunningDaemonPid,isProcessAlive,- readStatus,removePid,removeStatus,reportDaemonStartupReady,@@ -64,16 +63,17 @@ import {} from '../device/register';import { collectSystemInfo, probeNativeRuntimes } from '../device/systemInfo';import { TerminalSessionManager } from '../device/terminal';+import { cliVersion } from '../pkg';import {CONNECT_RETRYABLE_EXIT_CODE,getWorkspaceFailureExitCode,installConnectService,- readConnectServiceStatus,restartConnectService,startConnectService,stopConnectService,uninstallConnectService,} from '../service/connect';+import { getServiceRestartCommand, readConnectServices } from '../service/status';import {addWorkspaceEnrollment,loadOrCreateConnectionId,@@ -87,6 +87,7 @@ import { executeComputerUseCall, resolveComputerUseDevice } from '../tools/compuimport { cleanupAllProcesses, getActiveShellCount } from '../tools/shell';import { log, setVerbose } from '../utils/logger';import { sweepLocalTraces } from '../utils/traceMaintenance';+import { printConnectStatus } from './connectStatus';/** Longest a clean stop waits to push pending device health samples. */const SHUTDOWN_METRICS_FLUSH_MS = 3000;@@ -160,26 +161,8 @@ export function registerConnectCommand(program: Command) {connectCmd.command('status')- .description('Show background daemon status')- .action(() => {- const pid = getRunningDaemonPid();- if (pid === null) {- log.info('No daemon is running.');- return;- }-- const status = readStatus();- log.info('βββ Daemon Status βββ');- log.info(` PID : ${pid}`);- if (status) {- log.info(` Started at : ${status.startedAt}`);- log.info(` Connection : ${status.connectionStatus}`);- log.info(` Gateway : ${formatStatusGateway(status)}`);- const uptime = formatUptime(new Date(status.startedAt));- log.info(` Uptime : ${uptime}`);- }- log.info('βββββββββββββββββββββ');- });+ .description('Show connect daemon and user/system service status')+ .action(() => printConnectStatus());connectCmd.command('logs')@@ -228,7 +211,7 @@ export function registerConnectCommand(program: Command) {const serviceCmd = connectCmd.command('service')- .description('Manage the Linux user systemd connect service');+ .description('Inspect Linux connect services and manage the user-level systemd service');serviceCmd.command('install')@@ -255,7 +238,10 @@ export function registerConnectCommand(program: Command) {.action(() => {const removed = uninstallConnectService();if (removed) log.info(`Uninstalled ${CONNECT_SERVICE_NAME}.`);- else log.warn('No connect service is installed.');+ else+ log.warn(+ "No user-level connect service is installed. Run 'lh connect service status' to check for a system-level service.",+ );});serviceCmd@@ -264,7 +250,10 @@ export function registerConnectCommand(program: Command) {.action(() => {const started = startConnectService();if (started) log.info(`Started ${CONNECT_SERVICE_NAME}.`);- else log.warn('No connect service is installed.');+ else+ log.warn(+ "No user-level connect service is installed. Run 'lh connect service status' to check for a system-level service.",+ );});serviceCmd@@ -273,7 +262,10 @@ export function registerConnectCommand(program: Command) {.action(() => {const stopped = stopConnectService();if (stopped) log.info(`Stopped ${CONNECT_SERVICE_NAME}.`);- else log.warn('No connect service is installed.');+ else+ log.warn(+ "No user-level connect service is installed. Run 'lh connect service status' to check for a system-level service.",+ );});serviceCmd@@ -282,37 +274,16 @@ export function registerConnectCommand(program: Command) {.action(() => {const restarted = restartConnectService();if (restarted) log.info(`Restarted ${CONNECT_SERVICE_NAME}.`);- else log.warn('No connect service is installed.');+ else+ log.warn(+ "No user-level connect service is installed. Run 'lh connect service status' to check for a system-level service.",+ );});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 : ${formatStatusGateway(status)}`);- const uptime = formatUptime(new Date(status.startedAt));- log.info(` Uptime : ${uptime}`);- }- log.info('ββββββββββββββββββββββββββββββ');- });+ .description('Show user-level and system-level connect service status')+ .action(() => printConnectStatus({ servicesOnly: true }));// 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@@ -335,6 +306,15 @@ function handleStop() {}async function handleDaemonStart(options: ConnectOptions) {+ const { services } = await readConnectServices();+ const runningService = services.find((service) => service.active || service.mainPid);+ if (runningService) {+ log.error(+ `A ${runningService.scope}-level connect service is already running. After active tasks finish, restart it with: ${getServiceRestartCommand(runningService)}`,+ );+ process.exitCode = 1;+ return;+ }const existingPid = getRunningDaemonPid();if (existingPid !== null) {log.error(`Daemon is already running (PID ${existingPid}).`);@@ -492,6 +472,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {const updateStatus = (status: string) => {connectionStatus = status;writeStatus({+ cliVersion,connectionStatus,deviceId: client.currentDeviceId,gatewaySource: gateway.endpoint.source,@@ -1173,22 +1154,3 @@ function createDaemonLogger() {warn: (msg: string) => appendLog(`[WARN] ${msg}`),};}--function formatStatusGateway(status: { gatewaySource?: string; gatewayUrl: string }): string {- return status.gatewaySource- ? `${status.gatewayUrl} (${status.gatewaySource})`- : status.gatewayUrl;-}--function formatUptime(startedAt: Date): string {- const diff = Date.now() - startedAt.getTime();- const seconds = Math.floor(diff / 1000);- const minutes = Math.floor(seconds / 60);- const hours = Math.floor(minutes / 60);- const days = Math.floor(hours / 24);-- if (days > 0) return `${days}d ${hours % 24}h ${minutes % 60}m`;- if (hours > 0) return `${hours}h ${minutes % 60}m ${seconds % 60}s`;- if (minutes > 0) return `${minutes}m ${seconds % 60}s`;- return `${seconds}s`;-}diff --git a/apps/cli/src/commands/connectStatus.ts b/apps/cli/src/commands/connectStatus.tsnew file mode 100644index 00000000000..56d9cff8a71--- /dev/null+++ b/apps/cli/src/commands/connectStatus.ts@@ -0,0 +1,88 @@+import { readConnectRuntimes } from '../daemon/connectStatus';+import { cliVersion } from '../pkg';+import { log } from '../utils/logger';++/** Shared by status and update, including when the installed CLI is already current. */+export async function printConnectStatus(+ options: {+ installedVersion?: string;+ servicesOnly?: boolean;+ } = {},+) {+ const installedVersion = options.installedVersion ?? cliVersion;+ const { runtimes, unavailableScopes } = await readConnectRuntimes();+ const selected = runtimes.filter((runtime) => !options.servicesOnly || runtime.service);+ log.info(`Installed CLI version (this command): ${installedVersion}`);+ for (const scope of unavailableScopes) {+ log.warn(`Could not inspect ${scope} systemd services. Check 'systemctl --${scope} status'.`);+ }+ if (selected.length === 0) {+ log.info(+ unavailableScopes.length+ ? 'No managed connector found in the available managers; service status is incomplete.'+ : options.servicesOnly+ ? 'No user-level or system-level connect service found.'+ : 'No managed connect daemon or service found. Foreground connections are not included.',+ );+ return;+ }++ for (const runtime of selected) {+ const { pid, service, status } = runtime;+ log.info(+ runtime.manager === 'daemon' ? 'βββ Daemon Status βββ' : 'βββ Connect Service Status βββ',+ );+ log.info(+ ` Manager : ${runtime.manager === 'daemon' ? 'CLI daemon' : `${runtime.manager}-level systemd`}`,+ );+ if (service) {+ log.info(` Service : ${service.serviceName}`);+ log.info(` Unit : ${service.fragmentPath || 'unknown'}`);+ log.info(` User : ${service.user || 'current user'}`);+ log.info(` Enabled : ${service.enabled ? 'yes' : 'no'}`);+ log.info(` Active : ${service.active ? 'yes' : 'no'}`);+ log.info(` Sub-state : ${service.subState || 'unknown'}`);+ }+ if (pid) {+ log.info(` PID : ${pid}`);+ log.info(+ ` Running version : ${status?.cliVersion || 'unknown (not reported by this process)'}`,+ );+ }+ if (status) {+ log.info(` Started at : ${status.startedAt}`);+ log.info(` Uptime : ${formatUptime(new Date(status.startedAt))}`);+ log.info(` Connection : ${status.connectionStatus}`);+ log.info(+ ` Gateway : ${status.gatewayUrl}${status.gatewaySource ? ` (${status.gatewaySource})` : ''}`,+ );+ }+ log.info(` Restart command : ${runtime.restartCommand}`);+ if (pid && status?.cliVersion !== installedVersion) {+ log.warn(+ status?.cliVersion+ ? `Connector PID ${pid} is running ${status.cliVersion}; installed CLI is ${installedVersion}.`+ : `Connector PID ${pid} did not report its version. The installed CLI version does not confirm the running version.`,+ );+ log.warn(+ `Installing an update does not reload a running connector. After active tasks finish, run: ${runtime.restartCommand}`,+ );+ log.warn(+ 'Restarting disconnects the device and closes its remote terminals. If the version still differs, check the service uses the upgraded CLI installation.',+ );+ }+ }+}++function formatUptime(startedAt: Date): string {+ const diff = Date.now() - startedAt.getTime();+ const seconds = Math.floor(diff / 1000);+ const minutes = Math.floor(seconds / 60);+ const hours = Math.floor(minutes / 60);+ const days = Math.floor(hours / 24);++ if (days > 0) return `${days}d ${hours % 24}h ${minutes % 60}m`;+ if (hours > 0) return `${hours}h ${minutes % 60}m ${seconds % 60}s`;+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;+ return `${seconds}s`;+}diff --git a/apps/cli/src/commands/update.runtime.test.ts b/apps/cli/src/commands/update.runtime.test.tsnew file mode 100644index 00000000000..e7b04b02667--- /dev/null+++ b/apps/cli/src/commands/update.runtime.test.ts@@ -0,0 +1,135 @@+import type * as ChildProcessModule from 'node:child_process';+import { EventEmitter } from 'node:events';++import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../utils/logger';+import { registerUpdateCommand } from './update';++const state = vi.hoisted(() => ({+ latest: '0.0.71',+ pid: 4567,+ version: '0.0.65' as string | undefined,+}));+const spawn = vi.hoisted(() => vi.fn());++vi.mock('../pkg', () => ({ cliPackageName: '@lobehub/cli', cliVersion: '0.0.71' }));+vi.mock('../daemon/manager', () => ({+ getRunningDaemonPid: () => null,+ readStatus: () => ({+ cliVersion: state.version,+ connectionStatus: 'connected',+ gatewayUrl: 'wss://gateway.test',+ pid: state.pid,+ startedAt: '2026-10-26T00:00:00.000Z',+ }),+}));+vi.mock('node:child_process', async (importOriginal) => ({+ ...(await importOriginal<typeof ChildProcessModule>()),+ execFile: vi.fn((_command, args, _options, callback) =>+ callback(+ null,+ args.includes('--system')+ ? 'LoadState=loaded\nActiveState=active\nSubState=running\nMainPID=4567\nUser=ubuntu\nUnitFileState=enabled\nFragmentPath=/etc/systemd/system/lobehub-connect.service'+ : 'LoadState=not-found',+ ),+ ),+ spawn,+}));++describe('update with a running connector', () => {+ beforeEach(() => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');+ vi.spyOn(log, 'info').mockImplementation(() => {});+ vi.spyOn(log, 'warn').mockImplementation(() => {});+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({+ json: async () => ({ version: state.latest }),+ ok: true,+ }),+ );+ state.version = '0.0.65';+ state.latest = '0.0.71';+ state.pid = 4567;+ spawn.mockReset();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it('reports an old running version even when the installed CLI is already current', async () => {+ const program = new Command();+ registerUpdateCommand(program);+ await program.parseAsync(['node', 'test', 'update']);++ const output = [...vi.mocked(log.info).mock.calls, ...vi.mocked(log.warn).mock.calls]+ .flat()+ .join('\n');+ expect(output).toContain('0.0.65');+ expect(output).toContain('0.0.71');+ expect(output).toContain('sudo systemctl --no-block restart lobehub-connect.service');+ expect(output).toContain('tasks');+ expect(spawn).not.toHaveBeenCalled();+ });++ it('does not substitute the installed version for an unreported legacy runtime version', async () => {+ state.version = undefined;+ const program = new Command();+ registerUpdateCommand(program);+ await program.parseAsync(['node', 'test', 'update', '--check']);++ const output = [...vi.mocked(log.info).mock.calls, ...vi.mocked(log.warn).mock.calls]+ .flat()+ .join('\n');+ expect(output).toContain('unknown');+ expect(output).toContain('sudo systemctl --no-block restart lobehub-connect.service');+ expect(spawn).not.toHaveBeenCalled();+ });++ it('does not attribute a different process status to the service', async () => {+ state.pid = 9999;+ const program = new Command();+ registerUpdateCommand(program);+ await program.parseAsync(['node', 'test', 'update']);+ const output = vi.mocked(log.info).mock.calls.flat().join('\n');+ expect(output).toContain('unknown');+ expect(output).not.toContain('0.0.65');+ expect(output).not.toContain('connected');+ });++ it('does not ask to restart a connector already reporting the installed version', async () => {+ state.version = '0.0.71';+ const program = new Command();+ registerUpdateCommand(program);+ await program.parseAsync(['node', 'test', 'update']);+ expect(log.warn).not.toHaveBeenCalled();+ });++ it('reports installed and running versions separately after installation without restarting', async () => {+ state.latest = '0.0.72';+ spawn.mockImplementation(() => {+ const child = new EventEmitter();+ queueMicrotask(() => child.emit('close', 0));+ return child;+ });+ const program = new Command();+ registerUpdateCommand(program);+ await program.parseAsync(['node', 'test', 'update', '--package-manager', 'npm']);++ const output = [...vi.mocked(log.info).mock.calls, ...vi.mocked(log.warn).mock.calls]+ .flat()+ .join('\n');+ expect(output).toContain('Successfully installed CLI 0.0.72');+ expect(output).toContain('running 0.0.65; installed CLI is 0.0.72');+ expect(output).toContain('sudo systemctl --no-block restart lobehub-connect.service');+ expect(spawn).toHaveBeenCalledTimes(1);+ expect(spawn.mock.calls[0].slice(0, 2)).toEqual([+ 'npm',+ ['install', '-g', '@lobehub/[email protected]'],+ ]);+ });+});diff --git a/apps/cli/src/commands/update.ts b/apps/cli/src/commands/update.tsindex a4e2d2af860..2eec9899716 100644--- a/apps/cli/src/commands/update.ts+++ b/apps/cli/src/commands/update.ts@@ -11,6 +11,7 @@ import { CLI_DISPLAY_NAME } from '../constants/identity';// which would point outside the package once bundled into dist/index.js.import { cliPackageName, cliVersion } from '../pkg';import { log } from '../utils/logger';+import { printConnectStatus } from './connectStatus';export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';@@ -152,11 +153,13 @@ export function registerUpdateCommand(program: Command) {log.info(`Latest version: ${pc.bold(latest)} ${pc.dim(`(${tag})`)}`);if (!isNewerVersion(latest, current)) {- log.info(pc.green('Already on the latest version.'));+ log.info(pc.green('Installed CLI is already on the latest version.'));+ await printConnectStatus();return;}if (options.check) {+ await printConnectStatus();log.info(`Update available: ${current} β ${pc.green(latest)}. Run ${pc.cyan('lh update')} to upgrade.`,);@@ -171,11 +174,13 @@ export function registerUpdateCommand(program: Command) {try {await runInstall(command, args);- log.info(pc.green(`Successfully updated to ${latest}. Restart any running sessions.`));} catch (error) {log.error(`Update failed: ${(error as Error).message}`);log.error(`You can upgrade manually: ${[command, ...args].join(' ')}`);process.exit(1);+ return;}+ log.info(pc.green(`Successfully installed CLI ${latest}.`));+ await printConnectStatus({ installedVersion: latest });});}diff --git a/apps/cli/src/daemon/connectStatus.ts b/apps/cli/src/daemon/connectStatus.tsnew file mode 100644index 00000000000..b7a19ec94bd--- /dev/null+++ b/apps/cli/src/daemon/connectStatus.ts@@ -0,0 +1,36 @@+import { CLI_PRIMARY_BIN } from '../constants/identity';+import type { ConnectServiceStatus } from '../service/status';+import { getServiceRestartCommand, readConnectServices } from '../service/status';+import type { DaemonStatus } from './manager';+import { getRunningDaemonPid, readStatus } from './manager';++export interface ConnectRuntime {+ manager: 'daemon' | 'system' | 'user';+ pid: number | null;+ restartCommand: string;+ service?: ConnectServiceStatus;+ status?: DaemonStatus;+}++export async function readConnectRuntimes() {+ const inspection = await readConnectServices();+ const status = readStatus();+ const pid = getRunningDaemonPid();+ const runtimes: ConnectRuntime[] = inspection.services.map((service) => ({+ manager: service.scope,+ pid: service.mainPid,+ restartCommand: getServiceRestartCommand(service),+ service,+ // A status left by another process must not supply this service's version or connection state.+ status: service.mainPid && status?.pid === service.mainPid ? status : undefined,+ }));+ if (pid && !runtimes.some((runtime) => runtime.pid === pid)) {+ runtimes.unshift({+ manager: 'daemon',+ pid,+ restartCommand: `${CLI_PRIMARY_BIN} connect restart`,+ status: status?.pid === pid ? status : undefined,+ });+ }+ return { runtimes, unavailableScopes: inspection.unavailableScopes };+}diff --git a/apps/cli/src/daemon/manager.test.ts b/apps/cli/src/daemon/manager.test.tsindex d30c0750b6a..f35f58a6b2e 100644--- a/apps/cli/src/daemon/manager.test.ts+++ b/apps/cli/src/daemon/manager.test.ts@@ -155,6 +155,22 @@ describe('daemon manager', () => {expect(readStatus()).toBeNull();});+ it('preserves a service status when cleaning up an unrelated stale daemon pid', () => {+ writePid(999999);+ const serviceStatus = {+ cliVersion: '0.0.71',+ connectionStatus: 'connected',+ gatewayUrl: 'https://test.com',+ pid: process.pid,+ startedAt: new Date().toISOString(),+ };+ writeStatus(serviceStatus);++ expect(getRunningDaemonPid()).toBeNull();+ expect(readPid()).toBeNull();+ expect(readStatus()).toEqual(serviceStatus);+ });+it('should treat a live but reused (non-daemon) PID as stale and clean up', () => {// process.pid is alive, but the inspected command line is not our daemon β// simulates the OS reusing a dead daemon's PID for an unrelated process.diff --git a/apps/cli/src/daemon/manager.ts b/apps/cli/src/daemon/manager.tsindex 9368e59d719..5a44ee8c8b6 100644--- a/apps/cli/src/daemon/manager.ts+++ b/apps/cli/src/daemon/manager.ts@@ -28,6 +28,8 @@ function getLogFilePath() {}export interface DaemonStatus {+ /** Captured by the running process, never inferred from the installed package. */+ cliVersion?: string;connectionStatus: string;deviceId?: string;/** Where `gatewayUrl` came from: `server`, `manual`, `official` or `override`. */@@ -122,7 +124,8 @@ export function getRunningDaemonPid(): number | null {// Stale PID file β process is dead or the PID now belongs to someone else.removePid();- removeStatus();+ // Services share the status file; an old daemon pid must not erase their report.+ if (readStatus()?.pid === pid) removeStatus();return null;}diff --git a/apps/cli/src/doctor/checks/device.test.ts b/apps/cli/src/doctor/checks/device.test.tsindex 9ec534667e9..472e2f000e4 100644--- a/apps/cli/src/doctor/checks/device.test.ts+++ b/apps/cli/src/doctor/checks/device.test.ts@@ -2,6 +2,8 @@ import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-clientimport { beforeEach, describe, expect, it, vi } from 'vitest';import type * as ApiClientModule from '../../api/client';+import type { ConnectServiceStatus } from '../../service/status';+import type * as ServiceStatusModule from '../../service/status';import type * as SettingsModule from '../../settings';import type * as ProbesModule from '../probes';import { makeContext, runCheck } from '../testUtils';@@ -12,6 +14,7 @@ const state = vi.hoisted(() => ({daemonStatus: null as any,devices: [] as any[],localDeviceId: undefined as string | undefined,+ services: [] as ConnectServiceStatus[],}));const removePid = vi.hoisted(() => vi.fn());@@ -24,10 +27,9 @@ vi.mock('../../daemon/manager', () => ({removeStatus,}));-vi.mock('../../service/connect', () => ({- readConnectServiceStatus: () => {- throw new Error('not systemd');- },+vi.mock('../../service/status', async (importOriginal) => ({+ ...(await importOriginal<typeof ServiceStatusModule>()),+ readConnectServices: async () => ({ services: state.services, unavailableScopes: [] }),}));vi.mock('../../utils/device', () => ({ resolveLocalDeviceId: () => state.localDeviceId }));@@ -153,6 +155,7 @@ describe('device.daemon', () => {beforeEach(() => {state.daemonPid = null;state.daemonStatus = null;+ state.services = [];});it('survives a platform without the connect service', async () => {@@ -162,6 +165,34 @@ describe('device.daemon', () => {expect(outcome.detail).toContain('No connect daemon');});+ it('recognizes a connected system service without suggesting another daemon', async () => {+ state.services = [+ {+ active: true,+ enabled: true,+ fragmentPath: '/etc/systemd/system/lobehub-connect.service',+ mainPid: 42,+ scope: 'system',+ serviceName: 'lobehub-connect.service',+ subState: 'running',+ user: 'ubuntu',+ },+ ];+ state.daemonStatus = {+ cliVersion: '0.0.71',+ connectionStatus: 'connected',+ deviceId: 'dev_1',+ gatewayUrl: 'wss://gw',+ pid: 42,+ startedAt: '',+ };+ const outcome = await runCheck(deviceChecks, 'device.daemon');+ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('system');+ expect(outcome.detail).toContain('dev_1');+ expect(outcome.fix).toBeUndefined();+ });+it('flags a status file with no daemon behind it', async () => {state.daemonStatus = {connectionStatus: 'connected',diff --git a/apps/cli/src/doctor/checks/device.ts b/apps/cli/src/doctor/checks/device.tsindex 24031306a8a..fccd4cc6ad8 100644--- a/apps/cli/src/doctor/checks/device.ts+++ b/apps/cli/src/doctor/checks/device.ts@@ -1,9 +1,9 @@import { GatewayClient } from '@lobechat/device-gateway-client';import { CLI_PRIMARY_BIN } from '../../constants/identity';-import { getRunningDaemonPid, readStatus, removePid, removeStatus } from '../../daemon/manager';+import { readConnectRuntimes } from '../../daemon/connectStatus';+import { readStatus, removePid, removeStatus } from '../../daemon/manager';import { describeDeviceGateway, describeDeviceGatewayFailure } from '../../device/gatewayEndpoint';-import { readConnectServiceStatus } from '../../service/connect';import { resolveLocalDeviceId } from '../../utils/device';import { probeCredential, probeDeviceGateway, probeDevices } from '../probes';import { redactUrlCredentials, redactUrlsInMessage } from '../redact';@@ -29,12 +29,14 @@ const daemon: DoctorCheck = {removeStatus();return 'removed the stale daemon pid/status files';},- run: (): CheckOutcome => {- // Also self-heals: a pid file whose process is gone (or was recycled by the- // OS) is deleted as a side effect of asking.- const pid = getRunningDaemonPid();- const status = readStatus();- const service = readServiceStatus();+ run: async (): Promise<CheckOutcome> => {+ const { runtimes, unavailableScopes } = await readConnectRuntimes();+ const running = runtimes.filter((runtime) => runtime.pid);+ const runtime = running[0];+ const pid = runtime?.pid;+ const status = runtime ? runtime.status : readStatus();+ const service = runtimes.flatMap((item) => (item.service ? [item.service] : []));+ const label = runtime?.service ? `${runtime.manager}-level systemd service` : 'Daemon';const evidence = {connectionStatus: status?.connectionStatus,deviceId: status?.deviceId,@@ -42,9 +44,27 @@ const daemon: DoctorCheck = {gatewayUrl: redactUrlCredentials(status?.gatewayUrl),pid,service,+ unavailableScopes,};+ if (running.length > 1)+ return {+ detail: 'Multiple managed connect processes are running.',+ evidence,+ fix: `Inspect '${CLI_PRIMARY_BIN} connect status' and stop the duplicate through its manager.`,+ status: 'warn',+ };+if (!pid) {+ if (service.length || unavailableScopes.length)+ return {+ detail: service.length+ ? 'A connect service is installed, but no running process was reported.'+ : 'Connect service status could not be fully inspected.',+ evidence,+ fix: `Run '${CLI_PRIMARY_BIN} connect service status' before starting another connector.`,+ status: 'warn',+ };if (status)return {detail: 'A daemon status file is left over, but no daemon is running.',@@ -64,7 +84,7 @@ const daemon: DoctorCheck = {// A live process is not a connection: success needs the daemon's own report.if (!status?.connectionStatus)return {- detail: `Daemon ${pid} is running but has not reported a connection state.`,+ detail: `${label} ${pid} is running but has not reported a connection state.`,evidence,fix: `Check the daemon log: ${CLI_PRIMARY_BIN} connect logs`,status: 'warn',@@ -72,7 +92,7 @@ const daemon: DoctorCheck = {if (status.connectionStatus !== 'connected')return {- detail: `Daemon ${pid} is running but its last known state is "${status.connectionStatus}".`,+ detail: `${label} ${pid} is running but its last known state is "${status.connectionStatus}".`,evidence,fix: `Check the daemon log: ${CLI_PRIMARY_BIN} connect logs`,status: 'warn',@@ -82,7 +102,7 @@ const daemon: DoctorCheck = {? ` via ${evidence.gatewayUrl}${evidence.gatewaySource ? ` (${evidence.gatewaySource})` : ''}`: '';return {- detail: `Daemon ${pid} connected as device ${status.deviceId ?? 'unknown'}${via}.`,+ detail: `${label} ${pid} connected as device ${status.deviceId ?? 'unknown'}${via}.`,evidence,status: 'ok',};@@ -90,15 +110,6 @@ const daemon: DoctorCheck = {title: 'connect daemon',};-function readServiceStatus(): unknown {- try {- return readConnectServiceStatus();- } catch {- // Not installed, or not a systemd platform β neither is a finding.- return undefined;- }-}-/*** Can this machine authenticate to the device gateway at all β separating* "no address", "wrong URL", "rejected token" and "nothing answers", which alldiff --git a/apps/cli/src/service/connect.test.ts b/apps/cli/src/service/connect.test.tsindex 959106b4872..af5dd8b7ae0 100644--- a/apps/cli/src/service/connect.test.ts+++ b/apps/cli/src/service/connect.test.ts@@ -8,7 +8,6 @@ import {CONNECT_RETRYABLE_EXIT_CODE,getWorkspaceFailureExitCode,installConnectService,- readConnectServiceStatus,startConnectService,} from './connect';@@ -168,10 +167,6 @@ describe('connect service', () => {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 = [];diff --git a/apps/cli/src/service/connect.ts b/apps/cli/src/service/connect.tsindex f2bbbfc7198..8a731a58b36 100644--- a/apps/cli/src/service/connect.ts+++ b/apps/cli/src/service/connect.ts@@ -45,16 +45,6 @@ export interface ConnectServiceOptions {workspace?: string;}-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',@@ -275,31 +265,3 @@ export function restartConnectService(): boolean {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,- };-}diff --git a/apps/cli/src/service/status.test.ts b/apps/cli/src/service/status.test.tsnew file mode 100644index 00000000000..dd4b15f46af--- /dev/null+++ b/apps/cli/src/service/status.test.ts@@ -0,0 +1,87 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getServiceRestartCommand, readConnectServices } from './status';++const state = vi.hoisted(() => ({+ errorScopes: new Set<string>(),+ output: { system: 'LoadState=not-found', user: 'LoadState=not-found' },+}));+const execFile = vi.hoisted(() => vi.fn());+vi.mock('node:child_process', () => ({ execFile }));++const loaded =+ 'LoadState=loaded\nActiveState=active\nSubState=running\nUnitFileState=enabled\nMainPID=4567\nUser=ubuntu\nFragmentPath=/etc/systemd/system/lobehub-connect.service';++describe('connect service discovery', () => {+ beforeEach(() => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');+ state.errorScopes.clear();+ state.output = { system: 'LoadState=not-found', user: 'LoadState=not-found' };+ execFile.mockReset().mockImplementation((_command, args, _options, callback) => {+ const scope = args.includes('--system') ? 'system' : 'user';+ callback(+ state.errorScopes.has(scope) ? new Error('systemctl failed') : null,+ state.output[scope],+ );+ });+ });++ afterEach(() => vi.restoreAllMocks());++ it('finds a system service even when the user manager is unavailable', async () => {+ state.output = { system: loaded, user: '' };+ state.errorScopes.add('user');+ const result = await readConnectServices();++ expect(result.unavailableScopes).toEqual(['user']);+ expect(result.services).toMatchObject([+ {+ active: true,+ mainPid: 4567,+ scope: 'system',+ user: 'ubuntu',+ fragmentPath: '/etc/systemd/system/lobehub-connect.service',+ },+ ]);+ expect(getServiceRestartCommand(result.services[0])).toBe(+ 'sudo systemctl --no-block restart lobehub-connect.service',+ );+ });++ it('reports both scopes instead of hiding the system service behind an inactive user unit', async () => {+ state.output = {+ system: loaded,+ user: loaded+ .replace('ActiveState=active', 'ActiveState=inactive')+ .replace('MainPID=4567', 'MainPID=0'),+ };+ const { services } = await readConnectServices();+ expect(services).toHaveLength(2);+ expect(services[0]).toMatchObject({ active: false, mainPid: null, scope: 'user' });+ expect(getServiceRestartCommand(services[0])).toBe(+ 'systemctl --user --no-block restart lobehub-connect.service',+ );+ expect(services[1]).toMatchObject({ active: true, mainPid: 4567, scope: 'system' });+ });++ it('treats not-found as absence even when systemctl exits nonzero', async () => {+ state.errorScopes.add('system');+ expect(await readConnectServices()).toEqual({ services: [], unavailableScopes: [] });+ });++ it('does not turn an unreadable manager into a claim that no service is installed', async () => {+ state.output = { system: '', user: '' };+ state.errorScopes.add('system');+ state.errorScopes.add('user');+ expect(await readConnectServices()).toEqual({+ services: [],+ unavailableScopes: ['user', 'system'],+ });+ });++ it('does not invoke systemctl on other platforms', async () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');+ expect(await readConnectServices()).toEqual({ services: [], unavailableScopes: [] });+ expect(execFile).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/service/status.ts b/apps/cli/src/service/status.tsnew file mode 100644index 00000000000..8dc2cb6ea82--- /dev/null+++ b/apps/cli/src/service/status.ts@@ -0,0 +1,82 @@+import { execFile } from 'node:child_process';++import { CLI_CONNECT_SERVICE_NAME } from '../constants/identity';++type ServiceScope = 'system' | 'user';++export interface ConnectServiceStatus {+ active: boolean;+ enabled: boolean;+ fragmentPath: string | null;+ mainPid: number | null;+ scope: ServiceScope;+ serviceName: string;+ subState: string | null;+ user: string | null;+}++/** 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: [] };++ const scopes: ServiceScope[] = ['user', 'system'];+ const results = await Promise.allSettled(+ scopes.map(async (scope) => {+ // Query only public service metadata, never ExecStart or Environment (which may contain tokens).+ const stdout = await new Promise<string>((resolve, reject) => {+ execFile(+ 'systemctl',+ [+ `--${scope}`,+ 'show',+ CLI_CONNECT_SERVICE_NAME,+ '--property=LoadState,ActiveState,SubState,UnitFileState,MainPID,FragmentPath,User',+ ],+ { encoding: 'utf8', timeout: 3000 },+ (error, output) => {+ if (error && !output.split('\n').includes('LoadState=not-found')) reject(error);+ else resolve(output);+ },+ );+ });+ const values = Object.fromEntries(+ stdout+ .trim()+ .split('\n')+ .map((line) => {+ const separator = line.indexOf('=');+ return [line.slice(0, separator), line.slice(separator + 1)];+ }),+ );+ if (values.LoadState === 'not-found') return null;+ if (!values.LoadState) throw new Error('systemctl did not report the unit load state');++ const pid = Number(values.MainPID);+ return {+ active: values.ActiveState === 'active',+ enabled: values.UnitFileState === 'enabled',+ fragmentPath: values.FragmentPath || null,+ mainPid: Number.isSafeInteger(pid) && pid > 0 ? pid : null,+ scope,+ serviceName: CLI_CONNECT_SERVICE_NAME,+ subState: values.SubState || null,+ user: values.User || (scope === 'system' ? 'root' : null),+ } satisfies ConnectServiceStatus;+ }),+ );++ const services: ConnectServiceStatus[] = [];+ const unavailableScopes: ServiceScope[] = [];+ results.forEach((result, index) => {+ if (result.status === 'rejected') unavailableScopes.push(scopes[index]);+ else if (result.value) services.push(result.value);+ });+ return { services, unavailableScopes };+}++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+ // without waiting for systemd to stop the very terminal executing this command.+ return `${manager} --no-block restart ${service.serviceName}`;+}