🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(cli): flag connectors still running pre-update code (#22166)
AmAzing-a459d387959b
diff --git a/apps/cli/src/commands/connectStatus.test.ts b/apps/cli/src/commands/connectStatus.test.tsnew file mode 100644index 00000000000..f58e1c73af0--- /dev/null+++ b/apps/cli/src/commands/connectStatus.test.ts@@ -0,0 +1,56 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { ConnectRuntime } from '../daemon/connectStatus';+import { readConnectRuntimes } from '../daemon/connectStatus';+import { cliVersion } from '../pkg';+import { log } from '../utils/logger';+import { describeStaleConnector, warnStaleConnectors } from './connectStatus';++vi.mock('../daemon/connectStatus', () => ({ readConnectRuntimes: vi.fn() }));++const runtime = (cliVersionReported?: string, pid: number | null = 42): ConnectRuntime => ({+ manager: 'system',+ pid,+ restartCommand: 'sudo systemctl --no-block restart lobehub-connect.service',+ status: {+ cliVersion: cliVersionReported,+ connectionStatus: 'connected',+ gatewayUrl: 'wss://gw',+ pid: 42,+ startedAt: '',+ },+});++describe('stale connector warnings', () => {+ afterEach(() => vi.clearAllMocks());++ it('says nothing when the connector runs the installed version or is not running', () => {+ expect(describeStaleConnector(runtime('1.2.3'), '1.2.3')).toEqual([]);+ expect(describeStaleConnector(runtime(undefined, null), '1.2.3')).toEqual([]);+ });++ 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');+ });++ it('does not treat a connector from before version reporting as current', () => {+ expect(describeStaleConnector(runtime(undefined), '1.2.3')[0]).toContain(+ 'did not report its version',+ );+ });++ it('warns only for connectors that differ from this CLI', async () => {+ vi.mocked(readConnectRuntimes).mockResolvedValue({+ runtimes: [runtime(cliVersion), runtime(undefined)],+ unavailableScopes: [],+ });++ await warnStaleConnectors();++ expect(log.warn).toHaveBeenCalledTimes(3);+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('did not report its version'));+ expect(log.info).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/commands/connectStatus.ts b/apps/cli/src/commands/connectStatus.tsindex 56d9cff8a71..8d8762920a0 100644--- a/apps/cli/src/commands/connectStatus.ts+++ b/apps/cli/src/commands/connectStatus.ts@@ -1,7 +1,34 @@-import { readConnectRuntimes } from '../daemon/connectStatus';+import { type ConnectRuntime, readConnectRuntimes } from '../daemon/connectStatus';import { cliVersion } from '../pkg';import { log } from '../utils/logger';+/** Why a running connector may not be executing the installed CLI. Empty when it is. */+export function describeStaleConnector(+ runtime: ConnectRuntime,+ installedVersion: string,+): string[] {+ const { pid, status } = runtime;+ if (!pid || status?.cliVersion === installedVersion) return [];+ return [+ 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.',+ ];+}++/**+ * 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.+ */+export async function warnStaleConnectors() {+ const { runtimes } = await readConnectRuntimes();+ for (const runtime of runtimes) {+ for (const line of describeStaleConnector(runtime, cliVersion)) log.warn(line);+ }+}+/** Shared by status and update, including when the installed CLI is already current. */export async function printConnectStatus(options: {@@ -58,19 +85,7 @@ export async function printConnectStatus();}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.',- );- }+ for (const line of describeStaleConnector(runtime, installedVersion)) log.warn(line);}}diff --git a/apps/cli/src/commands/status.test.ts b/apps/cli/src/commands/status.test.tsindex c91f2b80e0e..98d06e3faf6 100644--- a/apps/cli/src/commands/status.test.ts+++ b/apps/cli/src/commands/status.test.ts@@ -6,6 +6,7 @@ import { createPublicLambdaClient } from '../api/client';import { resolveToken } from '../auth/resolveToken';import { loadDeviceGatewayUrl, saveDeviceGatewayUrl } from '../settings';import { log } from '../utils/logger';+import { warnStaleConnectors } from './connectStatus';import { registerStatusCommand } from './status';const OFFICIAL_AUTH = {@@ -16,6 +17,8 @@ const OFFICIAL_AUTH = {};const SELF_HOSTED = 'https://self-hosted.example.com';+vi.mock('./connectStatus', () => ({ warnStaleConnectors: vi.fn() }));+// Mock resolveTokenvi.mock('../auth/resolveToken', () => ({ resolveToken: vi.fn() }));vi.mock('../settings', () => ({@@ -67,6 +70,7 @@ describe('status command', () => {vi.mocked(resolveToken).mockResolvedValue(OFFICIAL_AUTH);vi.mocked(loadDeviceGatewayUrl).mockReturnValue(undefined);getGlobalConfig.mockResolvedValue({ serverConfig: {} });+ vi.mocked(warnStaleConnectors).mockResolvedValue(undefined);});afterEach(() => {@@ -102,6 +106,24 @@ describe('status command', () => {await parsePromise;};+ it('flags a connector running other code before probing with a fresh connection', async () => {+ await runConnected();++ expect(warnStaleConnectors).toHaveBeenCalledTimes(1);+ expect(vi.mocked(warnStaleConnectors).mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(resolveToken).mock.invocationCallOrder[0],+ );+ });++ it('still probes when the connector version check fails', async () => {+ vi.mocked(warnStaleConnectors).mockRejectedValue(new Error('status file unreadable'));++ await runConnected();++ expect(connectCalled).toBe(true);+ expect(exitSpy).toHaveBeenCalledWith(0);+ });+it("probes the gateway advertised by the token's server when none is saved", async () => {vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl: SELF_HOSTED });getGlobalConfig.mockResolvedValue({diff --git a/apps/cli/src/commands/status.ts b/apps/cli/src/commands/status.tsindex a8b6aa2f292..975b92e9abf 100644--- a/apps/cli/src/commands/status.ts+++ b/apps/cli/src/commands/status.ts@@ -10,6 +10,7 @@ import {resolveCliDeviceGateway,} from '../device/gatewayEndpoint';import { log, setVerbose } from '../utils/logger';+import { warnStaleConnectors } from './connectStatus';/*** `status` answers one question — does the gateway accept this machine. When it@@ -40,6 +41,12 @@ export function registerStatusCommand(program: Command) {.action(async (options: StatusOptions) => {if (options.verbose) setVerbose(true);+ // This probe opens its own connection, so a pass says nothing about the code a+ // running connector executes. Flag that first; it must never block the probe.+ await warnStaleConnectors().catch((error) =>+ log.debug(`Connector version check skipped: ${(error as Error).message}`),+ );+const auth = await resolveToken(options);// Same resolution as `connect`, against the server this token belongs to.const gateway = await resolveCliDeviceGateway({diff --git a/apps/cli/src/commands/update.test.ts b/apps/cli/src/commands/update.test.tsindex 6e9a4824456..73039ba088a 100644--- a/apps/cli/src/commands/update.test.ts+++ b/apps/cli/src/commands/update.test.ts@@ -1,6 +1,18 @@-import { describe, expect, it } from 'vitest';+import type * as ChildProcessModule from 'node:child_process';+import { EventEmitter } from 'node:events';-import { buildInstallCommand, isNewerVersion } from './update';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { printConnectStatus } from './connectStatus';+import { buildInstallCommand, isNewerVersion, reportInstalledConnectStatus } from './update';++const { execFile, spawn } = vi.hoisted(() => ({ execFile: vi.fn(), spawn: vi.fn() }));+vi.mock('node:child_process', async (original) => ({+ ...(await original<typeof ChildProcessModule>()),+ execFile,+ spawn,+}));+vi.mock('./connectStatus', () => ({ printConnectStatus: vi.fn() }));describe('isNewerVersion', () => {it('compares core versions', () => {@@ -55,3 +67,63 @@ describe('buildInstallCommand', () => {});});});++describe('reportInstalledConnectStatus', () => {+ let originalArgv: string[];+ const entry = '/global/node_modules/@lobehub/cli/dist/index.js';+ const installedReports = (version: string) =>+ execFile.mockImplementation((_command, _args, _options, callback) =>+ callback(null, `${version}\n`),+ );+ const statusExits = (code: number) =>+ spawn.mockImplementation(() => {+ const child = new EventEmitter();+ queueMicrotask(() => child.emit('close', code));+ return child;+ });++ beforeEach(() => {+ originalArgv = process.argv;+ process.argv = [process.execPath, entry];+ });+ afterEach(() => {+ process.argv = originalArgv;+ vi.clearAllMocks();+ });++ it('lets the newly installed CLI report connectors instead of the updating process', async () => {+ installedReports('2.0.0');+ statusExits(0);++ await reportInstalledConnectStatus('2.0.0');++ expect(execFile).toHaveBeenCalledWith(+ process.execPath,+ [entry, '--version'],+ expect.anything(),+ expect.any(Function),+ );+ expect(spawn).toHaveBeenCalledWith(process.execPath, [entry, 'connect', 'status'], {+ stdio: 'inherit',+ });+ expect(printConnectStatus).not.toHaveBeenCalled();+ });++ it('reports from this process when the entry does not run the installed version', async () => {+ installedReports('1.0.0');++ await reportInstalledConnectStatus('2.0.0');++ expect(spawn).not.toHaveBeenCalled();+ expect(printConnectStatus).toHaveBeenCalledWith({ installedVersion: '2.0.0' });+ });++ it('reports from this process when the installed CLI cannot report', async () => {+ installedReports('2.0.0');+ statusExits(1);++ await reportInstalledConnectStatus('2.0.0');++ expect(printConnectStatus).toHaveBeenCalledWith({ installedVersion: '2.0.0' });+ });+});diff --git a/apps/cli/src/commands/update.ts b/apps/cli/src/commands/update.tsindex 2eec9899716..b3d5fd3b7f8 100644--- a/apps/cli/src/commands/update.ts+++ b/apps/cli/src/commands/update.ts@@ -1,4 +1,4 @@-import { spawn } from 'node:child_process';+import { execFile, spawn } from 'node:child_process';import { realpathSync } from 'node:fs';import type { Command } from 'commander';@@ -117,6 +117,42 @@ function runInstall(command: string, args: string[]): Promise<void> {});}+function runEntry(args: string[]): Promise<void> {+ return new Promise((resolve, reject) => {+ // The Node binary and entry path are passed as argv, never through a shell.+ const child = spawn(process.execPath, [process.argv[1], ...args], { stdio: 'inherit' });+ child.on('error', reject);+ child.on('close', (code) =>+ code === 0 ? resolve() : reject(new Error(`exited with code ${code ?? 'null'}`)),+ );+ });+}++/**+ * Let the CLI that was just installed report the connectors, so the user sees the new+ * 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) {+ try {+ const stdout = await new Promise<string>((resolve, reject) => {+ execFile(+ process.execPath,+ [process.argv[1], '--version'],+ { encoding: 'utf8', timeout: 30_000 },+ (error, output) => (error ? reject(error) : resolve(output)),+ );+ });+ if (stdout.trim() === installedVersion) {+ await runEntry(['connect', 'status']);+ return;+ }+ } catch (error) {+ log.debug(`Installed CLI report unavailable: ${(error as Error).message}`);+ }+ await printConnectStatus({ installedVersion });+}+export function registerUpdateCommand(program: Command) {program.command('update')@@ -181,6 +217,6 @@ export function registerUpdateCommand(program: Command) {return;}log.info(pc.green(`Successfully installed CLI ${latest}.`));- await printConnectStatus({ installedVersion: latest });+ await reportInstalledConnectStatus(latest);});}diff --git a/apps/cli/src/doctor/checks/device.test.ts b/apps/cli/src/doctor/checks/device.test.tsindex 472e2f000e4..6bf8a51c3a5 100644--- a/apps/cli/src/doctor/checks/device.test.ts+++ b/apps/cli/src/doctor/checks/device.test.ts@@ -2,8 +2,9 @@ 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 { cliVersion } from '../../pkg';import type * as ServiceStatusModule from '../../service/status';+import type { ConnectServiceStatus } from '../../service/status';import type * as SettingsModule from '../../settings';import type * as ProbesModule from '../probes';import { makeContext, runCheck } from '../testUtils';@@ -179,7 +180,7 @@ describe('device.daemon', () => {},];state.daemonStatus = {- cliVersion: '0.0.71',+ cliVersion,connectionStatus: 'connected',deviceId: 'dev_1',gatewayUrl: 'wss://gw',@@ -221,6 +222,7 @@ describe('device.daemon', () => {it('reports a healthy daemon', async () => {state.daemonPid = 42;state.daemonStatus = {+ cliVersion,connectionStatus: 'connected',deviceId: 'dev_1',gatewayUrl: 'wss://gw',@@ -234,6 +236,31 @@ describe('device.daemon', () => {expect(outcome.detail).toContain('dev_1');});+ it.each([+ ['0.0.1', 'running CLI 0.0.1'],+ [undefined, 'did not report its CLI version'],+ ])(+ 'flags a connected daemon still running code from before an update (%s)',+ async (running, detail) => {+ state.daemonPid = 42;+ state.daemonStatus = {+ cliVersion: running,+ connectionStatus: 'connected',+ deviceId: 'dev_1',+ gatewayUrl: 'wss://gw',+ pid: 42,+ startedAt: '',+ };++ const outcome = await runCheck(deviceChecks, 'device.daemon');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain(detail);+ expect(outcome.detail).toContain(`installed CLI is ${cliVersion}`);+ expect(outcome.fix).toContain('lh connect restart');+ },+ );+it('flags a daemon whose last known state was not connected', async () => {state.daemonPid = 42;state.daemonStatus = {diff --git a/apps/cli/src/doctor/checks/device.ts b/apps/cli/src/doctor/checks/device.tsindex fccd4cc6ad8..34117058f74 100644--- a/apps/cli/src/doctor/checks/device.ts+++ b/apps/cli/src/doctor/checks/device.ts@@ -4,6 +4,7 @@ import { CLI_PRIMARY_BIN } from '../../constants/identity';import { readConnectRuntimes } from '../../daemon/connectStatus';import { readStatus, removePid, removeStatus } from '../../daemon/manager';import { describeDeviceGateway, describeDeviceGatewayFailure } from '../../device/gatewayEndpoint';+import { cliVersion } from '../../pkg';import { resolveLocalDeviceId } from '../../utils/device';import { probeCredential, probeDeviceGateway, probeDevices } from '../probes';import { redactUrlCredentials, redactUrlsInMessage } from '../redact';@@ -43,6 +44,7 @@ const daemon: DoctorCheck = {gatewaySource: status?.gatewaySource,gatewayUrl: redactUrlCredentials(status?.gatewayUrl),pid,+ runningVersion: status?.cliVersion,service,unavailableScopes,};@@ -98,6 +100,17 @@ const daemon: DoctorCheck = {status: 'warn',};+ // Connected on old code is the state an update leaves until the connector restarts.+ if (status.cliVersion !== cliVersion)+ return {+ detail: status.cliVersion+ ? `${label} ${pid} is connected but running CLI ${status.cliVersion}; installed CLI is ${cliVersion}.`+ : `${label} ${pid} is connected but did not report its CLI version; installed CLI is ${cliVersion}.`,+ evidence,+ fix: `After active tasks finish, run: ${runtime.restartCommand}`,+ status: 'warn',+ };+const via = evidence.gatewayUrl? ` via ${evidence.gatewayUrl}${evidence.gatewaySource ? ` (${evidence.gatewaySource})` : ''}`: '';