🤯 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(device): update and restart CLI daemons from device settings (#20528)
AmAzing-6dcf34051163
diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 06dec262ca4..f9e9068ab8a 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -17,7 +17,7 @@"man"],"scripts": {- "build": "bun scripts/ensureWorkspaceLinks.ts && tsdown",+ "build": "bun scripts/ensureWorkspaceLinks.ts && tsdown && tsdown src/daemon/maintenanceWorker.ts --no-config --no-clean --format esm --target node22","cli:link": "bun link","cli:unlink": "bun unlink","dev": "LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts",diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex e8cbb16a351..33ce2263047 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -33,10 +33,12 @@ import {CLI_PRIMARY_BIN,} from '../constants/identity';import { OFFICIAL_GATEWAY_URL } from '../constants/urls';+import { CliMaintenance } from '../daemon/maintenance';import {appendLog,getLogPath,getRunningDaemonPid,+ isProcessAlive,readStatus,removePid,removeStatus,@@ -45,6 +47,7 @@ import {stopDaemon,writeStatus,} from '../daemon/manager';+import { listTasks } from '../daemon/taskRegistry';import { spawnHeteroAgentRun } from '../device/agentRun';import {mintWorkspaceConnectToken,@@ -72,7 +75,7 @@ import {saveSettings,} from '../settings';import { executeToolCall } from '../tools';-import { cleanupAllProcesses } from '../tools/shell';+import { cleanupAllProcesses, getActiveShellCount } from '../tools/shell';import { log, setVerbose } from '../utils/logger';import { sweepLocalTraces } from '../utils/traceMaintenance';@@ -446,7 +449,17 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {// mode-specific `enrollWorkspace` / `unenrollWorkspace` handlers are attached// further below once the workspace-share machinery is in scope — every bound// connection reads this object by reference, so late attachment is safe.+ const maintenance = new CliMaintenance({+ activeTasks: () =>+ getActiveShellCount() + listTasks().filter((task) => isProcessAlive(task.pid)).length,+ daemon:+ !!options.daemonChild && !options.serviceChild && process.env.LOBEHUB_CONNECT_SERVICE !== '1',+ restartArgs: buildDaemonArgs(options).slice(1),+ shutdown: () => shutdown(),+ });const deviceControlDeps: DeviceControlDeps = {+ checkCliUpdate: maintenance.check,+ getCliUpdateState: maintenance.getState,getLocalFilePreview: defaultGetLocalFilePreview,getProjectFileIndex: defaultGetProjectFileIndex,listHeterogeneousAgentModels: (params) =>@@ -454,6 +467,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {...params,env: { ...process.env, ...params.env },}),+ restartCli: maintenance.restart,searchProjectFiles: defaultSearchProjectFiles,};@@ -464,6 +478,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {getServerUrl: () => auth.serverUrl,info,isDaemonChild,+ maintenance,};// Request handlers (system info / tool calls / device RPCs / agent runs) —@@ -875,6 +890,7 @@ interface GatewayHandlerContext {getServerUrl: () => string;info: (msg: string) => void;isDaemonChild: boolean;+ maintenance: CliMaintenance;}/**@@ -888,7 +904,7 @@ function bindGatewayClientHandlers(ctx: GatewayHandlerContext,connectionWorkspaceId?: string,) {- const { deps, error, getServerUrl, info, isDaemonChild } = ctx;+ const { deps, error, getServerUrl, info, isDaemonChild, maintenance } = ctx;// Handle system info requestsclient.on('system_info_request', (request: SystemInfoRequestMessage) => {@@ -915,7 +931,14 @@ function bindGatewayClientHandlers(// round trip, so reporting this back is what separates a slow tool from// slow transport.const startedAt = performance.now();- const result = await executeToolCall(toolCall.apiName, toolCall.arguments, timeout);+ const result = await maintenance+ .run(() => executeToolCall(toolCall.apiName, toolCall.arguments, timeout))+ .catch((err: Error) => ({+ content: '',+ error: err.message,+ state: undefined,+ success: false,+ }));const executionTimeMs = Math.round(performance.now() - startedAt);if (isDaemonChild) {@@ -947,8 +970,11 @@ function bindGatewayClientHandlers(else info(`Received rpc_request: method=${method} (${requestId})`);try {- const data = await executeDeviceRpc(method, params, deps);+ const run = () => executeDeviceRpc(method, params, deps);+ const isMaintenance = ['getCliUpdateState', 'checkCliUpdate', 'restartCli'].includes(method);+ const data = await (isMaintenance ? run() : maintenance.run(run));client.sendRpcResponse({ requestId, result: { data, success: true } });+ if (method === 'restartCli') maintenance.afterResponse();} catch (err) {const message = err instanceof Error ? err.message : String(err);if (isDaemonChild) appendLog(`[RPC ERROR] ${method}: ${message} (${requestId})`);@@ -967,24 +993,26 @@ function bindGatewayClientHandlers(`Received agent_run_request: operationId=${request.operationId} type=${request.agentType}`,);try {- const ack = await spawnHeteroAgentRun(- {- agentType: request.agentType,- assistantMessageId: request.assistantMessageId,- args: request.args,- cwd: request.cwd,- imageList: request.imageList,- jwt: request.jwt,- operationId: request.operationId,- prompt: request.prompt,- resumeFallbackSystemContext: request.resumeFallbackSystemContext,- resumeSessionId: request.resumeSessionId,- serverUrl: getServerUrl(),- systemContext: request.systemContext,- topicId: request.topicId,- workspaceId: request.ingestWorkspaceId ?? request.workspaceId ?? connectionWorkspaceId,- },- { error, info },+ const ack = await maintenance.run(() =>+ spawnHeteroAgentRun(+ {+ agentType: request.agentType,+ assistantMessageId: request.assistantMessageId,+ args: request.args,+ cwd: request.cwd,+ imageList: request.imageList,+ jwt: request.jwt,+ operationId: request.operationId,+ prompt: request.prompt,+ resumeFallbackSystemContext: request.resumeFallbackSystemContext,+ resumeSessionId: request.resumeSessionId,+ serverUrl: getServerUrl(),+ systemContext: request.systemContext,+ topicId: request.topicId,+ workspaceId: request.ingestWorkspaceId ?? request.workspaceId ?? connectionWorkspaceId,+ },+ { error, info },+ ),);client.sendAgentRunAck({ operationId: request.operationId, ...ack });} catch (err) {diff --git a/apps/cli/src/daemon/maintenance.test.ts b/apps/cli/src/daemon/maintenance.test.tsnew file mode 100644index 00000000000..c2061bf2133--- /dev/null+++ b/apps/cli/src/daemon/maintenance.test.ts@@ -0,0 +1,133 @@+import type * as ChildProcessModule from 'node:child_process';+import { EventEmitter } from 'node:events';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { CliMaintenance } from './maintenance';++const { spawn, child } = vi.hoisted(() => {+ return {+ child: {+ value: undefined as unknown as EventEmitter & {+ connected: boolean;+ send: ReturnType<typeof vi.fn>;+ unref: ReturnType<typeof vi.fn>;+ },+ },+ spawn: vi.fn(),+ };+});+vi.mock('node:child_process', async (original) => ({+ ...(await original<typeof ChildProcessModule>()),+ spawn,+}));++let home: string;+let originalArgv: string[];+const id = '82f26ff2-0ddc-4ddf-b633-6dd5219a3b47';+beforeEach(async () => {+ home = await mkdtemp(path.join(os.tmpdir(), 'cli-maintenance-gate-'));+ vi.spyOn(os, 'homedir').mockReturnValue(home);+ await mkdir(path.join(home, 'dist'));+ await writeFile(path.join(home, 'dist', 'index.js'), '');+ await writeFile(path.join(home, 'dist', 'maintenanceWorker.mjs'), '');+ originalArgv = process.argv;+ process.argv = [process.execPath, path.join(home, 'dist', 'index.js')];+ child.value = Object.assign(new EventEmitter(), {+ connected: true,+ send: vi.fn(),+ unref: vi.fn(),+ });+ spawn.mockReturnValue(child.value);+});+afterEach(async () => {+ process.argv = originalArgv;+ vi.restoreAllMocks();+ vi.clearAllMocks();+ await rm(home, { force: true, recursive: true });+});+const create = (activeTasks = () => 0, daemon = true) =>+ new CliMaintenance({+ activeTasks,+ daemon,+ restartArgs: ['connect', '--workspace', 'workspace-a', '--public'],+ shutdown: vi.fn(),+ });++describe('CLI maintenance admission', () => {+ it('makes historical operations recoverable after a manual version change', async () => {+ const maintenance = create();+ const state = await maintenance.restart({ requestId: id, update: false });+ const operation = { ...state.operation!, targetVersion: '0.0.0' };+ await writeFile(+ path.join(home, '.lobehub/cli-maintenance/state.json'),+ JSON.stringify(operation),+ );++ // An update in the originating process is still in flight, not a failure.+ expect((await maintenance.getState()).operation?.stage).toBe('restarting');+ const reconnected = await create().getState();+ expect(reconnected.operation).toMatchObject({+ id,+ stage: 'failed',+ error: expect.stringContaining('different CLI version'),+ });+ expect(reconnected.supported).toBe(true);+ });++ it('rejects background tasks and releases the gate after refusal', async () => {+ const maintenance = create(() => 2);+ await expect(maintenance.restart({ requestId: id, update: false })).rejects.toThrow(+ 'active tasks',+ );+ expect(spawn).not.toHaveBeenCalled();+ expect(await maintenance.run(async () => 'available')).toBe('available');+ });++ it('counts an in-flight request and rejects a restart before it finishes', async () => {+ const maintenance = create();+ let finish!: () => void;+ const running = maintenance.run(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );+ await expect(maintenance.restart({ requestId: id, update: false })).rejects.toThrow(+ 'active tasks',+ );+ finish();+ await running;+ expect((await maintenance.getState()).activeTasks).toBe(0);+ });++ it('starts only after acknowledgement, blocks new work, and deduplicates across processes', async () => {+ const maintenance = create();+ const state = await maintenance.restart({ requestId: id, update: false });+ expect(state.operation?.id).toBe(id);+ expect(child.value.send).not.toHaveBeenCalled();+ maintenance.afterResponse();+ maintenance.afterResponse();+ expect(child.value.send).toHaveBeenCalledTimes(1);+ await expect(maintenance.run(async () => true)).rejects.toThrow('updating or restarting');+ await maintenance.restart({ requestId: id, update: false });+ const restarted = create();+ expect((await restarted.restart({ requestId: id, update: false })).operation?.id).toBe(id);+ expect(spawn).toHaveBeenCalledTimes(1);+ const config = JSON.parse(+ await readFile(path.join(home, '.lobehub/cli-maintenance', `${id}.config.json`), 'utf8'),+ );+ expect(config.restartArgs).toEqual(['connect', '--workspace', 'workspace-a', '--public']);+ });++ it('does not support foreground connections or unchecked updates', async () => {+ expect((await create(undefined, false).getState()).supported).toBe(false);+ await expect(create().restart({ requestId: id, update: true })).rejects.toThrow(+ 'Check for updates',+ );+ expect(spawn).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/daemon/maintenance.ts b/apps/cli/src/daemon/maintenance.tsnew file mode 100644index 00000000000..af8f9e15d60--- /dev/null+++ b/apps/cli/src/daemon/maintenance.ts@@ -0,0 +1,241 @@+import { type ChildProcess, spawn } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { copyFile, mkdir, open, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import type {+ DeviceCliRestartParams,+ DeviceCliUpdateOperation,+ DeviceCliUpdateState,+} from '@lobechat/types';+import semver from 'semver';++import {+ buildInstallCommand,+ detectPackageManager,+ fetchLatestVersion,+ isNewerVersion,+} from '../commands/update';+import { CLI_CONFIG_DIR_NAME } from '../constants/identity';+import { cliPackageName, cliVersion } from '../pkg';+import { type MaintenanceConfig, writeMaintenanceState } from './maintenanceWorker';+import { getLogPath } from './manager';++const MAINTENANCE_MESSAGE = 'The CLI is updating or restarting. Retry after it reconnects.';++/** One gate shared by every workspace connection owned by this process. */+export class CliMaintenance {+ private readonly instanceId = randomUUID();+ private readonly directory = path.join(os.homedir(), CLI_CONFIG_DIR_NAME, 'cli-maintenance');+ private readonly statePath = path.join(this.directory, 'state.json');+ private activeRequests = 0;+ private locked = false;+ private child?: ChildProcess;+ private acknowledged = false;+ private latestVersion?: string;++ constructor(+ private readonly options: {+ activeTasks: () => number;+ daemon: boolean;+ restartArgs: string[];+ shutdown: () => Promise<void>;+ },+ ) {}++ async run<T>(action: () => Promise<T>): Promise<T> {+ if (this.locked) throw new Error(MAINTENANCE_MESSAGE);+ this.activeRequests++;+ try {+ return await action();+ } finally {+ this.activeRequests--;+ }+ }++ private async readOperation(+ file = this.statePath,+ ): Promise<DeviceCliUpdateOperation | undefined> {+ try {+ return JSON.parse(await readFile(file, 'utf8')) as DeviceCliUpdateOperation;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;+ throw error;+ }+ }++ private async workerPath() {+ const entry = await realpath(process.argv[1]);+ const worker = path.join(path.dirname(entry), 'maintenanceWorker.mjs');+ await stat(worker);+ return worker;+ }++ getState = async (): Promise<DeviceCliUpdateState> => {+ let supported = this.options.daemon && process.platform !== 'win32';+ try {+ if (supported) await this.workerPath();+ } catch {+ supported = false;+ }+ let operation = await this.readOperation();+ // A replacement process on a different version cannot complete this receipt.+ // Surface failure so a historical request does not permanently lock the UI.+ if (+ operation &&+ operation.stage !== 'failed' &&+ operation.fromInstanceId !== this.instanceId &&+ operation.targetVersion !== cliVersion+ ) {+ operation = {+ ...operation,+ error:+ 'The device reconnected on a different CLI version. Check for updates before retrying.',+ stage: 'failed',+ };+ }+ return {+ activeTasks: this.activeRequests + this.options.activeTasks(),+ currentVersion: cliVersion,+ instanceId: this.instanceId,+ latestVersion: this.latestVersion,+ operation,+ supported,+ unsupportedReason: supported+ ? undefined+ : 'Use an installed CLI with lh connect --daemon on macOS or Linux. Foreground and system-service connections must be maintained on the device.',+ };+ };++ check = async (): Promise<DeviceCliUpdateState> => {+ if (this.locked) return this.getState();+ const latest = await fetchLatestVersion(cliPackageName, 'latest');+ if (!semver.valid(latest))+ throw new Error('The package registry returned an invalid CLI version.');+ if (this.locked) return this.getState();+ this.latestVersion = isNewerVersion(latest, cliVersion) ? latest : undefined;+ await rm(this.statePath, { force: true });+ return this.getState();+ };++ restart = async ({+ requestId,+ update,+ }: DeviceCliRestartParams): Promise<DeviceCliUpdateState> => {+ // Also validate at the device boundary; requests must never choose a filesystem path.+ if (+ !/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i.test(requestId) ||+ typeof update !== 'boolean'+ ) {+ throw new Error('Invalid CLI maintenance request');+ }+ if (this.locked) return this.getState();+ this.locked = true;+ const receipt = path.join(this.directory, `${requestId}.json`);+ try {+ const previous = await this.readOperation(receipt);+ if (previous) {+ this.locked = false;+ return { ...(await this.getState()), operation: previous };+ }+ const state = await this.getState();+ if (!state.supported) throw new Error(state.unsupportedReason);+ if (state.activeTasks > 0)+ throw new Error('This device has active tasks. Wait for them to finish before restarting.');+ if (update && !this.latestVersion)+ throw new Error('Check for updates before updating this CLI.');+ const operation: DeviceCliUpdateOperation = {+ fromInstanceId: this.instanceId,+ id: requestId,+ kind: update ? 'update' : 'restart',+ stage: update ? 'updating' : 'restarting',+ targetVersion: update ? this.latestVersion! : cliVersion,+ };+ await mkdir(this.directory, { mode: 0o700, recursive: true });+ const worker = path.join(this.directory, `${requestId}.mjs`);+ const configPath = path.join(this.directory, `${requestId}.config.json`);+ await copyFile(await this.workerPath(), worker);+ const config: MaintenanceConfig = {+ entry: process.argv[1],+ executable: process.execPath,+ install: update+ ? buildInstallCommand(+ detectPackageManager(),+ `${cliPackageName}@${operation.targetVersion}`,+ )+ : undefined,+ operation,+ parentPid: process.pid,+ receiptPath: receipt,+ restartArgs: this.options.restartArgs,+ statePath: this.statePath,+ };+ await writeFile(configPath, JSON.stringify(config), { mode: 0o600 });+ await writeFile(receipt, JSON.stringify(operation), { flag: 'wx', mode: 0o600 });+ await writeMaintenanceState(this.statePath, operation);+ const failed = async (message: string) => {+ const latest = await this.readOperation();+ if (latest?.id === requestId && latest.stage !== 'failed') {+ const failure: DeviceCliUpdateOperation = {+ ...operation,+ error: message,+ stage: 'failed',+ };+ await writeMaintenanceState(receipt, failure);+ await writeMaintenanceState(this.statePath, failure);+ }+ await rm(configPath, { force: true });+ await rm(worker, { force: true });+ this.locked = false;+ };+ const log = await open(getLogPath(), 'a', 0o600);+ try {+ this.child = spawn(process.execPath, [worker, '--maintenance-config', configPath], {+ detached: true,+ stdio: ['ignore', log.fd, log.fd, 'ipc'],+ });+ // Register before yielding: spawn errors can arrive while closing our log FD.+ this.child.once('error', (error) => void failed(error.message).catch(console.error));+ this.child.once(+ 'exit',+ () =>+ void failed(+ 'CLI maintenance stopped before the connection restarted. See lh connect logs.',+ ).catch(console.error),+ );+ } finally {+ await log.close();+ }+ this.acknowledged = false;+ const child = this.child;+ child.on('message', (message: { type: string }) => {+ if (message.type === 'ready-to-restart') {+ void this.options.shutdown().catch((error) => console.error('CLI restart failed', error));+ }+ });+ child.unref();+ return this.getState();+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ try {+ const saved = await this.readOperation(receipt);+ if (saved) {+ const failed: DeviceCliUpdateOperation = { ...saved, error: message, stage: 'failed' };+ await writeMaintenanceState(receipt, failed);+ await writeMaintenanceState(this.statePath, failed);+ }+ } finally {+ this.locked = false;+ }+ throw new Error(`CLI_MAINTENANCE_REJECTED: ${message}`, { cause: error });+ }+ };++ /** Called only after sending the restart RPC acknowledgement. */+ afterResponse() {+ if (!this.child?.connected || this.acknowledged) return;+ this.acknowledged = true;+ this.child.send({ type: 'start' });+ }+}diff --git a/apps/cli/src/daemon/maintenanceWorker.test.ts b/apps/cli/src/daemon/maintenanceWorker.test.tsnew file mode 100644index 00000000000..855acabb4fb--- /dev/null+++ b/apps/cli/src/daemon/maintenanceWorker.test.ts@@ -0,0 +1,100 @@+import { spawn } from 'node:child_process';+import { once } from 'node:events';+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { type MaintenanceConfig, runMaintenanceWorker } from './maintenanceWorker';++let directory: string;+let config: MaintenanceConfig;+beforeEach(async () => {+ directory = await mkdtemp(path.join(os.tmpdir(), 'cli-maintenance-'));+ config = {+ entry: path.join(directory, 'entry.mjs'),+ executable: process.execPath,+ operation: {+ fromInstanceId: 'old',+ id: 'one',+ kind: 'restart',+ stage: 'restarting',+ targetVersion: '1.2.3',+ },+ parentPid: process.pid,+ receiptPath: path.join(directory, 'receipt.json'),+ restartArgs: [+ 'connect',+ '--workspace',+ 'workspace-42',+ '--public',+ '--gateway',+ 'wss://gateway.test',+ '--device-id',+ 'custom device',+ ],+ statePath: path.join(directory, 'state.json'),+ };+ await writeFile(+ config.entry,+ `import { writeFileSync } from 'node:fs';+if (process.argv[2] === '--version') console.log('1.2.3');+else writeFileSync(${JSON.stringify(path.join(directory, 'args.json'))}, JSON.stringify(process.argv.slice(2)));`,+ );+});+afterEach(async () => {+ vi.restoreAllMocks();+ await rm(directory, { force: true, recursive: true });+});++describe('independent CLI maintenance worker', () => {+ it('keeps the old connection alive when installation fails', async () => {+ config.install = { command: process.execPath, args: ['-e', 'process.exit(7)'] };+ const ready = vi.fn();+ await expect(runMaintenanceWorker(config, ready)).rejects.toThrow('failed (7)');+ expect(ready).not.toHaveBeenCalled();+ expect(JSON.parse(await readFile(config.statePath, 'utf8'))).toMatchObject({+ stage: 'failed',+ id: 'one',+ });+ expect(await readFile(config.receiptPath, 'utf8')).toBe(+ await readFile(config.statePath, 'utf8'),+ );+ });++ it('does not stop the daemon if the installed entry reports the wrong version', async () => {+ config.operation.targetVersion = '1.2.4';+ const ready = vi.fn();+ await expect(runMaintenanceWorker(config, ready)).rejects.toThrow('did not match');+ expect(ready).not.toHaveBeenCalled();+ await expect(readFile(path.join(directory, 'args.json'))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ });++ it('waits for the old process to exit and preserves workspace, public and custom connection args', async () => {+ const old = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)']);+ await once(old, 'spawn');+ config.parentPid = old.pid!;+ const exited = once(old, 'exit');+ try {+ await runMaintenanceWorker(config, () => old.kill('SIGTERM'));+ await exited;+ expect(JSON.parse(await readFile(path.join(directory, 'args.json'), 'utf8'))).toEqual([+ 'connect',+ '--workspace',+ 'workspace-42',+ '--public',+ '--gateway',+ 'wss://gateway.test',+ '--device-id',+ 'custom device',+ '--daemon',+ ]);+ expect(JSON.parse(await readFile(config.statePath, 'utf8')).stage).toBe('restarting');+ } finally {+ if (old.exitCode === null && old.signalCode === null) old.kill('SIGTERM');+ }+ });+});diff --git a/apps/cli/src/daemon/maintenanceWorker.ts b/apps/cli/src/daemon/maintenanceWorker.tsnew file mode 100644index 00000000000..888b1434e63--- /dev/null+++ b/apps/cli/src/daemon/maintenanceWorker.ts@@ -0,0 +1,120 @@+import { execFile, spawn } from 'node:child_process';+import { readFile, rename, rm, writeFile } from 'node:fs/promises';+import { setTimeout as delay } from 'node:timers/promises';+import { promisify } from 'node:util';++import type { DeviceCliUpdateOperation } from '@lobechat/types';++export interface MaintenanceConfig {+ entry: string;+ executable: string;+ install?: { args: string[]; command: string };+ operation: DeviceCliUpdateOperation;+ parentPid: number;+ receiptPath: string;+ restartArgs: string[];+ statePath: string;+}++/** Atomic replacement lets the connected daemon read progress during installation. */+export async function writeMaintenanceState(file: string, operation: DeviceCliUpdateOperation) {+ const temporary = `${file}.${process.pid}.tmp`;+ await writeFile(temporary, JSON.stringify(operation), { mode: 0o600 });+ await rename(temporary, file);+}++async function run(command: string, args: string[], timeout: number) {+ await new Promise<void>((resolve, reject) => {+ const child = spawn(command, args, { stdio: 'inherit', timeout });+ child.once('error', reject);+ child.once('close', (code, signal) => {+ if (code === 0) resolve();+ else+ reject(+ new Error(`CLI maintenance command failed (${signal ?? code}). See lh connect logs.`),+ );+ });+ });+}++/** Runs from a private copy outside the package being replaced. No runtime package imports. */+export async function runMaintenanceWorker(config: MaintenanceConfig, ready: () => void) {+ const { entry, executable, operation, statePath } = config;+ const persist = async () => {+ await writeMaintenanceState(config.receiptPath, operation);+ await writeMaintenanceState(statePath, operation);+ };+ try {+ if (config.install) await run(config.install.command, config.install.args, 180_000);++ // Do not stop a working connection unless the new executable can actually start.+ const { stdout } = await promisify(execFile)(executable, [entry, '--version'], {+ timeout: 30_000,+ });+ if (stdout.trim() !== operation.targetVersion) {+ throw new Error(+ 'Installed CLI version did not match the requested version. The existing connection was kept.',+ );+ }+ operation.stage = 'restarting';+ await persist();+ ready();++ const deadline = Date.now() + 30_000;+ while (true) {+ try {+ process.kill(config.parentPid, 0);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') break;+ throw error;+ }+ if (Date.now() >= deadline)+ throw new Error('The previous CLI did not stop. No second daemon was started.');+ await delay(100);+ }+ // The normal daemon launcher waits for startup preflight and writes its own PID.+ // Preserve argv as an array: paths and workspace flags never pass through a shell.+ await run(executable, [entry, ...config.restartArgs, '--daemon'], 45_000);+ } catch (error) {+ operation.stage = 'failed';+ operation.error = error instanceof Error ? error.message : String(error);+ await persist();+ throw error;+ }+}++if (process.argv[2] === '--maintenance-config') {+ const configPath = process.argv[3];+ // The config can carry an explicit connect token. Remove it immediately after reading.+ const config = JSON.parse(await readFile(configPath, 'utf8')) as MaintenanceConfig;+ await rm(configPath);+ let started = false;+ const timeout = setTimeout(() => process.disconnect?.(), 15_000);+ process.once('message', () => {+ started = true;+ clearTimeout(timeout);+ void runMaintenanceWorker(config, () => {+ if (!process.connected)+ throw new Error(+ 'The original daemon stopped during installation. Start the connection manually.',+ );+ process.send?.({ type: 'ready-to-restart' });+ })+ .catch((error) => {+ console.error(error);+ process.exitCode = 1;+ })+ .finally(async () => {+ if (process.connected) process.disconnect();+ await rm(process.argv[1], { force: true });+ });+ });+ // A parent disappearing before it acknowledges the request must not leave an idle helper.+ process.once('disconnect', () => {+ clearTimeout(timeout);+ if (!started) {+ process.exitCode = 1;+ void rm(process.argv[1], { force: true }).catch(console.error);+ }+ });+}diff --git a/apps/cli/src/tools/shell.ts b/apps/cli/src/tools/shell.tsindex 50f58e908f2..a0cab3bd350 100644--- a/apps/cli/src/tools/shell.ts+++ b/apps/cli/src/tools/shell.ts@@ -10,6 +10,8 @@ import { log } from '../utils/logger';const processManager = new ShellProcessManager();+export const getActiveShellCount = () => processManager.activeCount;+export function cleanupAllProcesses() {processManager.cleanupAll();}diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 00c0f639c19..839b19affbd 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -412,6 +412,23 @@"devices.capabilities.tools.title": "Call system tools","devices.channel.connected": "Connected {{time}}","devices.channel.unknown": "Unknown client",+ "devices.cliUpdate.ambiguous": "The request may have been accepted. Refresh status or retry the same request; do not start another operation.",+ "devices.cliUpdate.available": "v{{version}} available",+ "devices.cliUpdate.bootstrap": "Update the CLI manually and reconnect with a standalone daemon to enable remote maintenance.",+ "devices.cliUpdate.confirmDesc": "The CLI will briefly go offline. Wait for active tasks to finish before continuing.",+ "devices.cliUpdate.failed": "CLI maintenance failed. Review the error before trying again.",+ "devices.cliUpdate.loading": "Reading CLI maintenance status…",+ "devices.cliUpdate.pending": "Waiting for a new CLI process on the expected version…",+ "devices.cliUpdate.requestFailed": "The CLI request failed. Refresh status before trying again.",+ "devices.cliUpdate.restart": "Restart CLI",+ "devices.cliUpdate.retryCommand": "Retry same request",+ "devices.cliUpdate.retryRead": "Refresh status",+ "devices.cliUpdate.showDetails": "Show details",+ "devices.cliUpdate.success": "CLI restarted on the expected version.",+ "devices.cliUpdate.timedOut": "Restart could not be confirmed within five minutes. Read status before retrying.",+ "devices.cliUpdate.unavailable": "Cannot reach the CLI. Retry reading its status.",+ "devices.cliUpdate.unsupported": "Remote CLI maintenance is not supported.",+ "devices.cliUpdate.update": "Update and restart","devices.connectWizard.button": "Connect Device","devices.connectWizard.cli.connectDesc": "Start the background daemon to keep the device online and listening for remote operations.","devices.connectWizard.cli.connectTitle": "Start the daemon",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex e5e3fa0809e..c0225e2cae4 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -412,6 +412,23 @@"devices.capabilities.tools.title": "调用系统工具","devices.channel.connected": "已连接 {{time}}","devices.channel.unknown": "未知客户端",+ "devices.cliUpdate.ambiguous": "请求可能已被接受。请刷新状态或重试同一请求,不要发起新的操作。",+ "devices.cliUpdate.available": "v{{version}} 可供更新",+ "devices.cliUpdate.bootstrap": "请手动更新 CLI,并通过独立守护进程重新连接,以启用远程维护。",+ "devices.cliUpdate.confirmDesc": "CLI 将短暂离线。请等待正在运行的任务结束后再继续。",+ "devices.cliUpdate.failed": "CLI 维护失败,请查看错误后再重试。",+ "devices.cliUpdate.loading": "正在读取 CLI 维护状态…",+ "devices.cliUpdate.pending": "正在等待运行预期版本的新 CLI 进程…",+ "devices.cliUpdate.requestFailed": "CLI 请求失败。请刷新状态后重试。",+ "devices.cliUpdate.restart": "重启 CLI",+ "devices.cliUpdate.retryCommand": "重试同一请求",+ "devices.cliUpdate.retryRead": "刷新状态",+ "devices.cliUpdate.showDetails": "显示详情",+ "devices.cliUpdate.success": "CLI 已重启并运行预期版本。",+ "devices.cliUpdate.timedOut": "五分钟内未能确认重启,请先读取状态再重试。",+ "devices.cliUpdate.unavailable": "无法连接 CLI,请重试读取状态。",+ "devices.cliUpdate.unsupported": "此 CLI 不支持远程维护。",+ "devices.cliUpdate.update": "更新并重启","devices.connectWizard.button": "连接设备","devices.connectWizard.cli.connectDesc": "启动后台守护进程,保持设备在线并等待远程操作。","devices.connectWizard.cli.connectTitle": "启动守护进程",diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.tsindex bb9a23b9406..31c1b019708 100644--- a/packages/device-control/src/__tests__/dispatch.test.ts+++ b/packages/device-control/src/__tests__/dispatch.test.ts@@ -6,6 +6,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';import {APP_UPDATE_UNSUPPORTED_MESSAGE,+ CLI_UPDATE_UNSUPPORTED_MESSAGE,DEVICE_RPC_METHODS,executeDeviceRpc,TRASH_UNSUPPORTED_MESSAGE,@@ -59,6 +60,36 @@ const makeDeps = (): DeviceControlDeps => ({});describe('executeDeviceRpc', () => {+ it.each(['getCliUpdateState', 'checkCliUpdate', 'restartCli'])(+ 'rejects missing CLI handler %s with a stable reason',+ async (method) => {+ await expect(executeDeviceRpc(method, {}, makeDeps())).rejects.toThrow(+ CLI_UPDATE_UNSUPPORTED_MESSAGE,+ );+ expect(DEVICE_RPC_METHODS).toContain(method);+ },+ );++ it('dispatches CLI maintenance and preserves the restart idempotency key', async () => {+ const state = {+ activeTasks: 0,+ currentVersion: '1.0.0',+ instanceId: 'instance',+ supported: true,+ };+ const restart = { requestId: '89d177cf-52e5-4d55-b71c-13deef4ea366', update: true };+ const deps = {+ ...makeDeps(),+ checkCliUpdate: vi.fn(async () => state),+ getCliUpdateState: vi.fn(async () => state),+ restartCli: vi.fn(async () => state),+ };+ for (const method of ['getCliUpdateState', 'checkCliUpdate', 'restartCli']) {+ await expect(executeDeviceRpc(method, restart, deps)).resolves.toEqual(state);+ }+ expect(deps.restartCli).toHaveBeenCalledWith(restart);+ });+it('throws on an unknown method', async () => {await expect(executeDeviceRpc('nope', {}, makeDeps())).rejects.toThrow('Unknown device RPC method: nope',diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex b25c8bd89f3..41e5726a588 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -36,6 +36,7 @@ import type {CreateDirectoryParams,CreateFileParams,} from '@lobechat/local-file-shell/types';+import type { DeviceCliRestartParams } from '@lobechat/types';import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';import { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';@@ -121,6 +122,9 @@ export const DEVICE_RPC_METHODS = ['getAppUpdateState','checkAppUpdate','installAppUpdate',+ 'getCliUpdateState',+ 'checkCliUpdate',+ 'restartCli',] as const;export type DeviceRpcMethod = (typeof DEVICE_RPC_METHODS)[number];@@ -128,6 +132,9 @@ export type DeviceRpcMethod = (typeof DEVICE_RPC_METHODS)[number];/** Why a client without the app-update handlers rejects those RPCs. */export const APP_UPDATE_UNSUPPORTED_MESSAGE = 'This device client does not support remote updates';+export const CLI_UPDATE_UNSUPPORTED_MESSAGE =+ 'This device client does not support remote CLI updates';+/** Why a client without a recoverable trash (the CLI daemon) rejects `trashLocalFiles`. */export const TRASH_UNSUPPORTED_MESSAGE = 'This device does not support moving files to the trash';@@ -432,6 +439,21 @@ export const executeDeviceRpc = async (return deps.installAppUpdate();}+ case 'getCliUpdateState': {+ if (!deps.getCliUpdateState) throw new Error(CLI_UPDATE_UNSUPPORTED_MESSAGE);+ return deps.getCliUpdateState();+ }++ case 'checkCliUpdate': {+ if (!deps.checkCliUpdate) throw new Error(CLI_UPDATE_UNSUPPORTED_MESSAGE);+ return deps.checkCliUpdate();+ }++ case 'restartCli': {+ if (!deps.restartCli) throw new Error(CLI_UPDATE_UNSUPPORTED_MESSAGE);+ return deps.restartCli(params as DeviceCliRestartParams);+ }+default: {throw new Error(`Unknown device RPC method: ${method}`);}diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.tsindex 08c9871bbc2..03207321c47 100644--- a/packages/device-control/src/index.ts+++ b/packages/device-control/src/index.ts@@ -1,6 +1,7 @@export { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';export {APP_UPDATE_UNSUPPORTED_MESSAGE,+ CLI_UPDATE_UNSUPPORTED_MESSAGE,DEVICE_RPC_METHODS,type DeviceRpcMethod,executeDeviceRpc,diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.tsindex d17c22fdd4e..6d0bce84a1e 100644--- a/packages/device-control/src/types.ts+++ b/packages/device-control/src/types.ts@@ -6,6 +6,8 @@* desktop wiring can pass its own IPC-typed implementations directly.*/+import type { DeviceCliRestartParams, DeviceCliUpdateState } from '@lobechat/types';+// ─── Workspace scan ───export type ProjectSkillScope = 'device' | 'project';@@ -302,6 +304,7 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps* handlers and the dispatcher fails the RPC with a stable reason.*/checkAppUpdate?: () => Promise<AppUpdateState>;+ checkCliUpdate?: () => Promise<DeviceCliUpdateState>;/** Copy a publish asset (possibly outside the workspace) to a path inside the workspace. */copyAssetForPublish?: (params: CopyAssetForPublishParams) => Promise<CopyAssetForPublishResult>;/**@@ -316,6 +319,7 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDepsenrollWorkspace?: (params: EnrollWorkspaceParams) => Promise<EnrollWorkspaceResult>;/** Where this client's app update stands: current version, stage, progress. */getAppUpdateState?: () => Promise<AppUpdateState>;+ getCliUpdateState?: () => Promise<DeviceCliUpdateState>;/** Read a local file preview (host-gated on desktop; disk read on CLI). */getLocalFilePreview: (params: LocalFilePreviewUrlParams) => Promise<LocalFilePreviewResult>;/** Build the project file index. */@@ -333,6 +337,7 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDepsreadExternalAssetForPublish?: (params: ExternalAssetForPublishParams,) => Promise<ExternalAssetForPublishResult>;+ restartCli?: (params: DeviceCliRestartParams) => Promise<DeviceCliUpdateState>;/** Search project files without shipping the whole index to the caller. */searchProjectFiles: (params: ProjectFileSearchParams) => Promise<ProjectFileSearchResult>;/**diff --git a/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts b/packages/local-file-shell/src/shell/__tests__/process-manager.test.tsindex aa4d489f469..0767ae87eb6 100644--- a/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts+++ b/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts@@ -72,6 +72,19 @@ describe('ShellProcessManager', () => {fs.rmSync(tmpDir, { force: true, recursive: true });});+ it('counts running background commands until exit or spawn failure', () => {+ const child = createMockProcess();+ const shell = createShellProcess(manager, 'background', child);+ manager.register('background', shell);+ expect(manager.activeCount).toBe(1);+ Object.defineProperty(child, 'exitCode', { value: 0 });+ expect(manager.activeCount).toBe(0);+ const failed = createShellProcess(manager, 'failed', createMockProcess());+ failed.spawnError = new Error('spawn failed');+ manager.register('failed', failed);+ expect(manager.activeCount).toBe(0);+ });+describe('getOutput', () => {it('should return error for non-existent shell_id', async () => {const result = await manager.getOutput({ shell_id: 'non-existent' });diff --git a/packages/local-file-shell/src/shell/process-manager.ts b/packages/local-file-shell/src/shell/process-manager.tsindex 4c47e427c9a..15fd0f5a042 100644--- a/packages/local-file-shell/src/shell/process-manager.ts+++ b/packages/local-file-shell/src/shell/process-manager.ts@@ -111,6 +111,18 @@ export class ShellProcessManager {private processes = new Map<string, ShellProcess>();+ /** Includes commands whose observation window ended but whose process is still running. */+ get activeCount(): number {+ return [...this.processes.values()].filter(+ (entry) =>+ entry.process.exitCode === null &&+ entry.exitCode === null &&+ !entry.process.signalCode &&+ !entry.spawnError &&+ entry.closedAt === undefined,+ ).length;+ }+constructor(outputRoot?: string, backend: ShellBackend = new ChildProcessBackend()) {this.backend = backend;const date = new Date();diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 2f2173eb2d3..0a4f9d4d3ee 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1,4 +1,25 @@export default {+ 'devices.cliUpdate.restart': 'Restart CLI',+ 'devices.cliUpdate.update': 'Update and restart',+ 'devices.cliUpdate.confirmDesc':+ 'The CLI will briefly go offline. Wait for active tasks to finish before continuing.',+ 'devices.cliUpdate.bootstrap':+ 'Update the CLI manually and reconnect with a standalone daemon to enable remote maintenance.',+ 'devices.cliUpdate.unsupported': 'Remote CLI maintenance is not supported.',+ 'devices.cliUpdate.loading': 'Reading CLI maintenance status…',+ 'devices.cliUpdate.unavailable': 'Cannot reach the CLI. Retry reading its status.',+ 'devices.cliUpdate.pending': 'Waiting for a new CLI process on the expected version…',+ 'devices.cliUpdate.success': 'CLI restarted on the expected version.',+ 'devices.cliUpdate.failed': 'CLI maintenance failed. Review the error before trying again.',+ 'devices.cliUpdate.timedOut':+ 'Restart could not be confirmed within five minutes. Read status before retrying.',+ 'devices.cliUpdate.available': 'v{{version}} available',+ 'devices.cliUpdate.retryRead': 'Refresh status',+ 'devices.cliUpdate.requestFailed': 'The CLI request failed. Refresh status before trying again.',+ 'devices.cliUpdate.showDetails': 'Show details',+ 'devices.cliUpdate.retryCommand': 'Retry same request',+ 'devices.cliUpdate.ambiguous':+ 'The request may have been accepted. Refresh status or retry the same request; do not start another operation.','devices.keepAwake.desc':'Prevent automatic sleep while this computer is connected as a device, so it stays reachable. The display can still turn off; closing a laptop lid without an external display still puts it to sleep.','devices.keepAwake.title': 'Keep Awake While Connected',diff --git a/src/features/DeviceManager/CliUpdate/deriveCliUpdateView.test.ts b/src/features/DeviceManager/CliUpdate/deriveCliUpdateView.test.tsnew file mode 100644index 00000000000..d4260cb62eb--- /dev/null+++ b/src/features/DeviceManager/CliUpdate/deriveCliUpdateView.test.ts@@ -0,0 +1,66 @@+import type {+ DeviceCliUpdateOperation,+ DeviceCliUpdateState,+ DeviceCliUpdateStateResult,+} from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { deriveCliUpdateView } from './deriveCliUpdateView';++const operation: DeviceCliUpdateOperation = {+ fromInstanceId: 'old',+ id: 'request',+ kind: 'update',+ stage: 'restarting',+ targetVersion: '2.0',+};+const ok = (state: Partial<DeviceCliUpdateState> = {}): DeviceCliUpdateStateResult => ({+ status: 'ok',+ state: { activeTasks: 0, currentVersion: '1.0', instanceId: 'old', supported: true, ...state },+});++describe('CLI maintenance completion', () => {+ it('never treats an acknowledgement or reconnect of the same process as success', () => {+ expect(deriveCliUpdateView(ok({ operation }), operation)).toBe('pending');+ expect(deriveCliUpdateView(ok({ currentVersion: '2.0' }), operation)).toBe('pending');+ });+ it('requires both a new process and the exact target version', () => {+ expect(deriveCliUpdateView(ok({ instanceId: 'new' }), operation)).toBe('pending');+ expect(deriveCliUpdateView(ok({ instanceId: 'new', currentVersion: '2.0' }), operation)).toBe(+ 'success',+ );+ });+ it('confirms standalone restart only with a changed process', () => {+ const restart = { ...operation, kind: 'restart' as const, targetVersion: '1.0' };+ expect(deriveCliUpdateView(ok(), restart)).toBe('pending');+ expect(deriveCliUpdateView(ok({ instanceId: 'new' }), restart)).toBe('success');+ });+ it('keeps offline maintenance pending until its bounded deadline', () => {+ const offline: DeviceCliUpdateStateResult = { status: 'unavailable', message: 'offline' };+ expect(deriveCliUpdateView(offline, operation)).toBe('pending');+ expect(deriveCliUpdateView(offline, operation, true)).toBe('timedOut');+ expect(deriveCliUpdateView(ok({ instanceId: 'new' }), operation, true)).toBe('timedOut');+ });+ it('shows failed operations instead of success even if identity matches', () => {+ expect(+ deriveCliUpdateView(+ ok({+ instanceId: 'new',+ currentVersion: '2.0',+ operation: { ...operation, stage: 'failed', error: 'install failed' },+ }),+ operation,+ ),+ ).toBe('failed');+ });+ it('supports observation of maintenance started elsewhere', () => {+ expect(deriveCliUpdateView(ok({ operation }))).toBe('pending');+ });+ it('distinguishes old clients, unsupported installs, and unavailable reads', () => {+ expect(deriveCliUpdateView({ status: 'unsupported', message: 'old' })).toBe('unsupported');+ expect(deriveCliUpdateView(ok({ supported: false, unsupportedReason: 'dev build' }))).toBe(+ 'unsupported',+ );+ expect(deriveCliUpdateView({ status: 'unavailable', message: 'offline' })).toBe('unavailable');+ });+});diff --git a/src/features/DeviceManager/CliUpdate/deriveCliUpdateView.ts b/src/features/DeviceManager/CliUpdate/deriveCliUpdateView.tsnew file mode 100644index 00000000000..7972e502160--- /dev/null+++ b/src/features/DeviceManager/CliUpdate/deriveCliUpdateView.ts@@ -0,0 +1,35 @@+import type { DeviceCliUpdateOperation, DeviceCliUpdateStateResult } from '@lobechat/types';++type CliUpdateView =+ | 'failed'+ | 'loading'+ | 'pending'+ | 'ready'+ | 'success'+ | 'timedOut'+ | 'unavailable'+ | 'unsupported';++export const deriveCliUpdateView = (+ result: DeviceCliUpdateStateResult | undefined,+ operation?: DeviceCliUpdateOperation,+ timedOut = false,+): CliUpdateView => {+ const state = result?.status === 'ok' ? result.state : undefined;+ const pending = operation ?? state?.operation;+ if (pending) {+ if (state?.operation?.id === pending.id && state.operation.stage === 'failed') return 'failed';+ if (pending.stage === 'failed') return 'failed';+ if (+ state &&+ state.instanceId !== pending.fromInstanceId &&+ state.currentVersion === pending.targetVersion+ )+ return 'success';+ return timedOut ? 'timedOut' : 'pending';+ }+ if (!result) return 'loading';+ if (result.status === 'unsupported' || state?.supported === false) return 'unsupported';+ if (result.status === 'unavailable' || result.status === 'rejected') return 'unavailable';+ return 'ready';+};diff --git a/src/features/DeviceManager/CliUpdate/index.tsx b/src/features/DeviceManager/CliUpdate/index.tsxnew file mode 100644index 00000000000..67e9325ceeb--- /dev/null+++ b/src/features/DeviceManager/CliUpdate/index.tsx@@ -0,0 +1,150 @@+import { Flexbox } from '@lobehub/ui';+import { ActionIcon, Button, confirmModal, Popover, Text } from '@lobehub/ui/base-ui';+import { RotateCwIcon } from 'lucide-react';+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { useDeviceCliUpdate } from './useDeviceCliUpdate';++export const CliUpdate = ({+ children,+ deviceId,+ live,+ canEdit,+}: {+ children: (slots: { actions?: ReactNode; detail?: ReactNode }) => ReactNode;+ deviceId: string;+ live: boolean;+ canEdit: boolean;+}) => {+ const { t } = useTranslation(['setting', 'common']);+ const update = useDeviceCliUpdate(deviceId, live, canEdit);+ const { state, view } = update;+ const confirm = (install: boolean, retry = false) =>+ confirmModal({+ cancelText: t('common:cancel'),+ content: t('devices.cliUpdate.confirmDesc'),+ okText: t(install ? 'devices.cliUpdate.update' : 'devices.cliUpdate.restart'),+ onOk: () => {+ void (retry ? update.retryCommand() : update.restart(install));+ },+ title: t(install ? 'devices.cliUpdate.update' : 'devices.cliUpdate.restart'),+ });+ const operationError =+ view === 'failed' ? (state?.operation?.error ?? update.operation?.error) : undefined;+ const errorDetails =+ view === 'unsupported'+ ? undefined+ : [operationError, update.error].filter(Boolean).join('\n\n');+ if (!canEdit || (state?.activeTasks ?? 0) > 0) return children({});+ const actions = (+ <Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>+ {(update.error || !live || update.ambiguous || view === 'failed' || view === 'timedOut') && (+ <Button loading={update.refreshing} size={'small'} type={'text'} onClick={update.retryRead}>+ {t('devices.cliUpdate.retryRead')}+ </Button>+ )}+ {live &&+ view !== 'unsupported' &&+ view !== 'pending' &&+ view !== 'timedOut' &&+ !update.ambiguous && (+ <>+ {state?.latestVersion ? (+ <>+ <Text fontSize={12} type={'secondary'}>+ {t('devices.cliUpdate.available', { version: state.latestVersion })}+ </Text>+ <ActionIcon+ aria-label={t('devices.cliUpdate.update')}+ disabled={!update.allowed || update.requesting}+ icon={RotateCwIcon}+ loading={update.requesting}+ size={'small'}+ title={t('devices.cliUpdate.update')}+ onClick={() => confirm(true)}+ />+ </>+ ) : view === 'ready' && update.checked && !update.error ? (+ <Text fontSize={12} type={'secondary'}>+ {t('common:alreadyUpToDate')}+ </Text>+ ) : (+ <Button+ disabled={update.requesting}+ loading={update.requesting}+ size={'small'}+ type={'text'}+ onClick={update.check}+ >+ {t('common:checkForUpdates')}+ </Button>+ )}+ </>+ )}+ {(update.ambiguous || view === 'timedOut') && view !== 'success' && (+ <Button+ disabled={!update.allowed || update.requesting}+ loading={update.requesting}+ size={'small'}+ type={'text'}+ onClick={() => confirm(update.operation?.kind === 'update', true)}+ >+ {t('devices.cliUpdate.retryCommand')}+ </Button>+ )}+ </Flexbox>+ );+ const detail = (+ <Flexbox gap={4} style={{ paddingInlineStart: 16 }}>+ {view !== 'ready' && !(view === 'loading' && update.error) && (+ <Text+ fontSize={12}+ type={+ view === 'failed' || view === 'timedOut' || view === 'unavailable'+ ? 'danger'+ : 'secondary'+ }+ >+ {t(`devices.cliUpdate.${view}`)}+ {view === 'unsupported' && ` · ${t('devices.cliUpdate.bootstrap')}`}+ </Text>+ )}+ {update.error && view !== 'unsupported' && (+ <Text fontSize={12} type={'danger'}>+ {t('devices.cliUpdate.requestFailed')}+ </Text>+ )}+ {errorDetails && (+ <Popover+ placement={'bottomLeft'}+ styles={{ content: { maxWidth: 'min(400px, 80vw)' } }}+ trigger={'click'}+ content={+ <Text+ fontSize={12}+ style={{+ maxHeight: 200,+ overflow: 'auto',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ }}+ >+ {errorDetails}+ </Text>+ }+ >+ <Button size={'small'} style={{ alignSelf: 'flex-start' }} type={'text'}>+ {t('devices.cliUpdate.showDetails')}+ </Button>+ </Popover>+ )}+ {update.ambiguous && view !== 'success' && (+ <Text fontSize={12} type={'danger'}>+ {t('devices.cliUpdate.ambiguous')}+ </Text>+ )}+ </Flexbox>+ );+ return children({ actions, detail });+};diff --git a/src/features/DeviceManager/CliUpdate/useDeviceCliUpdate.test.ts b/src/features/DeviceManager/CliUpdate/useDeviceCliUpdate.test.tsnew file mode 100644index 00000000000..fea46a9995f--- /dev/null+++ b/src/features/DeviceManager/CliUpdate/useDeviceCliUpdate.test.ts@@ -0,0 +1,66 @@+import type { DeviceCliUpdateStateResult } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement } from 'react';+import { SWRConfig } from 'swr';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { deviceService } from '@/services/device';++import { useDeviceCliUpdate } from './useDeviceCliUpdate';++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => undefined,+}));+vi.mock('@/services/device', () => ({ deviceService: { getCliUpdateState: vi.fn() } }));+vi.mock('../const', () => ({ refreshDeviceList: vi.fn() }));++afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+});++describe('CLI maintenance availability', () => {+ it('automatically restores availability after tasks finish, then stops polling', async () => {+ vi.useFakeTimers();+ let activeTasks = 1;+ vi.mocked(deviceService.getCliUpdateState).mockImplementation(+ async () =>+ ({+ status: 'ok',+ state: {+ activeTasks,+ currentVersion: '2.1.0',+ instanceId: 'daemon',+ latestVersion: '2.1.1',+ supported: true,+ },+ }) satisfies DeviceCliUpdateStateResult,+ );+ const cache = new Map();+ const wrapper = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children);+ const { result, unmount } = renderHook(() => useDeviceCliUpdate('device', true, true), {+ wrapper,+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });+ expect(result.current.state?.activeTasks).toBe(1);+ expect(result.current.allowed).toBe(false);++ activeTasks = 0;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(3000);+ });+ expect(result.current.state?.activeTasks).toBe(0);+ expect(result.current.allowed).toBe(true);+ expect(deviceService.getCliUpdateState).toHaveBeenCalledTimes(2);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(9000);+ });+ expect(deviceService.getCliUpdateState).toHaveBeenCalledTimes(2);+ unmount();+ });+});diff --git a/src/features/DeviceManager/CliUpdate/useDeviceCliUpdate.ts b/src/features/DeviceManager/CliUpdate/useDeviceCliUpdate.tsnew file mode 100644index 00000000000..80c78fe36a3--- /dev/null+++ b/src/features/DeviceManager/CliUpdate/useDeviceCliUpdate.ts@@ -0,0 +1,170 @@+import type { DeviceCliUpdateOperation, DeviceCliUpdateStateResult } from '@lobechat/types';+import { useEffect, useRef, useState } from 'react';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useClientDataSWR } from '@/libs/swr';+import { deviceKeys } from '@/libs/swr/keys';+import { deviceService } from '@/services/device';++import { refreshDeviceList } from '../const';+import { deriveCliUpdateView } from './deriveCliUpdateView';++export const useDeviceCliUpdate = (deviceId: string, live: boolean, canEdit: boolean) => {+ const workspaceId = useActiveWorkspaceId();+ const [operation, setOperation] = useState<DeviceCliUpdateOperation>();+ const [timedOut, setTimedOut] = useState(false);+ const [requesting, setRequesting] = useState(false);+ const [requestError, setRequestError] = useState<string>();+ const [ambiguous, setAmbiguous] = useState(false);+ const [checked, setChecked] = useState(false);+ const mounted = useRef(true);+ const lock = useRef(false);+ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);+ const swr = useClientDataSWR<DeviceCliUpdateStateResult>(+ canEdit && (live || operation) ? deviceKeys.cliUpdateState(workspaceId, deviceId) : null,+ () => deviceService.getCliUpdateState({ deviceId }),+ {+ refreshInterval: (result) =>+ deriveCliUpdateView(result, operation, timedOut) === 'pending' ||+ (result?.status === 'ok' && result.state.activeTasks > 0)+ ? 3000+ : 0,+ revalidateOnFocus: false,+ shouldRetryOnError: !!operation && !timedOut,+ errorRetryCount: 100,+ errorRetryInterval: 3000,+ },+ );+ const state = swr.data?.status === 'ok' ? swr.data.state : undefined;+ const observedOperation = operation ?? state?.operation;+ const view = deriveCliUpdateView(swr.data, operation, timedOut);+ useEffect(() => {+ if (view === 'success' || view === 'failed') setAmbiguous(false);+ if (view === 'success') void refreshDeviceList();+ }, [view]);+ useEffect(() => {+ if (!operation && state?.operation && view === 'pending') setOperation(state.operation);+ }, [operation, state?.operation, view]);+ useEffect(() => {+ if (!observedOperation || timedOut || view !== 'pending') return;+ const timer = setTimeout(() => setTimedOut(true), 5 * 60_000);+ return () => clearTimeout(timer);+ }, [observedOperation?.id, timedOut, view]);++ const run = async (action: () => Promise<DeviceCliUpdateStateResult>, destructive: boolean) => {+ if (lock.current) return;+ lock.current = true;+ setRequesting(true);+ setRequestError(undefined);+ try {+ const result = await action();+ if (!mounted.current) return;+ if (destructive) setAmbiguous(result.status === 'unavailable');+ if (destructive && result.status === 'unsupported') setOperation(undefined);+ if (result.status === 'rejected') {+ setOperation(undefined);+ setRequestError(result.message);+ await swr.mutate();+ return;+ }+ if (result.status === 'ok') {+ setOperation(destructive ? result.state.operation : undefined);+ }+ await swr.mutate(result, { revalidate: false });+ } catch (error) {+ console.error(error);+ if (mounted.current) {+ setRequestError((error as Error).message);+ if (destructive) setAmbiguous(true);+ }+ } finally {+ lock.current = false;+ if (mounted.current) setRequesting(false);+ }+ };+ const allowed = canEdit && live && state?.supported && state.activeTasks === 0;+ // A confirmation can outlive a presence/permission change or scope unmount.+ const currentAccess = useRef({ allowed, canEdit, live });+ currentAccess.current = { allowed, canEdit, live };+ const restart = (update: boolean) => {+ if (+ !mounted.current ||+ !currentAccess.current.allowed ||+ !state ||+ !allowed ||+ lock.current ||+ view === 'pending' ||+ view === 'timedOut' ||+ ambiguous+ )+ return;+ const next: DeviceCliUpdateOperation = {+ fromInstanceId: state.instanceId,+ id: crypto.randomUUID(),+ kind: update ? 'update' : 'restart',+ stage: update ? 'updating' : 'restarting',+ targetVersion: update ? (state.latestVersion ?? state.currentVersion) : state.currentVersion,+ };+ setOperation(next);+ setTimedOut(false);+ return run(() => deviceService.restartCli({ deviceId, requestId: next.id, update }), true);+ };+ return {+ allowed,+ ambiguous,+ checked,+ operation: observedOperation,+ requesting,+ restart,+ check: () => {+ if (+ !mounted.current ||+ !currentAccess.current.canEdit ||+ !currentAccess.current.live ||+ !canEdit ||+ !live ||+ view === 'pending' ||+ view === 'timedOut' ||+ ambiguous ||+ lock.current+ )+ return;+ setTimedOut(false);+ setChecked(true);+ return run(() => deviceService.checkCliUpdate({ deviceId }), false);+ },+ error:+ requestError ??+ (swr.error as Error | undefined)?.message ??+ (swr.data?.status !== 'ok' ? swr.data?.message : undefined),+ refreshing: swr.isValidating,+ retryRead: () => swr.mutate(),+ retryCommand: () => {+ if (+ !mounted.current ||+ !currentAccess.current.allowed ||+ !allowed ||+ !operation ||+ (!ambiguous && view !== 'timedOut')+ )+ return;+ setTimedOut(false);+ return run(+ () =>+ deviceService.restartCli({+ deviceId,+ requestId: operation.id,+ update: operation.kind === 'update',+ }),+ true,+ );+ },+ state,+ view,+ };+};diff --git a/src/features/DeviceManager/Connections.tsx b/src/features/DeviceManager/Connections.tsxindex e083595f27d..38f2b4220c9 100644--- a/src/features/DeviceManager/Connections.tsx+++ b/src/features/DeviceManager/Connections.tsx@@ -5,10 +5,14 @@ import { Block, Flexbox } from '@lobehub/ui';import { Tag, Text } from '@lobehub/ui/base-ui';import dayjs from 'dayjs';import type { ReactNode } from 'react';+import { useRef } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { AppUpdateAction, AppUpdateHint, useDeviceAppUpdate } from './AppUpdate';import { getChannelKind, getChannelVersion } from './channelKind';+import { CliUpdate } from './CliUpdate';import FieldLabel from './FieldLabel';import PresenceDot from './PresenceDot';@@ -58,9 +62,13 @@ interface ConnectionsProps {*/const Connections = ({ canEdit, device }: ConnectionsProps) => {const { t } = useTranslation('setting');+ const workspaceId = useActiveWorkspaceId();const channels = device.channels ?? [];const kinds = channels.map((c) => getChannelKind(c.channel));+ const scope = `${workspaceId}:${device.deviceId}`;+ const seenCli = useRef<string | undefined>(undefined);+ if (kinds.includes('cli') || device.metadata?.cliVersion) seenCli.current = scope;const desktopIndex = kinds.indexOf('desktop');const hasDesktopChannel = desktopIndex !== -1;@@ -103,6 +111,7 @@ const Connections = ({ canEdit, device }: ConnectionsProps) => {time: dayjs(channel.connectedAt).fromNow(),});if (index === desktopIndex) return desktopCard(label, connectedText, true, key);+ if (kinds[index] === 'cli') return null;return (<ConnectionCard@@ -114,6 +123,31 @@ const Connections = ({ canEdit, device }: ConnectionsProps) => {/>);})}+ {seenCli.current === scope && (+ <CliUpdate+ canEdit={canEdit}+ deviceId={device.deviceId}+ key={`${workspaceId}:${device.deviceId}`}+ live={kinds.includes('cli')}+ >+ {({ actions, detail }) => (+ <ConnectionCard+ channel={'cli'}+ detail={detail}+ extra={actions}+ live={kinds.includes('cli')}+ version={getChannelVersion('cli', device.metadata)}+ status={plainStatus(+ kinds.includes('cli')+ ? t('devices.channel.connected', {+ time: dayjs(channels[kinds.indexOf('cli')].connectedAt).fromNow(),+ })+ : t('devices.status.offline'),+ )}+ />+ )}+ </CliUpdate>+ )}{restartInFlight && desktopCard('desktop', t('devices.status.offline'), false)}{channels.length === 0 &&!restartInFlight &&diff --git a/src/features/DeviceManager/DeviceDetailPanel.tsx b/src/features/DeviceManager/DeviceDetailPanel.tsxindex 37f6c610228..75733f7caef 100644--- a/src/features/DeviceManager/DeviceDetailPanel.tsx+++ b/src/features/DeviceManager/DeviceDetailPanel.tsx@@ -304,6 +304,26 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC{tab === 'overview' && (<>+ {/* ─── Name ─── */}+ <Flexbox gap={8}>+ <FieldLabel>{t('devices.edit.friendlyName')}</FieldLabel>+ {canEdit ? (+ <Input+ placeholder={t('devices.edit.friendlyNamePlaceholder')}+ value={name}+ onBlur={commitName}+ onChange={(e) => setName(e.target.value)}+ onPressEnter={commitName}+ />+ ) : device.friendlyName ? (+ // Read-only: render the canonical value (not the local draft), so a+ // value the caller can't actually commit never bleeds through.+ <Text>{device.friendlyName}</Text>+ ) : (+ <Text type={'secondary'}>—</Text>+ )}+ </Flexbox>+{/* ─── Enrolled by (workspace only) ─── */}{device.scope === 'workspace' && device.enroller && (<Flexbox gap={8}>@@ -352,26 +372,6 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC<FieldLabel extra={<HealthLegend />}>{t('devices.health.title')}</FieldLabel><DeviceHealth deviceId={device.deviceId} /></Flexbox>-- {/* ─── Name ─── */}- <Flexbox gap={8}>- <FieldLabel>{t('devices.edit.friendlyName')}</FieldLabel>- {canEdit ? (- <Input- placeholder={t('devices.edit.friendlyNamePlaceholder')}- value={name}- onBlur={commitName}- onChange={(e) => setName(e.target.value)}- onPressEnter={commitName}- />- ) : device.friendlyName ? (- // Read-only: render the canonical value (not the local draft), so a- // value the caller can't actually commit never bleeds through.- <Text>{device.friendlyName}</Text>- ) : (- <Text type={'secondary'}>—</Text>- )}- </Flexbox></>)}diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 857aee2ad24..41aea39a340 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -747,6 +747,11 @@ export const trashKeys = {};export const deviceKeys = {+ cliUpdateState: def('device:cliUpdateState', (workspaceId: string | null, deviceId: string) => [+ 'device:cliUpdateState',+ workspaceId,+ deviceId,+ ]),appUpdateState: def('device:appUpdateState', (workspaceId: string | null, deviceId: string) => ['device:appUpdateState',workspaceId,diff --git a/src/services/device.ts b/src/services/device.tsindex f6b9d34c0ec..b2374fbedcc 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -84,6 +84,19 @@ class DeviceService {return lambdaClient.device.installAppUpdate.mutate(input);}+ /** Read CLI maintenance state without checking the release registry. */+ getCliUpdateState(input: Parameters<DeviceClient['getCliUpdateState']['query']>[0]) {+ return lambdaClient.device.getCliUpdateState.query(input);+ }++ checkCliUpdate(input: Parameters<DeviceClient['checkCliUpdate']['mutate']>[0]) {+ return lambdaClient.device.checkCliUpdate.mutate(input);+ }++ restartCli(input: Parameters<DeviceClient['restartCli']['mutate']>[0]) {+ return lambdaClient.device.restartCli.mutate(input);+ }+/** The device's recent CPU / memory / load history, bucketed for charting. */getMetricSeries(deviceId: string) {return lambdaClient.deviceMetric.getSeries.query({ deviceId });