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.

πŸ› fix(cli): stop connect daemon on logout (#16038)

Arvin Xu80cce10dd530
diff --git a/apps/cli/package.json b/apps/cli/package.json
index 89506d83c16..e6cb019ab76 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@lobehub/cli",
- "version": "0.0.31",
+ "version": "0.0.32",
"type": "module",
"bin": {
"lh": "./dist/index.js",
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index 6475ba60b28..ecf0145eeeb 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -440,6 +440,25 @@ describe('connect command', () => {
});
});
+ describe('disconnect (alias for connect stop)', () => {
+ it('should stop running daemon', async () => {
+ mockRunningPid = 12345;
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'disconnect']);
+
+ expect(stopDaemon).toHaveBeenCalled();
+ expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Daemon stopped'));
+ });
+
+ it('should warn if no daemon is running', async () => {
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'disconnect']);
+
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('No daemon'));
+ });
+ });
+
describe('connect status', () => {
it('should show no daemon running', async () => {
const program = createProgram();
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index c188d925cbd..0554558167d 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -74,17 +74,7 @@ export function registerConnectCommand(program: Command) {
});
// Subcommands
- connectCmd
- .command('stop')
- .description('Stop the background daemon process')
- .action(() => {
- const stopped = stopDaemon();
- if (stopped) {
- log.info('Daemon stopped.');
- } else {
- log.warn('No daemon is running.');
- }
- });
+ connectCmd.command('stop').description('Stop the background daemon process').action(handleStop);
connectCmd
.command('status')
@@ -148,10 +138,27 @@ export function registerConnectCommand(program: Command) {
}
handleDaemonStart({ ...options, daemon: 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
+ // discoverable enough on its own.
+ program
+ .command('disconnect')
+ .description('Disconnect from the device gateway (alias for `connect stop`)')
+ .action(handleStop);
}
// --- Internal helpers ---
+function handleStop() {
+ const stopped = stopDaemon();
+ if (stopped) {
+ log.info('Daemon stopped.');
+ } else {
+ log.warn('No daemon is running.');
+ }
+}
+
function handleDaemonStart(options: ConnectOptions) {
const existingPid = getRunningDaemonPid();
if (existingPid !== null) {
diff --git a/apps/cli/src/commands/logout.test.ts b/apps/cli/src/commands/logout.test.ts
index de43596b99a..8b7a1244ee5 100644
--- a/apps/cli/src/commands/logout.test.ts
+++ b/apps/cli/src/commands/logout.test.ts
@@ -1,7 +1,8 @@
import { Command } from 'commander';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { clearCredentials } from '../auth/credentials';
+import { stopDaemon } from '../daemon/manager';
import { log } from '../utils/logger';
import { registerLogoutCommand } from './logout';
@@ -9,6 +10,10 @@ vi.mock('../auth/credentials', () => ({
clearCredentials: vi.fn(),
}));
+vi.mock('../daemon/manager', () => ({
+ stopDaemon: vi.fn(),
+}));
+
vi.mock('../utils/logger', () => ({
log: {
debug: vi.fn(),
@@ -19,6 +24,11 @@ vi.mock('../utils/logger', () => ({
}));
describe('logout command', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(stopDaemon).mockReturnValue(false);
+ });
+
function createProgram() {
const program = new Command();
program.exitOverride();
@@ -44,4 +54,24 @@ describe('logout command', () => {
expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Already logged out'));
});
+
+ it('should stop the connect daemon before clearing credentials', async () => {
+ vi.mocked(stopDaemon).mockReturnValue(true);
+ vi.mocked(clearCredentials).mockReturnValue(true);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'logout']);
+
+ expect(stopDaemon).toHaveBeenCalled();
+ expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Disconnected device daemon'));
+ });
+
+ it('should still attempt daemon teardown when no credentials exist', async () => {
+ vi.mocked(clearCredentials).mockReturnValue(false);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'logout']);
+
+ expect(stopDaemon).toHaveBeenCalled();
+ });
});
diff --git a/apps/cli/src/commands/logout.ts b/apps/cli/src/commands/logout.ts
index 4d7cd1d6215..82a7c67c62f 100644
--- a/apps/cli/src/commands/logout.ts
+++ b/apps/cli/src/commands/logout.ts
@@ -1,6 +1,7 @@
import type { Command } from 'commander';
import { clearCredentials } from '../auth/credentials';
+import { stopDaemon } from '../daemon/manager';
import { log } from '../utils/logger';
export function registerLogoutCommand(program: Command) {
@@ -8,6 +9,14 @@ export function registerLogoutCommand(program: Command) {
.command('logout')
.description('Log out and remove stored credentials')
.action(() => {
+ // Tear down the connect daemon first β€” otherwise it keeps the device
+ // online on the gateway with the cached token even after credentials are
+ // gone, leaving the machine remotely driveable past "logout".
+ const stopped = stopDaemon();
+ if (stopped) {
+ log.info('Disconnected device daemon.');
+ }
+
const removed = clearCredentials();
if (removed) {
log.info('Logged out. Credentials removed.');
diff --git a/apps/cli/src/daemon/manager.test.ts b/apps/cli/src/daemon/manager.test.ts
index 1593cb1e741..e2777a6e204 100644
--- a/apps/cli/src/daemon/manager.test.ts
+++ b/apps/cli/src/daemon/manager.test.ts
@@ -19,11 +19,22 @@ vi.mock('node:os', async (importOriginal) => {
};
});
+// Mock only `execFileSync` (used by isDaemonProcess to read a process command
+// line); keep the real `spawn` so nothing else changes.
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, any>>();
+ return { ...actual, execFileSync: vi.fn() };
+});
+
+// eslint-disable-next-line import-x/first
+import { execFileSync } from 'node:child_process';
+
// eslint-disable-next-line import-x/first
import {
appendLog,
getLogPath,
getRunningDaemonPid,
+ isDaemonProcess,
isProcessAlive,
readPid,
readStatus,
@@ -35,9 +46,15 @@ import {
writeStatus,
} from './manager';
+// A command line that matches the daemon signature (`connect … --daemon-child`).
+const DAEMON_COMMAND = '/usr/local/bin/node /path/to/cli.js connect --daemon-child';
+
describe('daemon manager', () => {
beforeEach(async () => {
await mkdir(mockDir, { recursive: true });
+ // Default: any inspected PID looks like our daemon. Tests that need a
+ // reused / unrelated PID override this per-case.
+ vi.mocked(execFileSync).mockReturnValue(DAEMON_COMMAND as any);
});
afterEach(() => {
@@ -80,6 +97,36 @@ describe('daemon manager', () => {
});
});
+ describe('isDaemonProcess', () => {
+ it('should return true when the command line matches the daemon signature', () => {
+ vi.mocked(execFileSync).mockReturnValue(DAEMON_COMMAND as any);
+ expect(isDaemonProcess(12345)).toBe(true);
+ expect(execFileSync).toHaveBeenCalledWith(
+ 'ps',
+ ['-ww', '-p', '12345', '-o', 'command='],
+ expect.any(Object),
+ );
+ });
+
+ it('should return false for an unrelated process command line', () => {
+ vi.mocked(execFileSync).mockReturnValue('/usr/bin/vim notes.txt' as any);
+ expect(isDaemonProcess(12345)).toBe(false);
+ });
+
+ it('should return false when the signature is only partially present', () => {
+ // `connect` without the internal `--daemon-child` flag is not our daemon.
+ vi.mocked(execFileSync).mockReturnValue('/usr/bin/node /path/cli connect' as any);
+ expect(isDaemonProcess(12345)).toBe(false);
+ });
+
+ it('should return false when ps is unavailable / throws', () => {
+ vi.mocked(execFileSync).mockImplementation(() => {
+ throw new Error('ps: command not found');
+ });
+ expect(isDaemonProcess(12345)).toBe(false);
+ });
+ });
+
describe('getRunningDaemonPid', () => {
it('should return null when no PID file', () => {
expect(getRunningDaemonPid()).toBeNull();
@@ -110,6 +157,23 @@ describe('daemon manager', () => {
expect(readStatus()).toBeNull();
});
+
+ 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.
+ writePid(process.pid);
+ writeStatus({
+ connectionStatus: 'connected',
+ gatewayUrl: 'https://test.com',
+ pid: process.pid,
+ startedAt: new Date().toISOString(),
+ });
+ vi.mocked(execFileSync).mockReturnValue('/usr/bin/some-other-process' as any);
+
+ expect(getRunningDaemonPid()).toBeNull();
+ expect(readPid()).toBeNull();
+ expect(readStatus()).toBeNull();
+ });
});
describe('status file', () => {
@@ -232,5 +296,23 @@ describe('daemon manager', () => {
killSpy.mockRestore();
});
+
+ it('should NOT SIGTERM a live PID that is not our daemon', () => {
+ // Stale daemon.pid whose PID was reused by an unrelated, living process.
+ writePid(process.pid);
+ vi.mocked(execFileSync).mockReturnValue('/usr/bin/some-other-process' as any);
+
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+
+ const result = stopDaemon();
+
+ expect(result).toBe(false);
+ // Only the liveness probe (signal 0) is allowed β€” never a real SIGTERM.
+ expect(killSpy).not.toHaveBeenCalledWith(process.pid, 'SIGTERM');
+ // Stale metadata is cleaned up so we don't keep re-checking it.
+ expect(readPid()).toBeNull();
+
+ killSpy.mockRestore();
+ });
});
});
diff --git a/apps/cli/src/daemon/manager.ts b/apps/cli/src/daemon/manager.ts
index e2f0a65bbe4..7f7684b1331 100644
--- a/apps/cli/src/daemon/manager.ts
+++ b/apps/cli/src/daemon/manager.ts
@@ -1,4 +1,4 @@
-import { spawn } from 'node:child_process';
+import { execFileSync, spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -70,6 +70,34 @@ export function isProcessAlive(pid: number): boolean {
}
}
+/**
+ * Verify a live PID actually belongs to a LobeHub connect daemon.
+ *
+ * A bare `isProcessAlive` check is not enough: if a daemon dies without cleaning
+ * up `daemon.pid` (crash, `kill -9`, reboot), the OS can later reuse that PID
+ * for an unrelated process. Acting on the stale PID would let `lh logout` /
+ * `connect stop` SIGTERM a stranger. The daemon is always spawned as
+ * `<node> … connect … --daemon-child`, so we confirm that signature in the
+ * process command line before trusting the PID.
+ *
+ * Best-effort and deliberately conservative: if the command line can't be read
+ * (e.g. `ps` is unavailable), we return `false` so callers never kill a process
+ * we can't positively identify.
+ */
+export function isDaemonProcess(pid: number): boolean {
+ try {
+ // `-ww` disables column truncation so the trailing `--daemon-child` flag is
+ // never cut off; stderr is silenced so a dead PID just yields an empty match.
+ const command = execFileSync('ps', ['-ww', '-p', String(pid), '-o', 'command='], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).trim();
+ return command.includes('--daemon-child') && command.includes('connect');
+ } catch {
+ return false;
+ }
+}
+
/**
* Get the PID of a running daemon, cleaning up stale PID files.
* Returns null if no daemon is running.
@@ -78,9 +106,11 @@ export function getRunningDaemonPid(): number | null {
const pid = readPid();
if (pid === null) return null;
- if (isProcessAlive(pid)) return 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;
- // Stale PID file β€” process is dead
+ // Stale PID file β€” process is dead or the PID now belongs to someone else.
removePid();
removeStatus();
return null;