Skip to content

🀯 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.

✨ feat(cli): clarify updates and unify connector restarts (#22185)

AmAzing-91fd120468b5
diff --git a/apps/cli/README.md b/apps/cli/README.md
index 927f82d4104..8ce806245a8 100644
--- a/apps/cli/README.md
+++ b/apps/cli/README.md
@@ -2,6 +2,54 @@
LobeHub command-line interface.
+## Update a connected device
+
+```bash
+lh update # Install the latest CLI without restarting a connector
+lh connect status # Connection, running version, and any required action
+lh connect status --verbose # Service metadata and CLI installation paths
+
+# Wait for active tasks to finish, then restart the detected connector:
+lh connect restart
+lh connect status # Verify the new running version and connection
+```
+
+Installing an update and activating it are separate steps. `lh update` keeps the
+running connector in place; it reports the installed and running versions separately.
+Restarting disconnects the device and closes its remote terminals. A terminal
+provided by LobeHub may close or print `Terminated` before the restart request
+returns. Reconnect before checking status; β€œRestart requested” is not confirmation
+that the device is already connected.
+
+`lh connect restart` detects a CLI daemon or a user/system systemd service. System
+services use `sudo` unless already running as root. When multiple connectors are
+running, select one with `--manager daemon`, `--manager user`, or `--manager system`.
+Service restarts preserve the unit's configuration; daemon connection flags such
+as `--token` cannot override it. `lh connect service restart` remains a user-service
+alias. With no managed connector and no inspection failures, `lh connect restart`
+retains its existing behavior of starting a daemon. Daemon restarts wait for the
+previous process to exit before starting its replacement, including when upgrading
+from an older CLI. If shutdown times out, no replacement is started.
+
+A daemon cannot be restarted from a terminal or shell it owns: its shutdown would
+kill the waiting restart command. This is rejected before stopping the connection;
+run `lh connect restart` from a local terminal or an independent SSH session instead.
+If process ancestry cannot be verified, the restart is also rejected without
+stopping the connector. Systemd service restarts still use the service manager.
+
+If an older restart lost `daemon.pid`, `lh connect status` can recover it from the
+status record only after verifying that the process is alive and is a daemon, not
+a foreground connection or systemd service. This recovery does not restart the
+connection. Cleanup checks PID ownership; normal restarts also wait for the old
+process to exit before creating new records.
+
+If the version still differs after a restart, the status report shows the command's
+CLI entry path and the connector's entry path when available. Different paths mean
+you should update the connector's installation or change its service configuration.
+Diagnostics never dump the service's command line or environment. Older connectors
+on Linux use a conservative `/proc` lookup; an inaccessible or unsupported entry
+is reported as unknown instead of guessed.
+
## Publish local artifacts
```bash
diff --git a/apps/cli/src/commands/connect.integration.test.ts b/apps/cli/src/commands/connect.integration.test.ts
index 1357cdb5f79..d1b237e40da 100644
--- a/apps/cli/src/commands/connect.integration.test.ts
+++ b/apps/cli/src/commands/connect.integration.test.ts
@@ -1,12 +1,13 @@
import { execFile } from 'node:child_process';
-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, describe, expect, it } from 'vitest';
-import { WebSocketServer } from 'ws';
+import type { ToolCallResponseMessage } from '@lobechat/device-gateway-client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { type WebSocket, WebSocketServer } from 'ws';
interface CliResult {
exitCode: number;
@@ -256,11 +257,136 @@ describe('connect daemon startup', () => {
expect(handshakes[0]?.path).toMatch(/^\/edge\/gw\/ws\?/);
expect(handshakes[0]?.auth).toMatchObject({ serverUrl, token, type: 'auth' });
- const status = await runCli(['connect', 'status'], home);
+ const status = await runCli(['connect', 'status', '--verbose'], home);
expect(status.stdout).toContain(`http://127.0.0.1:${gatewayPort}/edge/gw (server)`);
sockets.close();
}, 20_000);
+ it.skipIf(process.platform === 'win32')(
+ 'waits for slow shutdown and recovers a missing PID without another daemon',
+ async () => {
+ const home = await mkdtemp(path.join(os.tmpdir(), 'lobehub-cli-restart-'));
+ tempHomes.push(home);
+ daemonHomes.push(home);
+ const browser = path.join(home, 'slow-agent-browser');
+ await writeFile(browser, '#!/bin/sh\nsleep 3\n');
+ await chmod(browser, 0o755);
+ let connections = 0;
+ const server = createServer((_request, response) => {
+ response.setHeader('Content-Type', 'application/json');
+ response.end(JSON.stringify({ result: { data: { json: null } } }));
+ });
+ const sockets = new WebSocketServer({ server });
+ sockets.on('connection', (socket) => {
+ socket.on('message', (raw) => {
+ const message = JSON.parse(String(raw));
+ if (message.type === 'auth') {
+ connections++;
+ socket.send(JSON.stringify({ type: 'auth_success' }));
+ } else if (message.type === 'heartbeat') {
+ socket.send(JSON.stringify({ type: 'heartbeat_ack' }));
+ } else if (message.type === 'device_metrics') {
+ socket.send(JSON.stringify({ batchId: message.batchId, type: 'device_metrics_ack' }));
+ }
+ });
+ });
+ const port = await listen(server);
+ const env = {
+ LOBEHUB_JWT: unsignedJwt('fixture-user'),
+ LOBEHUB_SERVER: `http://127.0.0.1:${port}`,
+ };
+ const options = ['--gateway', env.LOBEHUB_SERVER, '--agent-browser', browser];
+ const first = await runCli(['connect', '--daemon', ...options], home, env);
+ expect(first.exitCode).toBe(0);
+ const pidPath = path.join(home, '.lobehub', 'daemon.pid');
+ const oldPid = Number(await readFile(pidPath, 'utf8'));
+
+ const restarted = await runCli(['connect', 'restart', ...options], home, env);
+ expect(restarted.exitCode).toBe(0);
+ expect(() => process.kill(oldPid, 0)).toThrow();
+ const newPid = Number(await readFile(pidPath, 'utf8'));
+ expect(newPid).not.toBe(oldPid);
+ await vi.waitFor(() => expect(connections).toBe(2));
+ // Reproduce the missing file left by a legacy restart, not a process failure.
+ await rm(pidPath);
+ const status = await runCli(['connect', 'status', '--verbose'], home);
+ expect(status.stdout).toContain(`PID : ${newPid}`);
+ expect(status.stdout).toContain('Connection : connected');
+ expect(Number(await readFile(pidPath, 'utf8'))).toBe(newPid);
+ expect(connections).toBe(2);
+ sockets.close();
+ },
+ 30_000,
+ );
+
+ it.skipIf(process.platform === 'win32')(
+ 'rejects a restart inside its own shell without losing the daemon',
+ async () => {
+ const home = await mkdtemp(path.join(os.tmpdir(), 'lobehub-cli-self-restart-'));
+ tempHomes.push(home);
+ daemonHomes.push(home);
+ const server = createServer((_request, response) => {
+ response.setHeader('Content-Type', 'application/json');
+ response.end(JSON.stringify({ result: { data: { json: null } } }));
+ });
+ const sockets = new WebSocketServer({ server });
+ let connection: WebSocket | undefined;
+ const replies = new Map<string, ToolCallResponseMessage['result']>();
+ sockets.on('connection', (socket) => {
+ connection = socket;
+ socket.on('message', (raw) => {
+ const message = JSON.parse(String(raw));
+ if (message.type === 'auth') socket.send(JSON.stringify({ type: 'auth_success' }));
+ if (message.type === 'heartbeat') socket.send(JSON.stringify({ type: 'heartbeat_ack' }));
+ if (message.type === 'device_metrics') {
+ socket.send(JSON.stringify({ batchId: message.batchId, type: 'device_metrics_ack' }));
+ }
+ if (message.type === 'tool_call_response') replies.set(message.requestId, message.result);
+ });
+ });
+ const port = await listen(server);
+ const started = await runCli(
+ ['connect', '--daemon', '--gateway', `http://127.0.0.1:${port}`],
+ home,
+ {
+ LOBEHUB_JWT: unsignedJwt('fixture-user'),
+ LOBEHUB_SERVER: `http://127.0.0.1:${port}`,
+ },
+ );
+ expect(started.exitCode).toBe(0);
+ await vi.waitFor(() => expect(connection).toBeDefined());
+ const pidPath = path.join(home, '.lobehub', 'daemon.pid');
+ const originalPid = await readFile(pidPath, 'utf8');
+ const command = `bun ${JSON.stringify(path.resolve(import.meta.dirname, '../index.ts'))} connect restart`;
+ const invoke = (requestId: string, shellCommand: string) =>
+ connection!.send(
+ JSON.stringify({
+ requestId,
+ toolCall: {
+ apiName: 'runCommand',
+ arguments: JSON.stringify({ command: shellCommand, timeout: 5000 }),
+ identifier: 'lobe-local-system',
+ },
+ type: 'tool_call_request',
+ }),
+ );
+ invoke('restart', command);
+ await vi.waitFor(() => expect(replies.has('restart')).toBe(true), { timeout: 10_000 });
+ expect(replies.get('restart')?.content).toContain('No connector was stopped');
+ expect(replies.get('restart')?.content).toContain('local terminal or SSH');
+ expect(replies.get('restart')?.state).toEqual(expect.objectContaining({ exitCode: 1 }));
+ expect(await readFile(pidPath, 'utf8')).toBe(originalPid);
+ expect(process.kill(Number(originalPid), 0)).toBe(true);
+ invoke('still-connected', 'printf still-connected');
+ await vi.waitFor(() =>
+ expect(replies.get('still-connected')?.content).toContain('still-connected'),
+ );
+ expect(replies.get('still-connected')?.success).toBe(true);
+ sockets.close();
+ },
+ 20_000,
+ );
+
it('remembers --gateway for that server and reuses it ahead of the advertised one', async () => {
const gatewayServer = createServer();
const sockets = new WebSocketServer({ server: gatewayServer });
@@ -312,7 +438,7 @@ describe('connect daemon startup', () => {
expect(paths.map((url) => url.split('?')[0])).toEqual(['/pinned/ws', '/pinned/ws']);
expect(configReads).toBe(0);
- const status = await runCli(['connect', 'status'], home);
+ const status = await runCli(['connect', 'status', '--verbose'], home);
expect(status.stdout).toContain(`${pinned} (manual)`);
sockets.close();
}, 30_000);
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index 2526a1e6de0..e973b33d2b3 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -11,7 +11,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type * as ApiClientModule from '../api/client';
import type * as RefreshModule from '../auth/refresh';
import { resolveToken } from '../auth/resolveToken';
-import { removeStatus, spawnDaemon, stopDaemon, writeStatus } from '../daemon/manager';
+import {
+ removePid,
+ removeStatus,
+ spawnDaemon,
+ stopDaemon,
+ stopDaemonAndWait,
+ writeStatus,
+} from '../daemon/manager';
import type * as DeviceRegister from '../device/register';
import type * as SystemInfoModule from '../device/systemInfo';
import { cliVersion } from '../pkg';
@@ -137,6 +144,11 @@ vi.mock('../daemon/manager', () => ({
}
return false;
}),
+ stopDaemonAndWait: vi.fn().mockImplementation(async () => {
+ const wasRunning = mockRunningPid !== null;
+ mockRunningPid = null;
+ return wasRunning;
+ }),
writeStatus: vi.fn(),
}));
@@ -691,7 +703,7 @@ describe('connect command', () => {
expect(setVerbose).toHaveBeenCalledWith(true);
});
- it('should handle SIGINT', async () => {
+ it('cleans up only its own daemon records on SIGINT', async () => {
const sigintHandlers: Array<() => Promise<void> | void> = [];
const origOn = process.on;
vi.spyOn(process, 'on').mockImplementation((event: any, handler: any) => {
@@ -700,7 +712,7 @@ describe('connect command', () => {
});
const program = createProgram();
- await program.parseAsync(['node', 'test', 'connect']);
+ await program.parseAsync(['node', 'test', 'connect', '--daemon-child']);
// Trigger SIGINT handler
for (const handler of sigintHandlers) {
@@ -713,7 +725,8 @@ describe('connect command', () => {
vi.mocked(cleanupAllProcesses).mock.invocationCallOrder[0],
);
expect(cleanupAllProcesses).toHaveBeenCalled();
- expect(removeStatus).toHaveBeenCalled();
+ expect(removeStatus).toHaveBeenCalledWith(process.pid);
+ expect(removePid).toHaveBeenCalledWith(process.pid);
});
it('should handle auth_expired when refresh fails', async () => {
@@ -1000,7 +1013,7 @@ describe('connect command', () => {
vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');
systemService.enabled = true;
try {
- await createProgram().parseAsync(['node', 'test', 'connect', ...command]);
+ await createProgram().parseAsync(['node', 'test', 'connect', ...command, '--verbose']);
const output = vi.mocked(log.info).mock.calls.flat().join('\n');
expect(output).toContain('system');
expect(output).toContain('4567');
@@ -1034,41 +1047,94 @@ describe('connect command', () => {
await program.parseAsync(['node', 'test', 'connect', 'status']);
expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Daemon Status'));
- expect(log.info).toHaveBeenCalledWith(expect.stringContaining('12345'));
expect(log.info).toHaveBeenCalledWith(expect.stringContaining('connected'));
});
});
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.each([['--daemon']])('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;
const program = createProgram();
await program.parseAsync(['node', 'test', 'connect', 'restart']);
- expect(stopDaemon).toHaveBeenCalled();
+ expect(stopDaemonAndWait).toHaveBeenCalled();
expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Stopped existing'));
expect(spawnDaemon).toHaveBeenCalled();
});
+ it.each([
+ [
+ 'connect',
+ 'restart',
+ '--device-id',
+ 'fixture-self',
+ '--gateway',
+ 'wss://gateway.example.test',
+ ],
+ [
+ 'connect',
+ '--device-id',
+ 'fixture-self',
+ '--gateway',
+ 'wss://gateway.example.test',
+ 'restart',
+ ],
+ ])('preserves explicit connection options: %j', async (...args) => {
+ mockRunningPid = 12345;
+ await createProgram().parseAsync(['node', 'test', ...args]);
+ expect(spawnDaemon).toHaveBeenCalledWith(
+ expect.arrayContaining([
+ '--device-id',
+ 'fixture-self',
+ '--gateway',
+ 'wss://gateway.example.test',
+ ]),
+ );
+ });
+
+ it('does not launch a replacement until shutdown has finished', async () => {
+ mockRunningPid = 12345;
+ let finishStop!: (stopped: boolean) => void;
+ vi.mocked(stopDaemonAndWait).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishStop = resolve;
+ }),
+ );
+ const restarting = createProgram().parseAsync(['node', 'test', 'connect', 'restart']);
+ await vi.waitFor(() => expect(finishStop).toBeDefined());
+ expect(spawnDaemon).not.toHaveBeenCalled();
+ mockRunningPid = null;
+ finishStop(true);
+ await restarting;
+ expect(spawnDaemon).toHaveBeenCalledOnce();
+ });
+
+ it('does not launch a replacement when the previous daemon will not stop', async () => {
+ mockRunningPid = 12345;
+ vi.mocked(stopDaemonAndWait).mockRejectedValueOnce(new Error('previous daemon did not exit'));
+ await expect(
+ createProgram().parseAsync(['node', 'test', 'connect', 'restart']),
+ ).rejects.toThrow('did not exit');
+ expect(spawnDaemon).not.toHaveBeenCalled();
+ });
+
it('should start daemon even if none was running', async () => {
const program = createProgram();
await program.parseAsync(['node', 'test', 'connect', 'restart']);
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index ce5d3106dca..4d993c46ecb 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -33,6 +33,7 @@ import { scheduleProactiveRefresh } from '../auth/proactiveRefresh';
import { resolveToken } from '../auth/resolveToken';
import { CLI_API_KEY_ENV } from '../constants/auth';
import { CLI_CONNECT_SERVICE_NAME, CLI_DISPLAY_NAME, CLI_PRIMARY_BIN } from '../constants/identity';
+import { getCliInstallationPath } from '../daemon/installation';
import { CliMaintenance } from '../daemon/maintenance';
import {
appendLog,
@@ -44,6 +45,7 @@ import {
reportDaemonStartupReady,
spawnDaemon,
stopDaemon,
+ stopDaemonAndWait,
writeStatus,
} from '../daemon/manager';
import { listTasks } from '../daemon/taskRegistry';
@@ -68,7 +70,6 @@ import {
CONNECT_RETRYABLE_EXIT_CODE,
getWorkspaceFailureExitCode,
installConnectService,
- restartConnectService,
startConnectService,
stopConnectService,
uninstallConnectService,
@@ -87,6 +88,7 @@ import { executeComputerUseCall, resolveComputerUseDevice } from '../tools/compu
import { cleanupAllProcesses, getActiveShellCount } from '../tools/shell';
import { log, setVerbose } from '../utils/logger';
import { sweepLocalTraces } from '../utils/traceMaintenance';
+import { restartConnector } from './connectRestart';
import { printConnectStatus } from './connectStatus';
/** Longest a clean stop waits to push pending device health samples. */
@@ -102,6 +104,7 @@ interface ConnectOptions {
daemonChild?: boolean;
deviceId?: string;
gateway?: string;
+ manager?: string;
/** With --workspace: enroll into the shared pool visible to every member (default: private). */
public?: boolean;
serviceChild?: boolean;
@@ -161,8 +164,11 @@ export function registerConnectCommand(program: Command) {
connectCmd
.command('status')
- .description('Show connect daemon and user/system service status')
- .action(() => printConnectStatus());
+ .description('Show connection, running version, and any required action')
+ .option('-v, --verbose', 'Include service details and installation paths')
+ .action((options: { verbose?: boolean }, command: Command) =>
+ printConnectStatus({ verbose: options.verbose || command.optsWithGlobals().verbose }),
+ );
connectCmd
.command('logs')
@@ -191,7 +197,8 @@ export function registerConnectCommand(program: Command) {
connectCmd
.command('restart')
- .description('Restart the background daemon process')
+ .description('Restart the detected daemon or systemd connect service')
+ .option('--manager <manager>', 'Choose a connector when multiple exist: daemon, user, system')
.option('--token <jwt>', 'JWT access token')
.option('--gateway <url>', 'Device gateway URL')
.option('--device-id <id>', 'Device ID')
@@ -201,12 +208,13 @@ export function registerConnectCommand(program: Command) {
'Run the browser tool with this agent-browser binary (default: agent-browser on PATH)',
)
.option('-v, --verbose', 'Enable verbose logging')
- .action(async (options: ConnectOptions) => {
- const wasStopped = stopDaemon();
- if (wasStopped) {
- log.info('Stopped existing daemon.');
- }
- await handleDaemonStart({ ...options, daemon: true });
+ .action((_options: ConnectOptions, command: Command) => {
+ const options = command.optsWithGlobals<ConnectOptions>();
+ return restartConnector(options, async () => {
+ const wasStopped = await stopDaemonAndWait();
+ if (wasStopped) log.info('Stopped existing daemon.');
+ await handleDaemonStart({ ...options, daemon: true });
+ });
});
const serviceCmd = connectCmd
@@ -270,20 +278,21 @@ export function registerConnectCommand(program: Command) {
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 user-level connect service is installed. Run 'lh connect service status' to check for a system-level service.",
- );
- });
+ .description(
+ 'Restart the user-level connect service (alias for connect restart --manager user)',
+ )
+ .action(() => restartConnector({ manager: 'user' }, async () => {}));
serviceCmd
.command('status')
.description('Show user-level and system-level connect service status')
- .action(() => printConnectStatus({ servicesOnly: true }));
+ .option('-v, --verbose', 'Include service details and installation paths')
+ .action((options: { verbose?: boolean }, command: Command) =>
+ printConnectStatus({
+ servicesOnly: true,
+ verbose: options.verbose || command.optsWithGlobals().verbose,
+ }),
+ );
// 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
@@ -467,11 +476,13 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
info('───────────────────');
// Update local connection status so other CLI commands can resolve the current device
+ const cliPath = await getCliInstallationPath();
let connectionStatus = 'connecting';
let lastRequestAt: string | undefined;
const updateStatus = (status: string) => {
connectionStatus = status;
writeStatus({
+ cliPath,
cliVersion,
connectionStatus,
deviceId: client.currentDeviceId,
@@ -909,9 +920,9 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
for (const wsId of workspaceConnections.keys()) closeWorkspaceConnection(wsId);
void metricsSampler?.stop();
client.disconnect();
- removeStatus();
+ removeStatus(process.pid);
if (isDaemonChild) {
- removePid();
+ removePid(process.pid);
}
};
diff --git a/apps/cli/src/commands/connectRestart.test.ts b/apps/cli/src/commands/connectRestart.test.ts
new file mode 100644
index 00000000000..49ed823fb6c
--- /dev/null
+++ b/apps/cli/src/commands/connectRestart.test.ts
@@ -0,0 +1,211 @@
+import { spawn } from 'node:child_process';
+import { EventEmitter } from 'node:events';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type ConnectRuntime, readConnectRuntimes } from '../daemon/connectStatus';
+import { log } from '../utils/logger';
+import { restartConnector } from './connectRestart';
+
+vi.mock('../daemon/connectStatus', () => ({ readConnectRuntimes: vi.fn() }));
+vi.mock('node:child_process', () => ({ spawn: vi.fn() }));
+
+function service(scope: 'system' | 'user'): ConnectRuntime {
+ return {
+ manager: scope,
+ pid: 42,
+ restartCommand: `${scope === 'system' ? 'sudo systemctl' : 'systemctl --user'} --no-block restart lobehub-connect.service`,
+ service: {
+ active: true,
+ enabled: true,
+ fragmentPath: null,
+ mainPid: 42,
+ restart: 'always',
+ restartPreventExitStatus: [],
+ scope,
+ serviceName: 'lobehub-connect.service',
+ subState: 'running',
+ successExitStatus: [],
+ user: 'user',
+ },
+ };
+}
+const daemon: ConnectRuntime = { manager: 'daemon', pid: 84, restartCommand: 'lh connect restart' };
+const restartDaemon = vi.fn().mockResolvedValue(undefined);
+let exitCode: typeof process.exitCode;
+
+beforeEach(() => {
+ exitCode = process.exitCode;
+ vi.spyOn(process, 'getuid').mockReturnValue(1000);
+ vi.mocked(spawn).mockImplementation(() => {
+ const child = new EventEmitter();
+ queueMicrotask(() => child.emit('close', 0));
+ return child as ReturnType<typeof spawn>;
+ });
+});
+afterEach(() => {
+ process.exitCode = exitCode;
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+});
+
+describe('restartConnector', () => {
+ it.each(['system', 'user'] as const)(
+ 'requests a nonblocking %s restart without starting a daemon',
+ async (scope) => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [service(scope)],
+ unavailableScopes: scope === 'system' ? ['user'] : [],
+ });
+ await restartConnector({}, restartDaemon);
+ expect(spawn).toHaveBeenCalledWith(
+ scope === 'system' ? 'sudo' : 'systemctl',
+ [
+ ...(scope === 'system' ? ['systemctl', '--system'] : ['--user']),
+ '--no-block',
+ 'restart',
+ 'lobehub-connect.service',
+ ],
+ { stdio: 'inherit' },
+ );
+ expect(restartDaemon).not.toHaveBeenCalled();
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('remote terminals'));
+ expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Terminated'));
+ expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Restart requested'));
+ expect(vi.mocked(log.warn).mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(spawn).mock.invocationCallOrder[0],
+ );
+ },
+ );
+
+ it('does not require sudo when already root', async () => {
+ vi.mocked(process.getuid!).mockReturnValue(0);
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [service('system')],
+ unavailableScopes: [],
+ });
+ await restartConnector({}, restartDaemon);
+ expect(spawn).toHaveBeenCalledWith(
+ 'systemctl',
+ ['--system', '--no-block', 'restart', 'lobehub-connect.service'],
+ { stdio: 'inherit' },
+ );
+ });
+
+ it('requires an explicit choice when multiple connectors are running', async () => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [service('system'), service('user'), daemon],
+ unavailableScopes: [],
+ });
+ await restartConnector({}, restartDaemon);
+ expect(spawn).not.toHaveBeenCalled();
+ expect(restartDaemon).not.toHaveBeenCalled();
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Multiple connectors'));
+ await restartConnector({ manager: 'user' }, restartDaemon);
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
+ it('prefers the active service over an inactive installation', async () => {
+ const inactive = service('user');
+ inactive.pid = null;
+ inactive.service!.active = false;
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [inactive, service('system')],
+ unavailableScopes: [],
+ });
+ await restartConnector({}, restartDaemon);
+ expect(spawn).toHaveBeenCalledWith(
+ 'sudo',
+ expect.arrayContaining(['--system']),
+ expect.anything(),
+ );
+ });
+
+ it('does not stop a selected daemon if a service would prevent its replacement', async () => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [daemon, service('system')],
+ unavailableScopes: [],
+ });
+ await restartConnector({ manager: 'daemon' }, restartDaemon);
+ expect(process.exitCode).toBe(1);
+ expect(restartDaemon).not.toHaveBeenCalled();
+ expect(spawn).not.toHaveBeenCalled();
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('No connector was stopped'));
+ });
+
+ it('warns before restarting a daemon', async () => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({ runtimes: [daemon], unavailableScopes: [] });
+ await restartConnector({}, restartDaemon);
+ expect(restartDaemon).toHaveBeenCalledOnce();
+ expect(vi.mocked(log.warn).mock.invocationCallOrder[0]).toBeLessThan(
+ restartDaemon.mock.invocationCallOrder[0],
+ );
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('preserves restart-as-start when no connector exists', async () => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({ runtimes: [], unavailableScopes: [] });
+ await restartConnector({}, restartDaemon);
+ expect(restartDaemon).toHaveBeenCalledOnce();
+ });
+
+ it.each(['user', 'system'] as const)(
+ 'does not start a competing daemon when %s inspection fails',
+ async (scope) => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [],
+ unavailableScopes: [scope],
+ });
+ await restartConnector({}, restartDaemon);
+ expect(process.exitCode).toBe(1);
+ expect(restartDaemon).not.toHaveBeenCalled();
+ expect(spawn).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['invalid', 'user'])(
+ 'rejects an invalid or missing explicit manager: %s',
+ async (manager) => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [service('system')],
+ unavailableScopes: [],
+ });
+ await restartConnector({ manager }, restartDaemon);
+ expect(process.exitCode).toBe(1);
+ expect(spawn).not.toHaveBeenCalled();
+ expect(restartDaemon).not.toHaveBeenCalled();
+ },
+ );
+
+ it('does not silently ignore daemon options or expose their values for a service', async () => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [service('system')],
+ unavailableScopes: [],
+ });
+ await restartConnector({ token: 'private-token' }, restartDaemon);
+ expect(spawn).not.toHaveBeenCalled();
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('cannot override'));
+ expect(JSON.stringify(vi.mocked(log.error).mock.calls)).not.toContain('private-token');
+ });
+
+ it.each(['error', 'nonzero'])(
+ 'does not report success after a failed restart request (%s)',
+ async (failure) => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [service('system')],
+ unavailableScopes: [],
+ });
+ vi.mocked(spawn).mockImplementationOnce(() => {
+ const child = new EventEmitter();
+ queueMicrotask(() =>
+ failure === 'error' ? child.emit('error', new Error('denied')) : child.emit('close', 1),
+ );
+ return child as ReturnType<typeof spawn>;
+ });
+ await restartConnector({}, restartDaemon);
+ expect(process.exitCode).toBe(1);
+ expect(log.info).not.toHaveBeenCalledWith(expect.stringContaining('Restart requested'));
+ expect(restartDaemon).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/apps/cli/src/commands/connectRestart.ts b/apps/cli/src/commands/connectRestart.ts
new file mode 100644
index 00000000000..3408ad6a637
--- /dev/null
+++ b/apps/cli/src/commands/connectRestart.ts
@@ -0,0 +1,125 @@
+import { spawn } from 'node:child_process';
+
+import { type ConnectRuntime, readConnectRuntimes } from '../daemon/connectStatus';
+import { log } from '../utils/logger';
+
+export interface ConnectRestartOptions {
+ agentBrowser?: string;
+ auv?: string;
+ deviceId?: string;
+ gateway?: string;
+ manager?: string;
+ token?: string;
+}
+
+/** Select a single owner before stopping anything; never start a daemon beside a service. */
+export async function restartConnector(
+ options: ConnectRestartOptions,
+ restartDaemon: () => Promise<void>,
+) {
+ const fail = (message: string) => {
+ log.error(message);
+ process.exitCode = 1;
+ };
+ if (options.manager && !['daemon', 'user', 'system'].includes(options.manager)) {
+ fail('Unknown manager. Use --manager daemon, user, or system.');
+ return;
+ }
+ const { runtimes, unavailableScopes } = await readConnectRuntimes();
+ if (options.manager && unavailableScopes.includes(options.manager as 'user' | 'system')) {
+ fail(`Cannot inspect the ${options.manager} systemd manager. No restart was requested.`);
+ return;
+ }
+ // An unseen service could also own this device. Require an explicit choice rather than guessing.
+ if (!options.manager && unavailableScopes.includes('system')) {
+ fail('Cannot inspect system services. Run lh connect status --verbose, then choose --manager.');
+ return;
+ }
+ const matching = runtimes.filter(
+ (runtime) => !options.manager || runtime.manager === options.manager,
+ );
+ const running = matching.filter((runtime) => runtime.pid || runtime.service?.active);
+ const candidates = running.length ? running : matching;
+ if (candidates.length > 1) {
+ fail(
+ 'Multiple connectors found. Choose one with lh connect restart --manager daemon|user|system.',
+ );
+ return;
+ }
+ const target = candidates[0];
+ if (!target) {
+ if (options.manager || unavailableScopes.length) {
+ fail(
+ 'No connector found in the selected/available manager. Run lh connect status --verbose.',
+ );
+ return;
+ }
+ // Preserve the existing restart-as-start behavior when no managed connector exists.
+ await restartDaemon();
+ return;
+ }
+ if (
+ target.manager === 'daemon' &&
+ runtimes.some((runtime) => runtime.service && (runtime.service.active || runtime.pid))
+ ) {
+ fail(
+ 'A systemd connect service is also running. Stop that service before restarting the daemon. No connector was stopped.',
+ );
+ return;
+ }
+ if (
+ target.service &&
+ [options.token, options.gateway, options.deviceId, options.auv, options.agentBrowser].some(
+ Boolean,
+ )
+ ) {
+ fail(
+ 'Connection options cannot override a systemd service. Update its configuration before restarting.',
+ );
+ return;
+ }
+
+ log.warn(
+ 'Restarting disconnects the device and closes its remote terminals. Wait for active tasks to finish.',
+ );
+ log.info('If this terminal is provided by LobeHub, it may close or show "Terminated".');
+ log.info(
+ "After reconnecting, run 'lh connect status' to confirm the running version and connection.",
+ );
+ if (!target.service) {
+ log.info('Waiting for the previous daemon to exit before starting its replacement...');
+ await restartDaemon();
+ return;
+ }
+ log.info(`Requesting restart of the ${target.manager}-level connect service...`);
+ try {
+ await requestServiceRestart(target);
+ log.info(
+ 'Restart requested. The service may still be starting; this does not confirm a connection.',
+ );
+ } catch {
+ fail(
+ `Could not request the restart. Check permissions and service status, or run: ${target.restartCommand}`,
+ );
+ }
+}
+
+function requestServiceRestart(runtime: ConnectRuntime): Promise<void> {
+ const system = runtime.manager === 'system';
+ const sudo = system && process.getuid?.() !== 0;
+ const command = sudo ? 'sudo' : 'systemctl';
+ const args = [
+ ...(sudo ? ['systemctl'] : []),
+ system ? '--system' : '--user',
+ '--no-block',
+ 'restart',
+ runtime.service!.serviceName,
+ ];
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, args, { stdio: 'inherit' });
+ child.once('error', reject);
+ child.once('close', (code) =>
+ code === 0 ? resolve() : reject(new Error('Restart request failed')),
+ );
+ });
+}
diff --git a/apps/cli/src/commands/connectStatus.test.ts b/apps/cli/src/commands/connectStatus.test.ts
index f58e1c73af0..529828d6e7d 100644
--- a/apps/cli/src/commands/connectStatus.test.ts
+++ b/apps/cli/src/commands/connectStatus.test.ts
@@ -2,11 +2,16 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import type { ConnectRuntime } from '../daemon/connectStatus';
import { readConnectRuntimes } from '../daemon/connectStatus';
+import { getCliInstallationPath, getConnectorInstallationPath } from '../daemon/installation';
import { cliVersion } from '../pkg';
import { log } from '../utils/logger';
-import { describeStaleConnector, warnStaleConnectors } from './connectStatus';
+import { describeStaleConnector, printConnectStatus, warnStaleConnectors } from './connectStatus';
vi.mock('../daemon/connectStatus', () => ({ readConnectRuntimes: vi.fn() }));
+vi.mock('../daemon/installation', () => ({
+ getCliInstallationPath: vi.fn().mockResolvedValue('/opt/cli/dist/index.js'),
+ getConnectorInstallationPath: vi.fn().mockResolvedValue('/opt/cli/dist/index.js'),
+}));
const runtime = (cliVersionReported?: string, pid: number | null = 42): ConnectRuntime => ({
manager: 'system',
@@ -21,6 +26,143 @@ const runtime = (cliVersionReported?: string, pid: number | null = 42): ConnectR
},
});
+const systemServiceRuntime = (): ConnectRuntime => ({
+ ...runtime(cliVersion),
+ service: {
+ active: true,
+ enabled: true,
+ fragmentPath: '/etc/systemd/system/lobehub-connect.service',
+ mainPid: 42,
+ restart: 'always',
+ restartPreventExitStatus: [],
+ scope: 'system',
+ serviceName: 'lobehub-connect.service',
+ subState: 'running',
+ successExitStatus: [],
+ user: 'ubuntu',
+ },
+});
+
+describe('service inspection messages', () => {
+ afterEach(() => vi.clearAllMocks());
+
+ it.each([false, true])(
+ 'reports unavailable user services as info when a system service is connected (servicesOnly=%s)',
+ async (servicesOnly) => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [systemServiceRuntime()],
+ unavailableScopes: ['user'],
+ });
+
+ await printConnectStatus({ servicesOnly, verbose: true });
+
+ expect(log.warn).not.toHaveBeenCalled();
+ expect(log.info).toHaveBeenCalledWith(
+ 'User-level systemd inspection is unavailable. The system-level connect service is running and connected; this does not affect its connection.',
+ );
+ expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Running version'));
+ expect(log.info).toHaveBeenCalledWith(
+ "Check 'systemctl --user status' to diagnose user-level systemd access.",
+ );
+ },
+ );
+
+ it.each(['missing', 'inactive', 'no-pid', 'disconnected', 'unknown', 'daemon'])(
+ 'keeps the warning when the system service is %s',
+ async (state) => {
+ const connected = systemServiceRuntime();
+ if (state === 'inactive') connected.service!.active = false;
+ if (state === 'no-pid') connected.pid = null;
+ if (state === 'disconnected') connected.status!.connectionStatus = 'disconnected';
+ if (state === 'unknown') connected.status = undefined;
+ if (state === 'daemon') {
+ connected.manager = 'daemon';
+ connected.service = undefined;
+ }
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: state === 'missing' ? [] : [connected],
+ unavailableScopes: ['user'],
+ });
+
+ await printConnectStatus();
+
+ expect(log.warn).toHaveBeenCalledWith(
+ "Could not inspect user systemd services. Check 'systemctl --user status'.",
+ );
+ expect(log.info).not.toHaveBeenCalledWith(expect.stringContaining('does not affect'));
+ },
+ );
+
+ it('keeps the healthy default output compact and puts optional inspection details behind verbose', async () => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [systemServiceRuntime()],
+ unavailableScopes: ['user'],
+ });
+ await printConnectStatus();
+ const output = vi.mocked(log.info).mock.calls.flat().join('\n');
+ expect(output).toContain('matches installed CLI');
+ expect(output).toContain('connected');
+ expect(output).toContain('lh connect status --verbose');
+ for (const detail of [
+ 'inspection is unavailable',
+ 'PID',
+ 'Unit',
+ 'Gateway',
+ 'Uptime',
+ 'CLI path',
+ ]) {
+ expect(output).not.toContain(detail);
+ }
+ expect(getCliInstallationPath).not.toHaveBeenCalled();
+ expect(log.warn).not.toHaveBeenCalled();
+ });
+
+ it('diagnoses multiple installations without hiding a stale version', async () => {
+ const connected = systemServiceRuntime();
+ connected.status!.cliVersion = '0.0.0-old';
+ vi.mocked(getConnectorInstallationPath).mockResolvedValueOnce('/other/cli/dist/index.js');
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [connected],
+ unavailableScopes: [],
+ });
+ await printConnectStatus();
+ const output = vi.mocked(log.info).mock.calls.flat().join('\n');
+ expect(output).toContain('/opt/cli/dist/index.js');
+ expect(output).toContain('/other/cli/dist/index.js');
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('Different CLI installations'));
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('running 0.0.0-old'));
+ });
+
+ it('keeps warnings when both systemd managers are unavailable', async () => {
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [],
+ unavailableScopes: ['user', 'system'],
+ });
+
+ await printConnectStatus();
+
+ expect(log.warn).toHaveBeenCalledTimes(2);
+ expect(log.warn).toHaveBeenCalledWith(
+ "Could not inspect system systemd services. Check 'systemctl --system status'.",
+ );
+ expect(log.info).toHaveBeenCalledWith(expect.stringContaining('service status is incomplete'));
+ });
+
+ it('still warns about an outdated connected system service', async () => {
+ const connected = systemServiceRuntime();
+ connected.status!.cliVersion = '0.0.0-old';
+ vi.mocked(readConnectRuntimes).mockResolvedValue({
+ runtimes: [connected],
+ unavailableScopes: ['user'],
+ });
+
+ await printConnectStatus();
+
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('running 0.0.0-old'));
+ expect(log.warn).not.toHaveBeenCalledWith(expect.stringContaining('Could not inspect'));
+ });
+});
+
describe('stale connector warnings', () => {
afterEach(() => vi.clearAllMocks());
@@ -32,7 +174,7 @@ describe('stale connector warnings', () => {
it('names the running version and the restart command after an update', () => {
const lines = describeStaleConnector(runtime('1.2.2'), '1.2.3');
expect(lines[0]).toBe('Connector PID 42 is running 1.2.2; installed CLI is 1.2.3.');
- expect(lines[1]).toContain('sudo systemctl --no-block restart lobehub-connect.service');
+ expect(lines[1]).toContain('lh connect restart --manager system');
});
it('does not treat a connector from before version reporting as current', () => {
diff --git a/apps/cli/src/commands/connectStatus.ts b/apps/cli/src/commands/connectStatus.ts
index 8d8762920a0..2128db2d3cd 100644
--- a/apps/cli/src/commands/connectStatus.ts
+++ b/apps/cli/src/commands/connectStatus.ts
@@ -1,4 +1,5 @@
import { type ConnectRuntime, readConnectRuntimes } from '../daemon/connectStatus';
+import { getCliInstallationPath, getConnectorInstallationPath } from '../daemon/installation';
import { cliVersion } from '../pkg';
import { log } from '../utils/logger';
@@ -13,15 +14,12 @@ export function describeStaleConnector(
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.`,
- `Installing an update does not reload a running connector. After active tasks finish, run: ${runtime.restartCommand}`,
- 'Restarting disconnects the device and closes its remote terminals. If the version still differs, check the service uses the upgraded CLI installation.',
+ `After active tasks finish, run: lh connect restart --manager ${runtime.manager}`,
+ 'Restarting disconnects the device and closes its remote terminals. Reconnect and run lh connect status to confirm the update is in use.',
];
}
-/**
- * Only the mismatch warnings, for commands whose own output is about something else. An
- * update from a CLI that predates the connector report leaves this as the first notice.
- */
+/** Only mismatch warnings, for commands whose own output is about something else. */
export async function warnStaleConnectors() {
const { runtimes } = await readConnectRuntimes();
for (const runtime of runtimes) {
@@ -34,14 +32,33 @@ export async function printConnectStatus(
options: {
installedVersion?: string;
servicesOnly?: boolean;
+ verbose?: 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}`);
+ log.info(`Installed CLI version: ${installedVersion}`);
+ const hasConnectedSystemService = selected.some(
+ (runtime) =>
+ runtime.manager === 'system' &&
+ runtime.service?.active &&
+ runtime.pid &&
+ runtime.status?.connectionStatus === 'connected',
+ );
for (const scope of unavailableScopes) {
- log.warn(`Could not inspect ${scope} systemd services. Check 'systemctl --${scope} status'.`);
+ // User buses are often unavailable inside service-owned terminals. This is
+ // diagnostic detail, not an action for someone whose system service is connected.
+ if (scope === 'user' && hasConnectedSystemService) {
+ if (options.verbose) {
+ log.info(
+ 'User-level systemd inspection is unavailable. The system-level connect service is running and connected; this does not affect its connection.',
+ );
+ log.info("Check 'systemctl --user status' to diagnose user-level systemd access.");
+ }
+ } else {
+ log.warn(`Could not inspect ${scope} systemd services. Check 'systemctl --${scope} status'.`);
+ }
}
if (selected.length === 0) {
log.info(
@@ -54,39 +71,63 @@ export async function printConnectStatus(
return;
}
+ let currentPath: string | undefined;
for (const runtime of selected) {
const { pid, service, status } = runtime;
+ const stale = describeStaleConnector(runtime, installedVersion);
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)'}`,
- );
+ log.info(` Connection : ${pid ? status?.connectionStatus || 'unknown' : 'stopped'}`);
+ log.info(
+ ` Running version : ${pid ? status?.cliVersion || 'unknown (not reported by this process)' : 'not running'}${pid && status?.cliVersion === installedVersion ? ' (matches installed CLI)' : ''}`,
+ );
+ if (options.verbose) {
+ 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}`);
+ if (status) {
+ log.info(` Started at : ${status.startedAt}`);
+ log.info(` Uptime : ${formatUptime(new Date(status.startedAt))}`);
+ log.info(
+ ` Gateway : ${status.gatewayUrl}${status.gatewaySource ? ` (${status.gatewaySource})` : ''}`,
+ );
+ }
+ log.info(` Restart command : ${runtime.restartCommand}`);
}
- 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})` : ''}`,
- );
+ if (options.verbose || stale.length) {
+ currentPath ??= await getCliInstallationPath();
+ const connectorPath = pid
+ ? await getConnectorInstallationPath(pid, status?.cliPath)
+ : undefined;
+ log.info(` CLI path (command): ${currentPath || 'unknown'}`);
+ log.info(` Connector CLI path: ${connectorPath || 'unknown (not reported or accessible)'}`);
+ if (currentPath && connectorPath && currentPath !== connectorPath) {
+ log.warn(
+ service
+ ? 'Different CLI installations detected. Restarting keeps the service installation shown above; update that installation or reconfigure the service to use this CLI.'
+ : "Different CLI installations detected. Restarting the daemon uses this command's CLI installation.",
+ );
+ } else if (stale.length) {
+ log.info(
+ 'If the version still differs after restarting, run lh connect status --verbose to check the installation paths.',
+ );
+ }
}
- log.info(` Restart command : ${runtime.restartCommand}`);
- for (const line of describeStaleConnector(runtime, installedVersion)) log.warn(line);
+ for (const line of stale) log.warn(line);
+ if (!pid)
+ log.info(`To start this connector, run: lh connect restart --manager ${runtime.manager}`);
}
+ if (!options.verbose) log.info('Details: lh connect status --verbose');
}
function formatUptime(startedAt: Date): string {
diff --git a/apps/cli/src/commands/update.runtime.test.ts b/apps/cli/src/commands/update.runtime.test.ts
index e7b04b02667..d58d23dff1f 100644
--- a/apps/cli/src/commands/update.runtime.test.ts
+++ b/apps/cli/src/commands/update.runtime.test.ts
@@ -71,7 +71,7 @@ describe('update with a running connector', () => {
.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('lh connect restart --manager system');
expect(output).toContain('tasks');
expect(spawn).not.toHaveBeenCalled();
});
@@ -86,7 +86,7 @@ describe('update with a running connector', () => {
.flat()
.join('\n');
expect(output).toContain('unknown');
- expect(output).toContain('sudo systemctl --no-block restart lobehub-connect.service');
+ expect(output).toContain('lh connect restart --manager system');
expect(spawn).not.toHaveBeenCalled();
});
@@ -123,9 +123,10 @@ describe('update with a running connector', () => {
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('CLI installation updated: 0.0.71 β†’ 0.0.72');
+ expect(output).toContain('Running connectors were not restarted');
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(output).toContain('lh connect restart --manager system');
expect(spawn).toHaveBeenCalledTimes(1);
expect(spawn.mock.calls[0].slice(0, 2)).toEqual([
'npm',
diff --git a/apps/cli/src/commands/update.test.ts b/apps/cli/src/commands/update.test.ts
index 73039ba088a..3b1c4e329fe 100644
--- a/apps/cli/src/commands/update.test.ts
+++ b/apps/cli/src/commands/update.test.ts
@@ -115,7 +115,7 @@ describe('reportInstalledConnectStatus', () => {
await reportInstalledConnectStatus('2.0.0');
expect(spawn).not.toHaveBeenCalled();
- expect(printConnectStatus).toHaveBeenCalledWith({ installedVersion: '2.0.0' });
+ expect(printConnectStatus).toHaveBeenCalledWith({ installedVersion: '2.0.0', verbose: false });
});
it('reports from this process when the installed CLI cannot report', async () => {
@@ -124,6 +124,19 @@ describe('reportInstalledConnectStatus', () => {
await reportInstalledConnectStatus('2.0.0');
- expect(printConnectStatus).toHaveBeenCalledWith({ installedVersion: '2.0.0' });
+ expect(printConnectStatus).toHaveBeenCalledWith({ installedVersion: '2.0.0', verbose: false });
+ });
+
+ it('forwards verbose diagnostics to the installed CLI', async () => {
+ installedReports('2.0.0');
+ statusExits(0);
+ await reportInstalledConnectStatus('2.0.0', true);
+ expect(spawn).toHaveBeenCalledWith(
+ process.execPath,
+ [entry, 'connect', 'status', '--verbose'],
+ {
+ stdio: 'inherit',
+ },
+ );
});
});
diff --git a/apps/cli/src/commands/update.ts b/apps/cli/src/commands/update.ts
index b3d5fd3b7f8..0d65f38a136 100644
--- a/apps/cli/src/commands/update.ts
+++ b/apps/cli/src/commands/update.ts
@@ -21,6 +21,7 @@ interface UpdateOptions {
check?: boolean;
packageManager?: PackageManager;
tag?: string;
+ verbose?: boolean;
}
/**
@@ -133,7 +134,7 @@ function runEntry(args: string[]): Promise<void> {
* version's detection rather than the code running this update. Report from this process
* when the entry no longer runs the installed version (a versioned pnpm path, for example).
*/
-export async function reportInstalledConnectStatus(installedVersion: string) {
+export async function reportInstalledConnectStatus(installedVersion: string, verbose = false) {
try {
const stdout = await new Promise<string>((resolve, reject) => {
execFile(
@@ -144,13 +145,13 @@ export async function reportInstalledConnectStatus(installedVersion: string) {
);
});
if (stdout.trim() === installedVersion) {
- await runEntry(['connect', 'status']);
+ await runEntry(['connect', 'status', ...(verbose ? ['--verbose'] : [])]);
return;
}
} catch (error) {
log.debug(`Installed CLI report unavailable: ${(error as Error).message}`);
}
- await printConnectStatus({ installedVersion });
+ await printConnectStatus({ installedVersion, verbose });
}
export function registerUpdateCommand(program: Command) {
@@ -158,6 +159,7 @@ export function registerUpdateCommand(program: Command) {
.command('update')
.description(`Update the ${CLI_DISPLAY_NAME} to the latest published version`)
.option('--check', 'Only check for a newer version without installing')
+ .option('-v, --verbose', 'Include connector details and installation paths')
.option('--tag <tag>', 'npm dist-tag to update to', 'latest')
.option(
'--package-manager <pm>',
@@ -190,12 +192,12 @@ export function registerUpdateCommand(program: Command) {
if (!isNewerVersion(latest, current)) {
log.info(pc.green('Installed CLI is already on the latest version.'));
- await printConnectStatus();
+ await printConnectStatus({ verbose: options.verbose });
return;
}
if (options.check) {
- await printConnectStatus();
+ await printConnectStatus({ verbose: options.verbose });
log.info(
`Update available: ${current} β†’ ${pc.green(latest)}. Run ${pc.cyan('lh update')} to upgrade.`,
);
@@ -216,7 +218,10 @@ export function registerUpdateCommand(program: Command) {
process.exit(1);
return;
}
- log.info(pc.green(`Successfully installed CLI ${latest}.`));
- await reportInstalledConnectStatus(latest);
+ log.info(pc.green(`CLI installation updated: ${current} β†’ ${latest}.`));
+ log.info(
+ 'Running connectors were not restarted. Their version and connection are shown below; the update takes effect for each connector after it restarts.',
+ );
+ await reportInstalledConnectStatus(latest, options.verbose);
});
}
diff --git a/apps/cli/src/daemon/installation.test.ts b/apps/cli/src/daemon/installation.test.ts
new file mode 100644
index 00000000000..8f8b2b64652
--- /dev/null
+++ b/apps/cli/src/daemon/installation.test.ts
@@ -0,0 +1,63 @@
+import { readFile, realpath } from 'node:fs/promises';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { getCliInstallationPath, getConnectorInstallationPath } from './installation';
+
+vi.mock('node:fs/promises', () => ({ readFile: vi.fn(), realpath: vi.fn(async (value) => value) }));
+afterEach(() => {
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+});
+
+describe('installation paths', () => {
+ it('resolves the invoked entry to its canonical installation', async () => {
+ vi.mocked(realpath).mockResolvedValueOnce('/opt/npm/@lobehub/cli/dist/index.js');
+ expect(await getCliInstallationPath()).toBe('/opt/npm/@lobehub/cli/dist/index.js');
+ });
+
+ it('uses the connector report without reading its arguments', async () => {
+ expect(await getConnectorInstallationPath(42, '/opt/cli/dist/index.js')).toBe(
+ '/opt/cli/dist/index.js',
+ );
+ expect(readFile).not.toHaveBeenCalled();
+ });
+
+ it('extracts only the entry path of a legacy Linux connector', async () => {
+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');
+ vi.mocked(readFile).mockResolvedValue(
+ '/usr/bin/node\0/opt/cli/dist/index.js\0connect\0--token\0secret\0',
+ );
+ expect(await getConnectorInstallationPath(42)).toBe('/opt/cli/dist/index.js');
+ expect(readFile).toHaveBeenCalledWith('/proc/42/cmdline', 'utf8');
+ });
+
+ it.each([
+ '/bin/sh\0-c\0secret\0',
+ '/usr/bin/node\0--token\0secret\0',
+ '/usr/bin/node\0secret\0connect\0',
+ '/usr/bin/node\0/opt/cli/index.js\0other-command\0',
+ ])('does not guess an entry from an unsupported argv shape', async (argv) => {
+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');
+ vi.mocked(readFile).mockResolvedValue(argv);
+ expect(await getConnectorInstallationPath(42)).toBeUndefined();
+ });
+
+ it('does not fabricate a path when proc is inaccessible', async () => {
+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');
+ vi.mocked(readFile).mockRejectedValueOnce(new Error('permission denied'));
+ expect(await getConnectorInstallationPath(42)).toBeUndefined();
+ });
+
+ it('keeps a valid path for a removed installation', async () => {
+ vi.mocked(realpath).mockRejectedValueOnce(new Error('missing'));
+ expect(await getConnectorInstallationPath(42, '/opt/old/index.js')).toBe('/opt/old/index.js');
+ });
+
+ it.each(['relative.js', '/opt/path\nWARN: false message', '/opt/path\0secret'])(
+ 'rejects invalid reported paths',
+ async (entry) => {
+ expect(await getConnectorInstallationPath(42, entry)).toBeUndefined();
+ },
+ );
+});
diff --git a/apps/cli/src/daemon/installation.ts b/apps/cli/src/daemon/installation.ts
new file mode 100644
index 00000000000..1b64431ccdb
--- /dev/null
+++ b/apps/cli/src/daemon/installation.ts
@@ -0,0 +1,31 @@
+import { readFile, realpath } from 'node:fs/promises';
+import path from 'node:path';
+
+/** Only paths, never the command line or environment (both can contain credentials). */
+async function resolveEntry(entry?: string): Promise<string | undefined> {
+ if (!entry || !path.isAbsolute(entry) || /[\r\n\0]/.test(entry)) return undefined;
+ try {
+ return await realpath(entry);
+ } catch {
+ return entry;
+ }
+}
+
+export function getCliInstallationPath() {
+ return resolveEntry(process.argv[1] ? path.resolve(process.argv[1]) : undefined);
+}
+
+/** Legacy connectors did not report their entry path. Inspect only a known Node/Bun argv shape. */
+export async function getConnectorInstallationPath(pid: number, reportedPath?: string) {
+ if (reportedPath) return resolveEntry(reportedPath);
+ if (process.platform !== 'linux') return undefined;
+ try {
+ const argv = (await readFile(`/proc/${pid}/cmdline`, 'utf8')).split('\0');
+ if (!/^(?:node|nodejs|bun)$/.test(path.basename(argv[0]))) return undefined;
+ if (argv[2] !== 'connect' || !/\.(?:[cm]?js|ts)$/.test(argv[1])) return undefined;
+ return resolveEntry(argv[1]);
+ } catch {
+ // A process may have exited or belong to a different user. Never print proc contents/errors.
+ return undefined;
+ }
+}
diff --git a/apps/cli/src/daemon/manager.test.ts b/apps/cli/src/daemon/manager.test.ts
index f35f58a6b2e..d3ba934c9d0 100644
--- a/apps/cli/src/daemon/manager.test.ts
+++ b/apps/cli/src/daemon/manager.test.ts
@@ -18,6 +18,7 @@ import {
removeStatus,
rotateLogIfNeeded,
stopDaemon,
+ stopDaemonAndWait,
writePid,
writeStatus,
} from './manager';
@@ -75,12 +76,12 @@ describe('daemon manager', () => {
it('should remove PID file', () => {
writePid(12345);
- removePid();
+ removePid(12345);
expect(readPid()).toBeNull();
});
it('should not throw when removing non-existent PID file', () => {
- expect(() => removePid()).not.toThrow();
+ expect(() => removePid(12345)).not.toThrow();
});
});
@@ -165,6 +166,9 @@ describe('daemon manager', () => {
startedAt: new Date().toISOString(),
};
writeStatus(serviceStatus);
+ vi.mocked(xSync).mockReturnValue({
+ stdout: '/usr/bin/node cli.js connect --service-child',
+ } as any);
expect(getRunningDaemonPid()).toBeNull();
expect(readPid()).toBeNull();
@@ -212,12 +216,224 @@ describe('daemon manager', () => {
pid: 1,
startedAt: '',
});
- removeStatus();
+ removeStatus(1);
expect(readStatus()).toBeNull();
});
it('should not throw when removing non-existent status file', () => {
- expect(() => removeStatus()).not.toThrow();
+ expect(() => removeStatus(1)).not.toThrow();
+ });
+ });
+
+ describe('restart ownership and recovery', () => {
+ const statusFor = (pid: number) => ({
+ connectionStatus: 'connected',
+ gatewayUrl: 'https://gateway.test',
+ pid,
+ startedAt: '',
+ });
+
+ it('does not let late cleanup from a predecessor delete a replacement', () => {
+ writePid(101);
+ writeStatus(statusFor(101));
+ writePid(202);
+ writeStatus(statusFor(202));
+
+ removePid(101);
+ removeStatus(101);
+
+ expect(readPid()).toBe(202);
+ expect(readStatus()?.pid).toBe(202);
+ removePid(202);
+ removeStatus(202);
+ expect(readPid()).toBeNull();
+ expect(readStatus()).toBeNull();
+ });
+
+ it('recovers a live daemon from its status without restarting it', () => {
+ writeStatus(statusFor(process.pid));
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ try {
+ expect(getRunningDaemonPid()).toBe(process.pid);
+ expect(readPid()).toBe(process.pid);
+ expect(kill.mock.calls.every(([, signal]) => signal === 0)).toBe(true);
+ } finally {
+ kill.mockRestore();
+ }
+ });
+
+ it('recovers the replacement after cleaning up a different stale pid', () => {
+ writePid(999999);
+ writeStatus(statusFor(process.pid));
+ expect(getRunningDaemonPid()).toBe(process.pid);
+ expect(readPid()).toBe(process.pid);
+ expect(readStatus()?.pid).toBe(process.pid);
+ });
+
+ it.each([
+ '/usr/bin/node cli.js connect --service-child',
+ '/usr/bin/node cli.js connect',
+ '/usr/bin/vim notes.txt',
+ '/usr/bin/node cli.js disconnect --daemon-child',
+ '/usr/bin/node cli.js connect --daemon-child-extra',
+ ])('does not recover a service, foreground, or unrelated process: %s', (command) => {
+ writeStatus(statusFor(process.pid));
+ vi.mocked(xSync).mockReturnValue({ stdout: command } as any);
+ expect(getRunningDaemonPid()).toBeNull();
+ expect(readPid()).toBeNull();
+ expect(readStatus()?.pid).toBe(process.pid);
+ });
+
+ it('does not overwrite a concurrent launcher while recovering a missing pid', () => {
+ writeStatus(statusFor(42));
+ const originalWrite = fs.writeFileSync;
+ const write = vi.spyOn(fs, 'writeFileSync').mockImplementationOnce((file, data, options) => {
+ originalWrite(file, '84', { mode: 0o600 });
+ originalWrite(file, data, options);
+ });
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ try {
+ expect(getRunningDaemonPid()).toBe(84);
+ expect(readPid()).toBe(84);
+ } finally {
+ write.mockRestore();
+ kill.mockRestore();
+ }
+ });
+
+ it.each([0, -1, 1.5, '42', null])('does not trust an invalid status pid: %s', async (pid) => {
+ await writeFile(
+ path.join(mockDir, 'daemon.status.json'),
+ JSON.stringify({ ...statusFor(42), pid }),
+ );
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ try {
+ expect(getRunningDaemonPid()).toBeNull();
+ expect(kill).not.toHaveBeenCalled();
+ } finally {
+ kill.mockRestore();
+ }
+ });
+
+ it('does not recover a dead daemon or signal it', () => {
+ writeStatus(statusFor(999999));
+ expect(getRunningDaemonPid()).toBeNull();
+ expect(readPid()).toBeNull();
+ });
+
+ it('does not recover when process identity cannot be read', () => {
+ writeStatus(statusFor(process.pid));
+ vi.mocked(xSync).mockImplementation(() => {
+ throw new Error('ps unavailable');
+ });
+ expect(getRunningDaemonPid()).toBeNull();
+ expect(readPid()).toBeNull();
+ });
+
+ it.skipIf(process.platform === 'win32')(
+ 'refuses a restart from a daemon-owned shell before signaling',
+ async () => {
+ writePid(process.ppid);
+ writeStatus(statusFor(process.ppid));
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ try {
+ await expect(stopDaemonAndWait(0)).rejects.toThrow('terminal or shell');
+ expect(kill.mock.calls.every(([, signal]) => signal === 0)).toBe(true);
+ expect(readPid()).toBe(process.ppid);
+ expect(readStatus()?.pid).toBe(process.ppid);
+ } finally {
+ kill.mockRestore();
+ }
+ },
+ );
+
+ it('retains metadata and refuses replacement if shutdown times out', async () => {
+ writePid(999999);
+ writeStatus(statusFor(999999));
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ try {
+ await expect(stopDaemonAndWait(0)).rejects.toThrow('No replacement was started');
+ expect(readPid()).toBe(999999);
+ expect(readStatus()?.pid).toBe(999999);
+ } finally {
+ kill.mockRestore();
+ }
+ });
+
+ it('does not mistake an argv inspection failure for a completed shutdown', async () => {
+ writePid(999999);
+ writeStatus(statusFor(999999));
+ vi.mocked(xSync).mockReturnValueOnce({ stdout: DAEMON_COMMAND } as any);
+ vi.mocked(xSync).mockReturnValueOnce({ stdout: DAEMON_COMMAND } as any);
+ vi.mocked(xSync).mockImplementation(() => {
+ throw new Error('ps unavailable');
+ });
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ try {
+ await expect(stopDaemonAndWait(0)).rejects.toThrow('No replacement was started');
+ expect(readPid()).toBe(999999);
+ } finally {
+ kill.mockRestore();
+ }
+ });
+
+ it('does not signal a PID whose identity changed during ancestry inspection', async () => {
+ writePid(999999);
+ writeStatus(statusFor(999999));
+ vi.mocked(xSync)
+ .mockReturnValueOnce({ stdout: DAEMON_COMMAND } as any)
+ .mockReturnValueOnce({ stdout: '/usr/bin/unrelated-process' } as any);
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ try {
+ await expect(stopDaemonAndWait()).rejects.toThrow('Daemon identity changed');
+ expect(kill.mock.calls.every(([, signal]) => signal === 0)).toBe(true);
+ expect(readPid()).toBe(999999);
+ } finally {
+ kill.mockRestore();
+ }
+ });
+
+ it('retains metadata if signaling the daemon is denied', async () => {
+ writePid(999999);
+ writeStatus(statusFor(999999));
+ const kill = vi.spyOn(process, 'kill').mockImplementation((_pid, signal) => {
+ if (signal === 'SIGTERM') throw Object.assign(new Error('denied'), { code: 'EPERM' });
+ return true;
+ });
+ try {
+ await expect(stopDaemonAndWait()).rejects.toThrow('denied');
+ expect(readPid()).toBe(999999);
+ expect(readStatus()?.pid).toBe(999999);
+ } finally {
+ kill.mockRestore();
+ }
+ });
+
+ it.each(['0', '-1', '123garbage', '1.5'])(
+ 'rejects unsafe pid file contents: %s',
+ async (value) => {
+ await writeFile(path.join(mockDir, 'daemon.pid'), value);
+ expect(readPid()).toBeNull();
+ },
+ );
+
+ it('does not delete a replacement that appears while stop is signaling its predecessor', () => {
+ writePid(process.pid);
+ writeStatus(statusFor(process.pid));
+ const kill = vi.spyOn(process, 'kill').mockImplementation((_pid, signal) => {
+ if (signal === 'SIGTERM') {
+ writePid(202);
+ writeStatus(statusFor(202));
+ }
+ return true;
+ });
+ try {
+ expect(stopDaemon()).toBe(true);
+ expect(readPid()).toBe(202);
+ expect(readStatus()?.pid).toBe(202);
+ } finally {
+ kill.mockRestore();
+ }
});
});
@@ -301,7 +517,7 @@ describe('daemon manager', () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation((() => {
callCount++;
if (callCount === 1) return true; // isProcessAlive check (signal 0)
- throw new Error('no such process'); // actual SIGTERM
+ throw Object.assign(new Error('no such process'), { code: 'ESRCH' });
}) as any);
const result = stopDaemon();
diff --git a/apps/cli/src/daemon/manager.ts b/apps/cli/src/daemon/manager.ts
index 5a44ee8c8b6..26ced40df50 100644
--- a/apps/cli/src/daemon/manager.ts
+++ b/apps/cli/src/daemon/manager.ts
@@ -1,10 +1,12 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
import { x, xSync } from 'tinyexec';
import { CLI_CONFIG_DIR_NAME } from '../constants/identity';
+import { assertExternalDaemonRestart } from './restartGuard';
const MAX_LOG_SIZE = 5 * 1024 * 1024; // 5MB
const STARTUP_TIMEOUT_MS = 30_000;
@@ -28,6 +30,8 @@ function getLogFilePath() {
}
export interface DaemonStatus {
+ /** Canonical entry path only; never persist argv or credentials for diagnostics. */
+ cliPath?: string;
/** Captured by the running process, never inferred from the installed package. */
cliVersion?: string;
connectionStatus: string;
@@ -49,8 +53,8 @@ function ensureDir() {
export function readPid(): number | null {
try {
const raw = fs.readFileSync(getPidPath(), 'utf8').trim();
- const pid = Number.parseInt(raw, 10);
- return Number.isNaN(pid) ? null : pid;
+ const pid = Number(raw);
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
} catch {
return null;
}
@@ -58,10 +62,14 @@ export function readPid(): number | null {
export function writePid(pid: number): void {
ensureDir();
- fs.writeFileSync(getPidPath(), String(pid), { mode: 0o600 });
+ const temporary = `${getPidPath()}.${process.pid}.tmp`;
+ fs.writeFileSync(temporary, String(pid), { mode: 0o600 });
+ fs.renameSync(temporary, getPidPath());
}
-export function removePid(): void {
+/** Check ownership before cleanup; restarts must still wait for the predecessor to exit. */
+export function removePid(expectedPid: number): void {
+ if (readPid() !== expectedPid) return;
try {
fs.unlinkSync(getPidPath());
} catch {
@@ -104,7 +112,11 @@ export function isDaemonProcess(pid: number): boolean {
nodePath: false,
});
const command = stdout.trim();
- return command.includes('--daemon-child') && command.includes('connect');
+ return (
+ /(?:^|\s)connect(?:\s|$)/.test(command) &&
+ /(?:^|\s)--daemon-child(?:\s|$)/.test(command) &&
+ !/(?:^|\s)--service-child(?:\s|$)/.test(command)
+ );
} catch {
return false;
}
@@ -116,17 +128,36 @@ export function isDaemonProcess(pid: number): boolean {
*/
export function getRunningDaemonPid(): number | null {
const pid = readPid();
- if (pid === null) return null;
+ if (pid !== null) {
+ // Require both liveness AND identity before using a recorded process.
+ if (isProcessAlive(pid) && isDaemonProcess(pid)) return pid;
+ removePid(pid);
+ removeStatus(pid);
+ }
- // Require both liveness AND identity β€” a live-but-reused PID is treated as
- // stale so we never act on a process that isn't ours.
- if (isProcessAlive(pid) && isDaemonProcess(pid)) return pid;
+ // Older restarts could lose daemon.pid when the predecessor cleaned up late.
+ // Status alone is not authority: services and foreground connections share it.
+ const reportedPid = readStatus()?.pid;
+ if (
+ !reportedPid ||
+ !Number.isSafeInteger(reportedPid) ||
+ reportedPid <= 0 ||
+ !isProcessAlive(reportedPid) ||
+ !isDaemonProcess(reportedPid)
+ )
+ return null;
- // Stale PID file β€” process is dead or the PID now belongs to someone else.
- removePid();
- // Services share the status file; an old daemon pid must not erase their report.
- if (readStatus()?.pid === pid) removeStatus();
- return null;
+ try {
+ // Never overwrite a concurrent launch's PID. A read-only status directory
+ // still permits inspection using the verified process without repairing it.
+ fs.writeFileSync(getPidPath(), String(reportedPid), { flag: 'wx', mode: 0o600 });
+ } catch {
+ const currentPid = readPid();
+ if (currentPid !== null && currentPid !== reportedPid) {
+ return isProcessAlive(currentPid) && isDaemonProcess(currentPid) ? currentPid : null;
+ }
+ }
+ return reportedPid;
}
// --- Status file ---
@@ -147,7 +178,8 @@ export function readStatus(): DaemonStatus | null {
}
}
-export function removeStatus(): void {
+export function removeStatus(expectedPid: number): void {
+ if (readStatus()?.pid !== expectedPid) return;
try {
fs.unlinkSync(getStatusPath());
} catch {
@@ -239,8 +271,8 @@ export function spawnDaemon(args: string[]): Promise<number> {
child.unref();
if (error) {
- removePid();
- removeStatus();
+ removePid(pid);
+ removeStatus(pid);
reject(error);
return;
}
@@ -312,21 +344,49 @@ export function reportDaemonStartupReady(): Promise<void> {
return sendStartupMessage({ type: 'startup-ready' });
}
-/**
- * Stop the running daemon process.
- * Returns true if a process was killed, false if none was running.
- */
+function signalDaemonStop(pid: number): void {
+ try {
+ process.kill(pid, 'SIGTERM');
+ } catch (error) {
+ // A permission failure is not a stopped process: retain its records.
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
+ }
+}
+
+/** Request a stop of the verified daemon; false when no daemon is running. */
export function stopDaemon(): boolean {
const pid = getRunningDaemonPid();
if (pid === null) return false;
+ signalDaemonStop(pid);
+ removePid(pid);
+ removeStatus(pid);
+ return true;
+}
- try {
- process.kill(pid, 'SIGTERM');
- } catch {
- // Process may have exited between check and kill
+/** Also protects upgrades from legacy daemons whose cleanup is unconditional. */
+export async function stopDaemonAndWait(timeoutMs = 30_000): Promise<boolean> {
+ const pid = getRunningDaemonPid();
+ if (pid === null) return false;
+ await assertExternalDaemonRestart(pid);
+ // The ancestry check yielded; do not signal a PID reused during that interval.
+ if (isProcessAlive(pid) && !isDaemonProcess(pid)) {
+ throw new Error(
+ 'Daemon identity changed during inspection. No connector was stopped; retry after checking lh connect status.',
+ );
}
-
- removePid();
- removeStatus();
+ signalDaemonStop(pid);
+ const deadline = Date.now() + timeoutMs;
+ // Failure to inspect argv is not proof of exit. Be conservative even if the
+ // PID is reused: timing out is safer than launching a competing connector.
+ while (isProcessAlive(pid)) {
+ if (Date.now() >= deadline) {
+ throw new Error(
+ 'The previous daemon did not exit. No replacement was started; check lh connect logs before retrying.',
+ );
+ }
+ await delay(100);
+ }
+ removePid(pid);
+ removeStatus(pid);
return true;
}
diff --git a/apps/cli/src/daemon/restartGuard.test.ts b/apps/cli/src/daemon/restartGuard.test.ts
new file mode 100644
index 00000000000..bbb06af1cac
--- /dev/null
+++ b/apps/cli/src/daemon/restartGuard.test.ts
@@ -0,0 +1,60 @@
+import { x } from 'tinyexec';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { assertExternalDaemonRestart } from './restartGuard';
+
+vi.mock('tinyexec', () => ({ x: vi.fn() }));
+
+afterEach(() => vi.resetAllMocks());
+
+function processTable(rows: string) {
+ vi.mocked(x).mockResolvedValue({ exitCode: 0, stderr: '', stdout: rows });
+}
+
+describe('assertExternalDaemonRestart', () => {
+ it('rejects a daemon-owned shell through multiple nested processes', async () => {
+ processTable(`${process.pid} 222\n222 333\n333 444\n444 1\n1 0\n`);
+ await expect(assertExternalDaemonRestart(444)).rejects.toThrow('own terminal or shell');
+ });
+
+ it('also rejects an ancestor running as container init', async () => {
+ processTable(`${process.pid} 222\n222 1\n1 0\n`);
+ await expect(assertExternalDaemonRestart(1)).rejects.toThrow('No connector was stopped');
+ });
+
+ it('permits a local or SSH caller in a different process tree', async () => {
+ processTable(`${process.pid} 222\n222 1\n444 1\n1 0\n`);
+ await expect(assertExternalDaemonRestart(444)).resolves.toBeUndefined();
+ expect(x).toHaveBeenCalledWith(
+ 'ps',
+ ['-axo', 'pid=,ppid='],
+ expect.objectContaining({
+ throwOnError: true,
+ timeout: 2000,
+ }),
+ );
+ });
+
+ it('permits restarting a different daemon from another daemon-owned terminal', async () => {
+ processTable(`${process.pid} 222\n222 333\n333 1\n444 1\n1 0\n`);
+ await expect(assertExternalDaemonRestart(444)).resolves.toBeUndefined();
+ });
+
+ it.each([
+ '',
+ 'unexpected output',
+ `${process.pid} 222\n`,
+ `${process.pid} 222\n222 ${process.pid}\n`,
+ `${process.pid} 9007199254740992\n`,
+ ])('refuses to signal when ancestry is incomplete or invalid: %s', async (rows) => {
+ processTable(rows);
+ await expect(assertExternalDaemonRestart(444)).rejects.toThrow('Could not verify');
+ });
+
+ it('does not leak subprocess errors or claim a restart when inspection fails', async () => {
+ vi.mocked(x).mockRejectedValue(new Error('private process information'));
+ await expect(assertExternalDaemonRestart(444)).rejects.toThrow(
+ 'No connector was stopped. Retry from a local terminal or SSH session.',
+ );
+ });
+});
diff --git a/apps/cli/src/daemon/restartGuard.ts b/apps/cli/src/daemon/restartGuard.ts
new file mode 100644
index 00000000000..1b8fc7012cf
--- /dev/null
+++ b/apps/cli/src/daemon/restartGuard.ts
@@ -0,0 +1,46 @@
+import { x } from 'tinyexec';
+
+const INSPECTION_ERROR =
+ 'Could not verify whether this command is running inside the daemon. No connector was stopped. Retry from a local terminal or SSH session.';
+
+/** A caller killed by daemon cleanup cannot finish waiting and launch its replacement. */
+export async function assertExternalDaemonRestart(daemonPid: number): Promise<void> {
+ let stdout: string;
+ try {
+ ({ stdout } = await x('ps', ['-axo', 'pid=,ppid='], {
+ nodePath: false,
+ throwOnError: true,
+ timeout: 2000,
+ }));
+ } catch {
+ throw new Error(INSPECTION_ERROR);
+ }
+
+ // Read only process relationships, never argv or environment (which may contain credentials).
+ const parents = new Map<number, number>();
+ for (const line of stdout.trim().split('\n')) {
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
+ if (!match) throw new Error(INSPECTION_ERROR);
+ const pid = Number(match[1]);
+ const parent = Number(match[2]);
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(parent)) {
+ throw new Error(INSPECTION_ERROR);
+ }
+ parents.set(pid, parent);
+ }
+
+ const visited = new Set<number>();
+ let current = process.pid;
+ while (current > 0) {
+ if (current === daemonPid) {
+ throw new Error(
+ 'Cannot restart this daemon from its own terminal or shell. No connector was stopped. Run lh connect restart from a local terminal or SSH session instead.',
+ );
+ }
+ if (current === 1) return;
+ const parent = parents.get(current);
+ if (parent === undefined || visited.has(current)) throw new Error(INSPECTION_ERROR);
+ visited.add(current);
+ current = parent;
+ }
+}
diff --git a/apps/cli/src/doctor/checks/device.test.ts b/apps/cli/src/doctor/checks/device.test.ts
index 6bf8a51c3a5..ccdaa8e3218 100644
--- a/apps/cli/src/doctor/checks/device.test.ts
+++ b/apps/cli/src/doctor/checks/device.test.ts
@@ -209,6 +209,27 @@ describe('device.daemon', () => {
expect(outcome.detail).toContain('left over');
});
+ it('repairs only the stale process observed by the check', async () => {
+ state.daemonStatus = {
+ pid: 4,
+ connectionStatus: 'connected',
+ gatewayUrl: 'wss://gw',
+ startedAt: '',
+ };
+ const outcome = await runCheck(deviceChecks, 'device.daemon');
+ state.daemonStatus = { ...state.daemonStatus, pid: 42 };
+ const check = deviceChecks.find((item) => item.id === 'device.daemon')!;
+ await check.repair!(makeContext(), {
+ ...outcome,
+ durationMs: 0,
+ group: 'device',
+ id: check.id,
+ title: check.title,
+ });
+ expect(removePid).toHaveBeenCalledWith(4);
+ expect(removeStatus).toHaveBeenCalledWith(4);
+ });
+
it('does not call a live daemon connected without its own report', async () => {
state.daemonPid = 42;
state.daemonStatus = null;
diff --git a/apps/cli/src/doctor/checks/device.ts b/apps/cli/src/doctor/checks/device.ts
index 34117058f74..9be494e73db 100644
--- a/apps/cli/src/doctor/checks/device.ts
+++ b/apps/cli/src/doctor/checks/device.ts
@@ -26,8 +26,10 @@ const daemon: DoctorCheck = {
if (result.evidence?.repairable !== 'stale-files')
throw new Error('the daemon process is still running, so its pid file is not stale');
- removePid();
- removeStatus();
+ const pid = result.evidence.stalePid;
+ if (typeof pid !== 'number') throw new Error('the stale process identity was not recorded');
+ removePid(pid);
+ removeStatus(pid);
return 'removed the stale daemon pid/status files';
},
run: async (): Promise<CheckOutcome> => {
@@ -70,7 +72,7 @@ const daemon: DoctorCheck = {
if (status)
return {
detail: 'A daemon status file is left over, but no daemon is running.',
- evidence: { ...evidence, repairable: 'stale-files' },
+ evidence: { ...evidence, repairable: 'stale-files', stalePid: status.pid },
fix: `Run '${CLI_PRIMARY_BIN} connect --daemon', or re-run with --fix to clear the leftovers.`,
status: 'warn',
};