🤯 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(desktop): added Computer Use with `auv` (#19051)
Neko29acee69f6a1
diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjsindex 23b6b06be88..d81d99afd3c 100644--- a/apps/desktop/electron-builder.mjs+++ b/apps/desktop/electron-builder.mjs@@ -151,6 +151,17 @@ const config = {await copyNativeModulesToSource();await copyExternalRuntimeModulesToSource();+ // Keep the AUV daemon version locked to @auv-js/sdk. The CLI package+ // resolves the platform-specific executable without running postinstall,+ // then we stage that real file outside app.asar for child_process.spawn().+ const { binaryPath: resolveAuvBinaryPath } = await import('@auv-js/cli/binary');+ const auvSource = resolveAuvBinaryPath();+ const auvExecutable = process.platform === 'win32' ? 'auv.exe' : 'auv';+ const auvDestination = path.resolve(__dirname, 'resources/bin', auvExecutable);+ await fs.mkdir(path.dirname(auvDestination), { recursive: true });+ await fs.copyFile(auvSource, auvDestination);+ if (process.platform !== 'win32') await fs.chmod(auvDestination, 0o755);+// agent-browser is no longer bundled in the installer — BinaryManager// lazily downloads it on first use into the per-user cache dir. See// apps/desktop/src/main/modules/binaries/agentBrowserBinaries.ts.@@ -257,6 +268,13 @@ const config = {'dist/renderer/**/*','!resources/locales','!resources/dmg.png',+ // NOTICE:+ // AUV must execute from the external bin directory, so its ASAR copy is unnecessary.+ // The resources glob otherwise duplicates the binary copied by extraResources below.+ // Source: PR #19051 ASAR Size Gate; resources/bin is staged in beforePack above.+ // Remove these exclusions only if AUV no longer ships through extraResources.+ '!resources/bin/auv',+ '!resources/bin/auv.exe',// Exclude all node_modules first'!node_modules',// Then explicitly include native modules using object form (handles pnpm symlinks)@@ -272,7 +290,10 @@ const config = {target: ['AppImage', 'snap', 'deb', 'rpm', 'tar.gz'],},mac: {- binaries: ['Contents/Resources/app.asar.unpacked/node_modules/font-list/libs/darwin/fontlist'],+ binaries: [+ 'Contents/Resources/app.asar.unpacked/node_modules/font-list/libs/darwin/fontlist',+ 'Contents/Resources/bin/auv',+ ],compression: 'maximum',entitlementsInherit: 'build/entitlements.mac.plist',...(macCommunicationEntitlementsdiff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 74cebdad35a..be4dffeb13b 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -48,6 +48,8 @@"update-server": "sh scripts/update-test/run-test.sh"},"dependencies": {+ "@auv-js/cli": "0.0.16",+ "@auv-js/sdk": "0.0.16","@lobehub/fluent-emoji": "^4.1.0","@lydell/node-pty": "1.2.0-beta.12","electron-log": "^5.4.4",@@ -94,7 +96,7 @@"drizzle-kit": "^0.31.10","drizzle-orm": "^0.45.2","electron": "43.2.0",- "electron-builder": "26.14.0",+ "electron-builder": "26.16.1","electron-store": "^8.2.0","electron-updater": "^6.8.9","electron-window-state": "^5.0.3",diff --git a/apps/desktop/src/main/controllers/AuvCtr.ts b/apps/desktop/src/main/controllers/AuvCtr.tsnew file mode 100644index 00000000000..82c60cac217--- /dev/null+++ b/apps/desktop/src/main/controllers/AuvCtr.ts@@ -0,0 +1,96 @@+import AuvService, {+ type AuvConnectionSnapshot,+ type AuvRunCommandParams,+ type AuvRunCommandResult,+} from '@/services/auvSrv';++import { ControllerModule, IpcMethod } from './index';++/** Electron IPC seam for the main-process AUV runtime. */+export default class AuvCtr extends ControllerModule {+ static override readonly groupName = 'auv';++ private get service() {+ return this.app.getService(AuvService);+ }++ /**+ * Connects the Electron main process to AUV and returns its initial inventory.+ *+ * Triggering workflow:+ *+ * {@link IpcMethod}+ * -> `auv.connect`+ * -> {@link AuvCtr.connect}+ *+ * Upstream:+ * - Electron renderer IPC invocation of `auv.connect`+ *+ * Downstream:+ * - {@link AuvService.connect}+ */+ @IpcMethod()+ async connect(): Promise<AuvConnectionSnapshot> {+ return this.service.connect();+ }++ /**+ * Disconnects the Electron main process from AUV.+ *+ * Triggering workflow:+ *+ * {@link IpcMethod}+ * -> `auv.disconnect`+ * -> {@link AuvCtr.disconnect}+ *+ * Upstream:+ * - Electron renderer IPC invocation of `auv.disconnect`+ *+ * Downstream:+ * - {@link AuvService.disconnect}+ */+ @IpcMethod()+ async disconnect(): Promise<AuvConnectionSnapshot> {+ return this.service.disconnect();+ }++ /**+ * Returns the last serializable AUV connection snapshot.+ *+ * Triggering workflow:+ *+ * {@link IpcMethod}+ * -> `auv.getStatus`+ * -> {@link AuvCtr.getStatus}+ *+ * Upstream:+ * - Electron renderer IPC invocation of `auv.getStatus`+ *+ * Downstream:+ * - {@link AuvService.getSnapshot}+ */+ @IpcMethod()+ async getStatus(): Promise<AuvConnectionSnapshot> {+ return this.service.getSnapshot();+ }++ /**+ * Runs one typed AUV CLI command against the app-owned private daemon.+ *+ * Triggering workflow:+ *+ * {@link IpcMethod}+ * -> `auv.runCommand`+ * -> {@link AuvCtr.runCommand}+ *+ * Upstream:+ * - `lobe-computer-use/runCommand` client executor+ *+ * Downstream:+ * - {@link AuvService.runCommand}+ */+ @IpcMethod()+ async runCommand(params: AuvRunCommandParams): Promise<AuvRunCommandResult> {+ return this.service.runCommand(params);+ }+}diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 2afa561b8e6..507ad1e78f5 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -13,6 +13,7 @@ import {} from '@lobechat/heterogeneous-agents/scanHost';import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';+import AuvService, { type AuvRunCommandParams } from '@/services/auvSrv';import GatewayConnectionService from '@/services/gatewayConnectionSrv';import ImessageBridgeService from '@/services/imessageBridgeSrv';import { createLogger } from '@/utils/logger';@@ -35,6 +36,7 @@ type AvailableRemotePlatformRuntime = Extract<RemotePlatformCommandRuntime, { av// Hardcoded (not imported) so the desktop main process keeps zero builtin-tool// package deps — importing one risks the @lobechat/types stub runtime leak.const BrowserIdentifier = 'lobe-browser';+const AuvIdentifier = 'lobe-computer-use';function parseHermesSessionId(stderr: string): string | undefined {for (const line of stderr.split(/\r?\n/).reverse()) {@@ -144,6 +146,10 @@ export default class GatewayConnectionCtr extends ControllerModule {return this.app.getService(GatewayConnectionService);}+ private get auvService() {+ return this.app.getService(AuvService);+ }+private get remoteServerConfigCtr() {return this.app.getController(RemoteServerConfigCtr);}@@ -402,11 +408,29 @@ export default class GatewayConnectionCtr extends ControllerModule {return runDeviceRpc(method, params, this.deviceControlDeps);}+ /**+ * Dispatches a device-gateway tool call to its desktop-owned runtime.+ *+ * Triggering workflow:+ *+ * {@link GatewayConnectionService.setToolCallHandler}+ * -> `tool_call_request`+ * -> {@link GatewayConnectionCtr.executeToolCall}+ *+ * Upstream:+ * - {@link GatewayConnectionService.setToolCallHandler}+ *+ * Downstream:+ * - {@link GatewayConnectionCtr.executeAuvToolCall}+ * - {@link LocalSystemExecutionRuntime.executeToolCall}+ */private async executeToolCall(identifier: string | undefined,apiName: string,args: unknown,): Promise<BuiltinServerRuntimeOutput> {+ if (identifier === AuvIdentifier) return this.executeAuvToolCall(apiName, args);+// Browser is a renderer-resident tool: forward to the client executor via// BrowserControlCtr instead of the local-system apiName switch below.if (identifier === BrowserIdentifier) {@@ -492,6 +516,40 @@ export default class GatewayConnectionCtr extends ControllerModule {}}+ /**+ * Executes the stable LobeHub CLI tool against the app-owned AUV daemon.+ *+ * Triggering workflow:+ *+ * {@link GatewayConnectionCtr.executeToolCall}+ * -> `lobe-computer-use/runCommand`+ * -> {@link GatewayConnectionCtr.executeAuvToolCall}+ *+ * Upstream:+ * - {@link GatewayConnectionCtr.executeToolCall}+ *+ * Downstream:+ * - {@link AuvService.runCommand}+ */+ private async executeAuvToolCall(+ apiName: string,+ args: unknown,+ ): Promise<BuiltinServerRuntimeOutput> {+ if (apiName !== 'runCommand') {+ throw new Error(`AUV tool "${apiName}" is not available on this device`);+ }++ const result = await this.auvService.runCommand(args as AuvRunCommandParams);+ return {+ content: JSON.stringify(result),+ ...(result.exitCode !== 0 && {+ error: result.stderr || `Computer Use exited with code ${result.exitCode}`,+ }),+ state: result,+ success: result.exitCode === 0,+ };+ }+/*** Execute an MCP tool call tunneled from the cloud server, for MCP servers* only this machine can reach: stdio (the server can't spawn the user'sdiff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex c95ad7a37ee..5454a9c6ee0 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -5,6 +5,7 @@ import { deriveDeviceId, deriveScopedFallbackId } from '@lobechat/device-identitimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';+import AuvService from '@/services/auvSrv';import GatewayConnectionService from '@/services/gatewayConnectionSrv';import ImessageBridgeService from '@/services/imessageBridgeSrv';@@ -60,13 +61,18 @@ const { ipcMainHandleMock, MockGatewayClient } = vi.hoisted(() => {this.emit('status_changed', status);}- simulateToolCallRequest(apiName: string, args: object, requestId = 'req-1') {+ simulateToolCallRequest(+ apiName: string,+ args: object,+ requestId = 'req-1',+ identifier = 'test-tool',+ ) {this.emit('tool_call_request', {requestId,toolCall: {apiName,arguments: JSON.stringify(args),- identifier: 'test-tool',+ identifier,},type: 'tool_call_request',});@@ -260,6 +266,14 @@ const mockImessageBridgeSrv = {handleGatewayMessageApi: vi.fn().mockResolvedValue({ ok: true }),} as unknown as ImessageBridgeService;+const mockAuvSrv = {+ runCommand: vi.fn().mockResolvedValue({+ argv: ['invoke', 'display.capture'],+ exitCode: 0,+ output: { artifacts: [{ file_path: '/tmp/capture.png' }] },+ }),+} as unknown as AuvService;+const mockMcpCtr = {runStdioMcpTool: vi.fn().mockResolvedValue({ content: 'mcp result', state: {}, success: true }),} as unknown as McpCtr;@@ -286,6 +300,7 @@ const mockApp = {return null;}),getService: vi.fn((Cls) => {+ if (Cls === AuvService) return mockAuvSrv;if (Cls === GatewayConnectionService) return mockGatewayConnectionSrv;if (Cls === ImessageBridgeService) return mockImessageBridgeSrv;return null;@@ -650,6 +665,59 @@ describe('GatewayConnectionCtr', () => {expect((controller as any)[methodName]).toHaveBeenCalled();});+ it('should route AUV CLI commands to the app-owned runtime', async () => {+ const client = await connectAndOpen();++ client.simulateToolCallRequest(+ 'runCommand',+ { argv: ['invoke', 'display.capture'] },+ 'auv-command',+ 'lobe-computer-use',+ );+ await vi.advanceTimersByTimeAsync(0);++ expect(mockAuvSrv.runCommand).toHaveBeenCalledWith({+ argv: ['invoke', 'display.capture'],+ });+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({+ requestId: 'auv-command',+ result: expect.objectContaining({+ content: JSON.stringify({+ argv: ['invoke', 'display.capture'],+ exitCode: 0,+ output: { artifacts: [{ file_path: '/tmp/capture.png' }] },+ }),+ success: true,+ }),+ });+ });++ it('preserves AUV failure details in the gateway response', async () => {+ const client = await connectAndOpen();+ const result = {+ argv: ['invoke', 'input.typeText'],+ exitCode: 1,+ output: { command_id: 'input.typeText', failure: { kind: 'target_resolution' } },+ stderr: 'target not found',+ };+ vi.mocked(mockAuvSrv.runCommand).mockResolvedValueOnce(result);+ client.simulateToolCallRequest(+ 'runCommand',+ { argv: result.argv },+ 'auv-failure',+ 'lobe-computer-use',+ );+ await vi.advanceTimersByTimeAsync(0);+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({+ requestId: 'auv-failure',+ result: expect.objectContaining({+ content: JSON.stringify(result),+ state: result,+ success: false,+ }),+ });+ });+it('should send tool_call_response with content + state envelope on success', async () => {vi.mocked(mockLocalFileCtr.readFile).mockResolvedValueOnce({charCount: 5,diff --git a/apps/desktop/src/main/controllers/registry.ts b/apps/desktop/src/main/controllers/registry.tsindex fa11058840b..441ba17f60f 100644--- a/apps/desktop/src/main/controllers/registry.ts+++ b/apps/desktop/src/main/controllers/registry.ts@@ -1,6 +1,7 @@import type { CreateServicesResult, IpcServiceConstructor, MergeIpcService } from '@/utils/ipc';import AuthCtr from './AuthCtr';+import AuvCtr from './AuvCtr';import BinaryCtr from './BinaryCtr';import BrowserControlCtr from './BrowserControlCtr';import BrowserSidebarCtr from './BrowserSidebarCtr';@@ -35,6 +36,7 @@ import WorkspaceCtr from './WorkspaceCtr';export const controllerIpcConstructors = [HeterogeneousAgentCtr,AuthCtr,+ AuvCtr,BrowserControlCtr,BrowserSidebarCtr,BrowserWindowsCtr,diff --git a/apps/desktop/src/main/services/__tests__/auvSrv.test.ts b/apps/desktop/src/main/services/__tests__/auvSrv.test.tsnew file mode 100644index 00000000000..578fb99f3fa--- /dev/null+++ b/apps/desktop/src/main/services/__tests__/auvSrv.test.ts@@ -0,0 +1,259 @@+import type { AuvClient, AuvConnection, AuvDaemon } from '@auv-js/sdk/node';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import AuvService, { type AuvSdkRuntime } from '../auvSrv';++const localDevice = {+ id: 'device-local',+ labels: { 'auv.dev/platform': 'DEVICE_PLATFORM_MACOS' },+ local: true,+ name: '',+ platform: 'macos' as const,+};++const localRunnerClass = {+ available: true,+ deviceId: localDevice.id,+ displayName: 'auv.core.local',+ id: 'auv.core.local',+ supportedLifecycles: ['ephemeral', 'unless_idle', 'unless_shutdown'] as const,+};++function createHarness() {+ const connection = {+ close: vi.fn().mockResolvedValue(undefined),+ } as unknown as AuvConnection;+ const daemon = {+ connect: vi.fn().mockResolvedValue(connection),+ connectionOptions: {+ endpoint: 'unix:///tmp/lobehub-auv.sock',+ local: true,+ transport: 'unix',+ },+ stop: vi.fn().mockResolvedValue({ code: 0, signal: null }),+ } as unknown as AuvDaemon;+ const client = {+ devices: { list: vi.fn().mockResolvedValue([localDevice]) },+ health: { check: vi.fn().mockResolvedValue('serving') },+ runners: {+ listClasses: vi.fn().mockResolvedValue([localRunnerClass]),+ },+ } as unknown as AuvClient;+ const sdk = {+ createAuv: vi.fn().mockReturnValue(client),+ startAuv: vi.fn().mockResolvedValue(daemon),+ } as unknown as AuvSdkRuntime;+ const app = {+ appStoragePath: '/tmp/lobehub-storage',+ } as unknown as App;+ const ipcCleanup = vi.fn().mockResolvedValue(undefined);+ const resolveBinaryPath = vi.fn().mockResolvedValue('/opt/lobehub/bin/auv');+ const runCli = vi.fn().mockResolvedValue({+ stderr: '',+ stdout: JSON.stringify({+ artifacts: [{ file_path: '/tmp/lobehub-storage/auv/runs/capture.png' }],+ command_id: 'display.capture',+ status: 'completed',+ }),+ });+ const service = new AuvService(app, {+ createIpcListener: vi.fn().mockResolvedValue({+ cleanup: ipcCleanup,+ listener: 'unix:///private/auv/session.sock',+ }),+ hostname: () => 'Nekos-MBP.lan',+ loadSdk: vi.fn().mockResolvedValue(sdk),+ resolveBinaryPath,+ runCli,+ });++ return { app, client, connection, daemon, ipcCleanup, resolveBinaryPath, runCli, sdk, service };+}++describe('AuvService', () => {+ beforeEach(() => {+ delete process.env.AUV_BINARY_PATH;+ });++ it('starts an app-owned daemon and exposes a serializable device inventory', async () => {+ const { client, daemon, resolveBinaryPath, sdk, service } = createHarness();++ const snapshot = await service.connect();++ expect(resolveBinaryPath).toHaveBeenCalledOnce();+ expect(sdk.startAuv).toHaveBeenCalledWith({+ binaryPath: '/opt/lobehub/bin/auv',+ listeners: ['unix:///private/auv/session.sock'],+ noDiscovery: true,+ storeRoot: '/tmp/lobehub-storage/auv/store',+ });+ expect(daemon.connect).toHaveBeenCalledOnce();+ expect(client.health.check).toHaveBeenCalledOnce();+ expect(client.runners.listClasses).toHaveBeenCalledWith();+ expect(snapshot).toEqual({+ devices: [+ {+ id: 'device-local',+ labels: { 'auv.dev/platform': 'DEVICE_PLATFORM_MACOS' },+ local: true,+ name: 'Nekos-MBP',+ platform: 'macos',+ },+ ],+ runnerClasses: [localRunnerClass],+ status: 'connected',+ transport: 'unix',+ });+ });++ it('rejects and stops a child that does not expose a local IPC transport', async () => {+ const { daemon, ipcCleanup, service } = createHarness();+ Object.assign(daemon.connectionOptions, {+ endpoint: 'http://127.0.0.1:19847',+ local: true,+ transport: 'http',+ });++ await expect(service.connect()).rejects.toThrow('AUV refused non-private transport: http');++ expect(daemon.connect).not.toHaveBeenCalled();+ expect(daemon.stop).toHaveBeenCalledOnce();+ expect(ipcCleanup).toHaveBeenCalledOnce();+ expect(service.getSnapshot()).toEqual({+ devices: [],+ error: 'AUV refused non-private transport: http',+ runnerClasses: [],+ status: 'error',+ });+ });++ it('closes partially-opened resources and records a failed connection', async () => {+ const { client, connection, daemon, ipcCleanup, service } = createHarness();+ vi.mocked(client.health.check).mockRejectedValueOnce(new Error('daemon is unavailable'));++ await expect(service.connect()).rejects.toThrow('daemon is unavailable');++ expect(connection.close).toHaveBeenCalledOnce();+ expect(daemon.stop).toHaveBeenCalledOnce();+ expect(ipcCleanup).toHaveBeenCalledOnce();+ expect(service.getSnapshot()).toEqual({+ devices: [],+ error: 'daemon is unavailable',+ runnerClasses: [],+ status: 'error',+ });+ });++ it('closes the SDK connection and embedded daemon on disconnect', async () => {+ const { connection, daemon, ipcCleanup, service } = createHarness();+ await service.connect();++ const snapshot = await service.disconnect();++ expect(connection.close).toHaveBeenCalledOnce();+ expect(daemon.stop).toHaveBeenCalledOnce();+ expect(ipcCleanup).toHaveBeenCalledOnce();+ expect(snapshot).toEqual({ devices: [], runnerClasses: [], status: 'disconnected' });+ });++ it('returns defensive copies of device metadata', async () => {+ const { service } = createHarness();+ const snapshot = await service.connect();++ snapshot.devices[0]!.labels.changed = 'yes';+ snapshot.devices.length = 0;++ expect(service.getSnapshot().devices).toEqual([+ expect.objectContaining({+ labels: { 'auv.dev/platform': 'DEVICE_PLATFORM_MACOS' },+ name: 'Nekos-MBP',+ }),+ ]);+ });++ it('runs a typed CLI command against the private endpoint and preserves image artifacts', async () => {+ const { runCli, service } = createHarness();++ // Display-only reasoning must never become a CLI argument.+ const params = { argv: ['invoke', 'display.capture'], reasoning: 'Check the current screen' };+ const result = await service.runCommand(params);++ expect(runCli).toHaveBeenCalledWith({+ argv: ['invoke', 'display.capture', '--json'],+ binaryPath: '/opt/lobehub/bin/auv',+ endpoint: 'unix:///private/auv/session.sock',+ storeRoot: '/tmp/lobehub-storage/auv/runs',+ });+ expect(result).toEqual({+ argv: ['invoke', 'display.capture'],+ exitCode: 0,+ output: {+ artifacts: [{ file_path: '/tmp/lobehub-storage/auv/runs/capture.png' }],+ command_id: 'display.capture',+ status: 'completed',+ },+ });+ });++ // https://github.com/lobehub/lobehub/pull/19051+ it('preserves structured CLI failure output across the IPC boundary', async () => {+ const { runCli, service } = createHarness();+ const failure = {+ command_id: 'input.typeText',+ failure: { kind: 'target_resolution', message: 'target application not found' },+ };+ runCli.mockRejectedValueOnce(+ Object.assign(new Error('Command failed'), {+ code: 1,+ stderr: 'target application not found\n',+ stdout: JSON.stringify(failure),+ }),+ );++ await expect(+ service.runCommand({+ argv: ['invoke', 'input.typeText', 'hello', '--target', 'app:missing'],+ }),+ ).resolves.toEqual({+ argv: ['invoke', 'input.typeText', 'hello', '--target', 'app:missing'],+ exitCode: 1,+ output: failure,+ stderr: 'target application not found',+ });+ });++ it('keeps process startup failures as errors', async () => {+ const { runCli, service } = createHarness();+ runCli.mockRejectedValueOnce(Object.assign(new Error('spawn ENOENT'), { code: 'ENOENT' }));+ await expect(service.runCommand({ argv: ['invoke', 'display.list'] })).rejects.toThrow(+ 'spawn ENOENT',+ );+ });++ it('returns CLI help as text without forcing JSON output', async () => {+ const { runCli, service } = createHarness();+ runCli.mockResolvedValueOnce({ stderr: '', stdout: 'Usage: auv invoke <COMMAND>' });++ const result = await service.runCommand({ argv: ['invoke', '--help'] });++ expect(runCli).toHaveBeenCalledWith(expect.objectContaining({ argv: ['invoke', '--help'] }));+ expect(result.output).toBe('Usage: auv invoke <COMMAND>');+ });++ it.each([+ [{ argv: ['serve', '--help'] }, 'Only "auv invoke" commands are allowed'],+ [+ { argv: ['invoke', 'display.capture', '--store-root', '/tmp/other'] },+ 'AUV --store-root is managed by LobeHub',+ ],+ ])('rejects unsafe CLI argv before starting AUV', async (params, message) => {+ const { runCli, sdk, service } = createHarness();++ await expect(service.runCommand(params)).rejects.toThrow(message);++ expect(sdk.startAuv).not.toHaveBeenCalled();+ expect(runCli).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/services/auvSrv.ts b/apps/desktop/src/main/services/auvSrv.tsnew file mode 100644index 00000000000..1563345017d--- /dev/null+++ b/apps/desktop/src/main/services/auvSrv.ts@@ -0,0 +1,450 @@+import { execFile, type ExecFileException } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { access, chmod, mkdtemp, rmdir } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';++import type {+ AuvClient,+ AuvConnection,+ AuvDaemon,+ createAuv,+ Device,+ RunnerClass,+ startAuv,+} from '@auv-js/sdk/node';++import type { App } from '@/core/App';+import { createLogger } from '@/utils/logger';++import { ServiceModule } from './index';++const logger = createLogger('services:AuvSrv');++export interface AuvSdkRuntime {+ createAuv: typeof createAuv;+ startAuv: typeof startAuv;+}++export type AuvConnectionStatus = 'connected' | 'connecting' | 'disconnected' | 'error';++export interface AuvDeviceInfo {+ id: string;+ labels: Record<string, string>;+ local: boolean;+ name: string;+ platform: Device['platform'];+}++export interface AuvRunnerClassInfo {+ available: boolean;+ deviceId?: string;+ displayName: string;+ id: string;+ supportedLifecycles: RunnerClass['supportedLifecycles'];+}++export interface AuvRunCommandParams {+ argv: string[];+}++export interface AuvRunCommandResult {+ argv: string[];+ /** Process exit status, not verification of the requested UI effect. */+ exitCode: number;+ output: unknown;+ stderr?: string;+}++export interface AuvCliExecutionOptions {+ argv: string[];+ binaryPath: string;+ endpoint: string;+ storeRoot: string;+}++export interface AuvConnectionSnapshot {+ devices: AuvDeviceInfo[];+ error?: string;+ runnerClasses: AuvRunnerClassInfo[];+ status: AuvConnectionStatus;+ transport?: 'npipe' | 'unix';+}++export interface AuvRuntimeDependencies {+ createIpcListener: () => Promise<PrivateIpcListener>;+ hostname: () => string;+ loadSdk: () => Promise<AuvSdkRuntime>;+ resolveBinaryPath: () => Promise<string>;+ runCli: (options: AuvCliExecutionOptions) => Promise<{ stderr: string; stdout: string }>;+}++export interface PrivateIpcListener {+ cleanup?: () => Promise<void>;+ listener: string;+}++const createPrivateIpcListener = async (): Promise<PrivateIpcListener> => {+ if (process.platform === 'win32') {+ return { listener: `npipe://./pipe/lobehub-auv-${randomUUID()}` };+ }++ // Darwin's sockaddr_un.sun_path is only 104 bytes. A short mkdtemp path also+ // gives each app-owned child an unguessable, owner-only directory.+ const ipcDirectory = await mkdtemp('/tmp/lobehub-auv-');+ await chmod(ipcDirectory, 0o700);+ return {+ cleanup: () => rmdir(ipcDirectory),+ listener: `unix://${path.join(ipcDirectory, 'auv.sock')}`,+ };+};++const resolveAuvBinaryPath = async (): Promise<string> => {+ const executable = process.platform === 'win32' ? 'auv.exe' : 'auv';+ const packagedBinary = process.resourcesPath+ ? path.join(process.resourcesPath, 'bin', executable)+ : undefined;++ if (packagedBinary) {+ try {+ await access(packagedBinary);+ return packagedBinary;+ } catch {+ // Development resolves the platform-matched executable from @auv-js/cli.+ }+ }++ const { binaryPath } = await import('@auv-js/cli/binary');+ return binaryPath();+};++const execFileAsync = promisify(execFile);++const runAuvCli = async ({+ argv,+ binaryPath,+ endpoint,+ storeRoot,+}: AuvCliExecutionOptions): Promise<{ stderr: string; stdout: string }> => {+ const { stderr, stdout } = await execFileAsync(binaryPath, [...argv, '--store-root', storeRoot], {+ encoding: 'utf8',+ env: { ...process.env, AUV_ENDPOINT: endpoint },+ maxBuffer: 4 * 1024 * 1024,+ timeout: 120_000,+ windowsHide: true,+ });++ return { stderr, stdout };+};++const defaultDependencies: AuvRuntimeDependencies = {+ createIpcListener: createPrivateIpcListener,+ hostname: os.hostname,+ loadSdk: () => import('@auv-js/sdk/node'),+ resolveBinaryPath: resolveAuvBinaryPath,+ runCli: runAuvCli,+};++const normalizeHostname = (hostname: string) => hostname.replace(/\.(?:lan|local)$/i, '');++const serializeError = (error: unknown) => (error instanceof Error ? error.message : String(error));++const MAX_CLI_ARGUMENTS = 128;+const MAX_CLI_ARGUMENT_LENGTH = 16_384;+const AUV_COMMAND_ID = /^[a-z][A-Za-z0-9]*(?:\.[A-Za-z][A-Za-z0-9]*)+$/;++const normalizeCliArgv = (params: AuvRunCommandParams): string[] => {+ if (!Array.isArray(params.argv)) throw new Error('AUV argv must be an array');+ if (params.argv.length < 2) {+ throw new Error('AUV argv must include "invoke" and a command or --help');+ }+ if (params.argv.length > MAX_CLI_ARGUMENTS) {+ throw new Error(`AUV argv cannot contain more than ${MAX_CLI_ARGUMENTS} arguments`);+ }++ const argv = params.argv.map((argument) => {+ if (typeof argument !== 'string') throw new Error('Every AUV argument must be a string');+ if (argument.includes('\0')) throw new Error('AUV arguments cannot contain NUL bytes');+ if (argument.length > MAX_CLI_ARGUMENT_LENGTH) {+ throw new Error(`AUV arguments cannot exceed ${MAX_CLI_ARGUMENT_LENGTH} characters`);+ }+ return argument;+ });++ if (argv[0] !== 'invoke') {+ throw new Error('Only "auv invoke" commands are allowed');+ }+ if (+ argv.some((argument) => argument === '--store-root' || argument.startsWith('--store-root='))+ ) {+ throw new Error('AUV --store-root is managed by LobeHub');+ }++ const command = argv[1]!;+ if (+ command !== '--help' &&+ command !== '-h' &&+ command !== 'help' &&+ !AUV_COMMAND_ID.test(command)+ ) {+ throw new Error(`Invalid AUV invoke command: ${command}`);+ }++ const isHelp = argv.includes('--help') || argv.includes('-h') || command === 'help';+ if (!isHelp && !argv.includes('--json')) argv.push('--json');+ return argv;+};++const parseCliOutput = (stdout: string): unknown => {+ const output = stdout.trim();+ if (!output) return null;++ try {+ return JSON.parse(output);+ } catch {+ return output;+ }+};++/**+ * Owns the AUV SDK connection and, when needed, the embedded daemon lifecycle.+ * Renderer callers only receive serializable snapshots; raw SDK and child-process+ * handles remain in the Electron main process.+ */+export default class AuvService extends ServiceModule {+ private client: AuvClient | null = null;+ private connectInFlight: Promise<AuvConnectionSnapshot> | null = null;+ private connection: AuvConnection | null = null;+ private daemon: AuvDaemon | null = null;+ private binaryPath: string | null = null;+ private ipcCleanup: (() => Promise<void>) | null = null;+ private ipcEndpoint: string | null = null;+ private snapshot: AuvConnectionSnapshot = {+ devices: [],+ runnerClasses: [],+ status: 'disconnected',+ };++ constructor(+ app: App,+ private readonly dependencies: AuvRuntimeDependencies = defaultDependencies,+ ) {+ super(app);+ }++ /** Connect once and return a fresh inventory of the target AUV daemon. */+ async connect(): Promise<AuvConnectionSnapshot> {+ if (this.connectInFlight) return this.connectInFlight;++ if (this.connection && this.client) {+ return this.refreshSnapshot();+ }++ this.snapshot = { devices: [], runnerClasses: [], status: 'connecting' };+ const task = this.open().finally(() => {+ this.connectInFlight = null;+ });+ this.connectInFlight = task;+ return task;+ }++ /** Close the SDK transport and stop an app-owned daemon, if one was started. */+ async disconnect(): Promise<AuvConnectionSnapshot> {+ if (this.connectInFlight) {+ try {+ await this.connectInFlight;+ } catch {+ // The failed connection path already released any partially-owned handles.+ }+ }++ const connection = this.connection;+ const daemon = this.daemon;+ const ipcCleanup = this.ipcCleanup;+ this.client = null;+ this.connection = null;+ this.daemon = null;+ this.binaryPath = null;+ this.ipcCleanup = null;+ this.ipcEndpoint = null;++ const errors: unknown[] = [];+ try {+ await connection?.close();+ } catch (error) {+ errors.push(error);+ }++ try {+ await daemon?.stop();+ } catch (error) {+ errors.push(error);+ }++ try {+ await ipcCleanup?.();+ } catch (error) {+ errors.push(error);+ }++ this.snapshot = { devices: [], runnerClasses: [], status: 'disconnected' };+ if (errors.length > 0) throw errors[0];+ return this.getSnapshot();+ }++ getSnapshot(): AuvConnectionSnapshot {+ return {+ ...this.snapshot,+ devices: this.snapshot.devices.map((device) => ({ ...device, labels: { ...device.labels } })),+ runnerClasses: this.snapshot.runnerClasses.map((runnerClass) => ({ ...runnerClass })),+ };+ }++ /** Let other main-process modules use AUV without learning its lifecycle rules. */+ async getClient(): Promise<AuvClient> {+ if (!this.client) await this.connect();+ return this.client!;+ }++ /**+ * Triggering workflow: AuvCtr / GatewayConnectionCtr `runCommand` -> runCommand+ * -> private app-owned CLI invocation; preserve output on nonzero exits.+ */+ async runCommand(params: AuvRunCommandParams): Promise<AuvRunCommandResult> {+ const argv = normalizeCliArgv(params);+ await this.getClient();+ if (!this.binaryPath || !this.ipcEndpoint) throw new Error('AUV is not connected');++ let stdout: string;+ let stderr: string;+ let exitCode = 0;+ try {+ ({ stderr, stdout } = await this.dependencies.runCli({+ argv,+ binaryPath: this.binaryPath,+ endpoint: this.ipcEndpoint,+ storeRoot: path.join(this.app.appStoragePath, 'auv', 'runs'),+ }));+ } catch (error) {+ // execFile rejects nonzero exits even when stdout contains AUV's structured+ // failure. Return that envelope over IPC; spawn/timeout failures still throw.+ const failure = error as ExecFileException & { stdout?: string; stderr?: string };+ if (typeof failure?.code !== 'number' || failure.killed) throw error;+ exitCode = failure.code;+ stdout = failure.stdout ?? '';+ stderr = failure.stderr ?? '';+ }+ const stderrOutput = stderr.trim();++ return {+ argv: [...params.argv],+ exitCode,+ output: parseCliOutput(stdout),+ ...(stderrOutput && { stderr: stderrOutput }),+ };+ }++ destroy() {+ void this.disconnect().catch((error) => logger.warn('Failed to stop AUV cleanly:', error));+ }++ private async open(): Promise<AuvConnectionSnapshot> {+ let connection: AuvConnection | null = null;+ let daemon: AuvDaemon | null = null;+ let privateIpc: PrivateIpcListener | null = null;++ try {+ const sdk = await this.dependencies.loadSdk();+ const binaryPath =+ process.env.AUV_BINARY_PATH || (await this.dependencies.resolveBinaryPath());+ const auvRoot = path.join(this.app.appStoragePath, 'auv');+ privateIpc = await this.dependencies.createIpcListener();+ daemon = await sdk.startAuv({+ binaryPath,+ listeners: [privateIpc.listener],+ noDiscovery: true,+ storeRoot: path.join(auvRoot, 'store'),+ });++ const { local, transport } = daemon.connectionOptions;+ if (!local || (transport !== 'unix' && transport !== 'npipe')) {+ throw new Error(`AUV refused non-private transport: ${transport}`);+ }++ connection = await daemon.connect();+ const client = sdk.createAuv(connection);+ await client.health.check();++ this.connection = connection;+ this.daemon = daemon;+ this.binaryPath = binaryPath;+ this.ipcCleanup = privateIpc.cleanup ?? null;+ this.ipcEndpoint = privateIpc.listener;+ this.client = client;+ this.snapshot = { devices: [], runnerClasses: [], status: 'connected', transport };++ const snapshot = await this.refreshSnapshot();+ logger.info(+ `Connected to app-owned AUV via ${transport}; devices: ${snapshot.devices.map((device) => device.name).join(', ')}`,+ );+ return snapshot;+ } catch (error) {+ await connection?.close().catch(() => undefined);+ await daemon?.stop().catch(() => undefined);+ await privateIpc?.cleanup?.().catch(() => undefined);+ this.connection = null;+ this.daemon = null;+ this.binaryPath = null;+ this.ipcCleanup = null;+ this.ipcEndpoint = null;+ this.client = null;+ this.snapshot = {+ devices: [],+ error: serializeError(error),+ runnerClasses: [],+ status: 'error',+ };+ throw error;+ }+ }++ private async refreshSnapshot(): Promise<AuvConnectionSnapshot> {+ if (!this.client) throw new Error('AUV is not connected');++ const devices = await this.client.devices.list();+ const localName = normalizeHostname(this.dependencies.hostname());+ const deviceInfo = devices.map((device) => this.toDeviceInfo(device, localName));+ // Local IPC connections are already scoped to the app-owned daemon. The SDK+ // rejects an explicit device selector on this transport.+ const runnerClasses = await this.client.runners.listClasses();++ this.snapshot = {+ devices: deviceInfo,+ runnerClasses: runnerClasses.map(this.toRunnerClassInfo),+ status: 'connected',+ transport: this.snapshot.transport,+ };+ return this.getSnapshot();+ }++ private toDeviceInfo(device: Device, localName: string): AuvDeviceInfo {+ return {+ id: device.id,+ labels: { ...device.labels },+ local: device.local,+ name: device.name || (device.local ? localName : device.id),+ platform: device.platform,+ };+ }++ private toRunnerClassInfo(runnerClass: RunnerClass): AuvRunnerClassInfo {+ return {+ available: runnerClass.available,+ deviceId: runnerClass.deviceId,+ displayName: runnerClass.displayName,+ id: runnerClass.id,+ supportedLifecycles: runnerClass.supportedLifecycles,+ };+ }+}diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.tsindex 49789931b9d..61a2a09c80e 100644--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts@@ -691,6 +691,10 @@ export default class GatewayConnectionService extends ServiceModule {// ─── System Info ───+ /**+ * Triggering workflow: gateway `system_info_request` -> handleSystemInfoRequest+ * -> {@link GatewayClient.sendSystemInfoResponse}, including desktop tool support.+ */private async handleSystemInfoRequest(client: GatewayClient, request: SystemInfoRequestMessage) {logger.info(`Received system_info_request: requestId=${request.requestId}`);const { getShellInfo } = await import('@lobechat/local-file-shell/shell');@@ -699,6 +703,7 @@ export default class GatewayConnectionService extends ServiceModule {result: {success: true,systemInfo: {+ supportedTools: ['lobe-computer-use'],arch: os.arch(),// Tell the server-side prompt builder which shell runCommand spawns here.defaultShell: (await getShellInfo()).displayName,diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.tsindex 17381b62439..0d3eaa70aca 100644--- a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';@@ -219,6 +220,99 @@ describe('createServerToolsEngine', () => {});describe('createServerAgentToolsEngine', () => {+ // https://github.com/lobehub/lobehub/pull/19051+ it('keeps Computer Use unloaded until activation on a supported device', () => {+ const engine = createServerAgentToolsEngine(createMockContext(), {+ agentConfig: { plugins: [] },+ canUseDevice: true,+ deviceContext: {+ gatewayConfigured: true,+ deviceOnline: true,+ autoActivated: true,+ supportedTools: [AuvManifest.identifier],+ },+ model: 'gpt-4',+ provider: 'openai',+ });+ expect(+ engine.generateToolsDetailed({ model: 'gpt-4', provider: 'openai', toolIds: [] })+ .enabledToolIds,+ ).not.toContain(AuvManifest.identifier);+ expect(+ engine.generateToolsDetailed({+ model: 'gpt-4',+ provider: 'openai',+ toolIds: [AuvManifest.identifier],+ context: { isExplicitActivation: true },+ }).enabledToolIds,+ ).toContain(AuvManifest.identifier);+ });++ it('allows Web explicit activation through a connected desktop device', () => {+ const engine = createServerAgentToolsEngine(createMockContext(), {+ agentConfig: { plugins: [AuvManifest.identifier] },+ canUseDevice: true,+ deviceContext: {+ gatewayConfigured: true,+ deviceOnline: true,+ autoActivated: true,+ supportedTools: [AuvManifest.identifier],+ },+ manifestContext: { executionEnv: 'device' },+ model: 'gpt-4',+ provider: 'openai',+ });+ expect(engine.getAvailablePlugins()).toContain(AuvManifest.identifier);+ expect(+ engine.generateToolsDetailed({+ model: 'gpt-4',+ provider: 'openai',+ toolIds: [AuvManifest.identifier],+ context: { isExplicitActivation: true },+ }).enabledToolIds,+ ).toContain(AuvManifest.identifier);+ });++ // https://github.com/lobehub/lobehub/pull/19051+ it('cannot explicitly activate Computer Use on an older device', () => {+ const engine = createServerAgentToolsEngine(createMockContext(), {+ agentConfig: { plugins: [AuvManifest.identifier] },+ canUseDevice: true,+ deviceContext: { gatewayConfigured: true, deviceOnline: true, autoActivated: true },+ model: 'gpt-4',+ provider: 'openai',+ });+ const result = engine.generateToolsDetailed({+ context: { isExplicitActivation: true },+ model: 'gpt-4',+ provider: 'openai',+ toolIds: [AuvManifest.identifier],+ });+ expect(result.enabledToolIds).not.toContain(AuvManifest.identifier);+ });++ it('enables Computer Use when the routed device reports support', () => {+ const engine = createServerAgentToolsEngine(createMockContext(), {+ agentConfig: { plugins: [AuvManifest.identifier] },+ canUseDevice: true,+ deviceContext: {+ gatewayConfigured: true,+ deviceOnline: true,+ autoActivated: true,+ supportedTools: [AuvManifest.identifier],+ },+ model: 'gpt-4',+ provider: 'openai',+ });+ expect(+ engine.generateToolsDetailed({+ model: 'gpt-4',+ provider: 'openai',+ toolIds: [AuvManifest.identifier],+ }).enabledToolIds,+ ).toContain(AuvManifest.identifier);+ });+it('should return a ToolsEngine instance', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/index.tsindex f47164911a4..e3b21494192 100644--- a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts@@ -9,6 +9,7 @@* - Gets model capabilities from provided function* - No dependency on frontend stores (useToolStore, useAgentStore, etc.)*/+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { BrowserManifest } from '@lobechat/builtin-tool-browser';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { ImageGenerationManifest } from '@lobechat/builtin-tool-image-generation';@@ -354,6 +355,8 @@ export const createServerAgentToolsEngine = (};const excludedIdentifiers = new Set(disabledPluginIds);+ if (hasDeviceProxy && !deviceContext?.supportedTools?.includes(AuvManifest.identifier))+ excludedIdentifiers.add(AuvManifest.identifier);if (!canUseDevice) {for (const identifier of DEVICE_TOOL_IDENTIFIERS) excludedIdentifiers.add(identifier);} else if (deviceLocked) {@@ -367,7 +370,12 @@ export const createServerAgentToolsEngine = (// denies them. Without this filter, `lobe-activator`'s explicit// activation could resolve the manifest and bypass the rule-layer// gates below ().- builtinTools: buildAllowedBuiltinTools({ canUseDevice, deviceLocked, disableLocalSystem }),+ builtinTools: buildAllowedBuiltinTools({+ canUseDevice,+ deviceLocked,+ disableLocalSystem,+ supportedDeviceTools: hasDeviceProxy ? (deviceContext?.supportedTools ?? []) : undefined,+ }),// Add default tools based on configuration. Custom mode = exactly the// agent's plugins; chat mode = strict allow-list; agent mode = full defaults.// Agent mode: the supervisor's orchestration tools are neither in thediff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/types.tsindex 8778c6f295a..dbe263a0315 100644--- a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts@@ -99,6 +99,7 @@ export interface ServerCreateAgentToolsEngineParams {canUseDevice?: boolean;/** Device gateway context for remote tool calling */deviceContext?: {+ supportedTools?: readonly string[];/** When true, a device has been auto-activated — Remote Device tool is unnecessary */autoActivated?: boolean;boundDeviceId?: string;diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.tsindex cda6d260cd3..aba894c6c44 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts@@ -22,6 +22,7 @@ const { mockDeviceProxy } = vi.hoisted(() => ({mockDeviceProxy: {isConfigured: false,queryDeviceList: vi.fn().mockResolvedValue([]),+ queryDeviceSystemInfo: vi.fn().mockResolvedValue(undefined),},}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.tsindex e8bab1dac80..6b2b785bed5 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts@@ -1,3 +1,4 @@+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';import type * as ModelBankModule from 'model-bank';@@ -232,6 +233,45 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {});});+ // https://github.com/lobehub/lobehub/pull/19051+ it('exposes Computer Use for Web activation through an online desktop', async () => {+ const { deviceGateway } = await import('@/server/services/deviceGateway');+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);+ mockQueryDeviceList.mockResolvedValue([+ { deviceId: 'dev-1', hostname: 'Mac', online: true, platform: 'darwin' },+ ]);+ mockQueryDeviceSystemInfo.mockResolvedValue({ supportedTools: [AuvManifest.identifier] });+ mockGetAgentConfig.mockResolvedValue(+ createBaseAgentConfig({+ agencyConfig: { executionTarget: 'local' },+ plugins: [AuvManifest.identifier],+ }),+ );+ mockGetEnabledPluginManifests.mockReturnValue(new Map([[AuvManifest.identifier, AuvManifest]]));+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello', deviceId: 'dev-1' });+ expect(+ mockCreateOperation.mock.calls[0][0].toolSet.manifestMap[AuvManifest.identifier],+ ).toBeDefined();+ });++ it.each([undefined, ['lobe-computer-use']])(+ 'gates Computer Use discovery on reported support %j',+ async (supportedTools) => {+ const { deviceGateway } = await import('@/server/services/deviceGateway');+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);+ mockQueryDeviceList.mockResolvedValue([+ { deviceId: 'dev-1', hostname: 'Mac', online: true, platform: 'darwin' },+ ]);+ mockQueryDeviceSystemInfo.mockResolvedValue({ supportedTools });+ mockGetAgentConfig.mockResolvedValue(+ createBaseAgentConfig({ agencyConfig: { executionTarget: 'local' } }),+ );+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello', deviceId: 'dev-1' });+ const map = mockCreateOperation.mock.calls[0][0].toolSet.manifestMap;+ expect(Boolean(map[AuvManifest.identifier])).toBe(Boolean(supportedTools));+ },+ );+describe('deviceContext forwarded to createServerAgentToolsEngine', () => {it('should pass deviceContext when gateway is configured', async () => {// Override deviceGateway.isConfigured@@ -376,6 +416,21 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {expect(executorMap[LocalSystemManifest.identifier]).toBe('client');});+ it('keeps Computer Use client-routed in standalone Electron', async () => {+ const { deviceGateway } = await import('@/server/services/deviceGateway');+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(false);+ mockGetEnabledPluginManifests.mockReturnValue(+ new Map([[AuvManifest.identifier, AuvManifest]]),+ );+ mockGetAgentConfig.mockResolvedValue(+ createBaseAgentConfig({ plugins: [AuvManifest.identifier] }),+ );+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });+ const toolSet = mockCreateOperation.mock.calls[0][0].toolSet;+ expect(toolSet.manifestMap[AuvManifest.identifier]).toBeDefined();+ expect(toolSet.executorMap[AuvManifest.identifier]).toBe('client');+ });+it('should NOT mark local-system as client when gateway IS configured (cloud)', async () => {const { deviceGateway } = await import('@/server/services/deviceGateway');vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);diff --git a/apps/server/src/services/aiAgent/deviceToolRegistry.test.ts b/apps/server/src/services/aiAgent/deviceToolRegistry.test.tsindex ae7811380d5..ed382ffc732 100644--- a/apps/server/src/services/aiAgent/deviceToolRegistry.test.ts+++ b/apps/server/src/services/aiAgent/deviceToolRegistry.test.ts@@ -1,3 +1,4 @@+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { BrowserManifest } from '@lobechat/builtin-tool-browser';import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';@@ -11,12 +12,13 @@ import {} from './deviceToolRegistry';describe('deviceToolRegistry', () => {- it('pins the device tool set to exactly local-system + remote-device + browser', () => {+ it('pins the device tool set to local-system, AUV, remote-device, and browser', () => {expect([...DEVICE_TOOL_IDENTIFIERS].sort()).toEqual([LocalSystemManifest.identifier,RemoteDeviceManifest.identifier,BrowserManifest.identifier,+ AuvManifest.identifier,].sort(),);});@@ -25,14 +27,25 @@ describe('deviceToolRegistry', () => {expect(isDeviceToolIdentifier(LocalSystemManifest.identifier)).toBe(true);expect(isDeviceToolIdentifier(RemoteDeviceManifest.identifier)).toBe(true);expect(isDeviceToolIdentifier(BrowserManifest.identifier)).toBe(true);+ expect(isDeviceToolIdentifier(AuvManifest.identifier)).toBe(true);expect(isDeviceToolIdentifier('web-browsing')).toBe(false);expect(isDeviceToolIdentifier('')).toBe(false);});describe('buildAllowedBuiltinTools', () => {+ // https://github.com/lobehub/lobehub/pull/19051+ it('hides Computer Use when a device does not report support', () => {+ expect(+ buildAllowedBuiltinTools({ canUseDevice: true, supportedDeviceTools: [] }).map(+ (tool) => tool.identifier,+ ),+ ).not.toContain(AuvManifest.identifier);+ });+it('returns the full builtin list when canUseDevice=true and disableLocalSystem=false', () => {const result = buildAllowedBuiltinTools({canUseDevice: true,+ supportedDeviceTools: [AuvManifest.identifier],disableLocalSystem: false,});expect(result.map((t) => t.identifier).sort()).toEqual(@@ -47,18 +60,21 @@ describe('deviceToolRegistry', () => {});const ids = result.map((t) => t.identifier);expect(ids).not.toContain(LocalSystemManifest.identifier);+ expect(ids).not.toContain(AuvManifest.identifier);expect(ids).not.toContain(RemoteDeviceManifest.identifier);// Non-device builtin tools are still present.expect(ids.length).toBeGreaterThan(0);});- it('strips only local-system when canUseDevice=true and disableLocalSystem=true', () => {+ it('strips local-system and AUV when disableLocalSystem=true', () => {const result = buildAllowedBuiltinTools({canUseDevice: true,+ supportedDeviceTools: [AuvManifest.identifier],disableLocalSystem: true,});const ids = result.map((t) => t.identifier);expect(ids).not.toContain(LocalSystemManifest.identifier);+ expect(ids).not.toContain(AuvManifest.identifier);expect(ids).toContain(RemoteDeviceManifest.identifier);});@@ -69,27 +85,37 @@ describe('deviceToolRegistry', () => {});const ids = result.map((t) => t.identifier);expect(ids).not.toContain(LocalSystemManifest.identifier);+ expect(ids).not.toContain(AuvManifest.identifier);expect(ids).not.toContain(RemoteDeviceManifest.identifier);});it('treats omitted disableLocalSystem as false', () => {- const result = buildAllowedBuiltinTools({ canUseDevice: true });+ const result = buildAllowedBuiltinTools({+ canUseDevice: true,+ supportedDeviceTools: [AuvManifest.identifier],+ });const ids = result.map((t) => t.identifier);expect(ids).toContain(LocalSystemManifest.identifier);+ expect(ids).toContain(AuvManifest.identifier);});it('strips only remote-device when deviceLocked=true — local-system stays for the routed device', () => {const result = buildAllowedBuiltinTools({canUseDevice: true,+ supportedDeviceTools: [AuvManifest.identifier],deviceLocked: true,});const ids = result.map((t) => t.identifier);expect(ids).not.toContain(RemoteDeviceManifest.identifier);expect(ids).toContain(LocalSystemManifest.identifier);+ expect(ids).toContain(AuvManifest.identifier);});it('keeps remote-device when deviceLocked is omitted', () => {- const result = buildAllowedBuiltinTools({ canUseDevice: true });+ const result = buildAllowedBuiltinTools({+ canUseDevice: true,+ supportedDeviceTools: [AuvManifest.identifier],+ });const ids = result.map((t) => t.identifier);expect(ids).toContain(RemoteDeviceManifest.identifier);});diff --git a/apps/server/src/services/aiAgent/deviceToolRegistry.ts b/apps/server/src/services/aiAgent/deviceToolRegistry.tsindex 2efb345dc80..239dd10ef28 100644--- a/apps/server/src/services/aiAgent/deviceToolRegistry.ts+++ b/apps/server/src/services/aiAgent/deviceToolRegistry.ts@@ -19,6 +19,7 @@* because the manifest was still resolvable in the engine even when* the rule-layer gate denied it).*/+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { BrowserManifest } from '@lobechat/builtin-tool-browser';import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';@@ -28,6 +29,7 @@ export const DEVICE_TOOL_MANIFESTS = [LocalSystemManifest,RemoteDeviceManifest,BrowserManifest,+ AuvManifest,] as const;export const DEVICE_TOOL_IDENTIFIERS: ReadonlySet<string> = new Set(@@ -73,6 +75,8 @@ export interface AllowedBuiltinToolsParams {* `disableLocalSystem?: boolean` param through don't need to coerce.*/disableLocalSystem?: boolean;+ /** Gateway callers pass reported capabilities or [] for older clients; omitted for standalone client execution. */+ supportedDeviceTools?: readonly string[];}/**@@ -87,10 +91,20 @@ export interface AllowedBuiltinToolsParams {* here is the only reliable enforcement point.*/export const buildAllowedBuiltinTools = (params: AllowedBuiltinToolsParams) => {- const { canUseDevice, deviceLocked, disableLocalSystem } = params;+ const { canUseDevice, deviceLocked, disableLocalSystem, supportedDeviceTools } = params;return builtinTools.filter((tool) => {- if (disableLocalSystem && tool.identifier === LocalSystemManifest.identifier) {+ if (+ tool.identifier === AuvManifest.identifier &&+ supportedDeviceTools !== undefined &&+ !supportedDeviceTools.includes(tool.identifier)+ )+ return false;+ if (+ disableLocalSystem &&+ (tool.identifier === LocalSystemManifest.identifier ||+ tool.identifier === AuvManifest.identifier)+ ) {return false;}if (!canUseDevice && DEVICE_TOOL_IDENTIFIERS.has(tool.identifier)) {diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex 72d6e3e5af8..ec90eceb5fc 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -1,3 +1,4 @@+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { GoalIdentifier, isGoalPrompt } from '@lobechat/builtin-tool-goal';import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';@@ -745,6 +746,19 @@ export const discoverTools = async (});}+ // Opt-in capability from the existing system-info RPC. Older desktop and CLI+ // clients omit it, so they must never receive the new Computer Use manifest.+ const supportedDeviceTools =+ activeDeviceId && canUseDevice && !disableLocalSystem+ ? (+ await deviceGateway.queryDeviceSystemInfo(+ deps.userId,+ activeDeviceId,+ activeDeviceScope === 'workspace' ? deps.workspaceId : undefined,+ )+ )?.supportedTools+ : undefined;+// Resolve the operation's group context ONCE here and snapshot it into op// metadata below — the per-step context engine reads it back without a DB// lookup, mirroring agentConfig/botContext. The same roster fetch also@@ -811,6 +825,7 @@ export const discoverTools = async (boundDeviceId,deviceOnline,gatewayConfigured: true,+ supportedTools: supportedDeviceTools,}: undefined,disableLocalSystem,@@ -861,7 +876,7 @@ export const discoverTools = async (: [...new Set([...agentPlugins,- ...(disableLocalSystem ? [] : [LocalSystemManifest.identifier]),+ ...(disableLocalSystem ? [] : [LocalSystemManifest.identifier, AuvManifest.identifier]),RemoteDeviceManifest.identifier,// Include LobeHub Skills and Composio tools so they are passed to generateToolsDetailed...activeLobehubSkillManifests.map((m) => m.identifier),@@ -903,6 +918,12 @@ export const discoverTools = async (const isManifestIngestAllowed = (identifier: string): boolean => {if (exclusivePluginIds && !exclusivePluginIds.includes(identifier)) return false;if (disabledPluginIdSet.has(identifier)) return false;+ if (+ gatewayConfigured &&+ identifier === AuvManifest.identifier &&+ !supportedDeviceTools?.includes(identifier)+ )+ return false;if (!canUseDevice && isDeviceToolIdentifier(identifier)) return false;if (deviceLocked && REMOTE_DEVICE_TOOL_IDENTIFIERS.has(identifier)) return false;return true;@@ -923,6 +944,7 @@ export const discoverTools = async (canUseDevice,deviceLocked,disableLocalSystem,+ supportedDeviceTools: gatewayConfigured ? (supportedDeviceTools ?? []) : undefined,});// Effective runtimeMode from the plan's resolved target — same value the// engine derives, single derivation point.@@ -948,6 +970,7 @@ export const discoverTools = async (// executor marking below, and the desktop client owns the tool gate.const stripDeviceTools = gatewayConfigured && !deviceCapable;if (stripDeviceTools) {+ delete toolManifestMap[AuvManifest.identifier];delete toolManifestMap[RemoteDeviceManifest.identifier];delete toolManifestMap[LocalSystemManifest.identifier];}@@ -963,21 +986,23 @@ export const discoverTools = async (}}- // lobe-local-system has `discoverable: isDesktop` in builtinTools, which- // evaluates to false on the Node.js server side, so it never enters the- // loop above. Explicitly inject it only when the device gateway is+ // Local System and AUV have `discoverable: isDesktop` in builtinTools,+ // which evaluates to false on the Node.js server side, so they never enter+ // the loop above. Explicitly inject them only when the device gateway is// configured AND the plan's target is 'local' — skip for sandbox/none// targets to avoid leaking local-system into non-local sessions. (The// plan already degrades to `none` when device access is denied, so no// separate `canUseDevice` check is needed here.)- if (- !disableLocalSystem &&- isManifestIngestAllowed(LocalSystemManifest.identifier) &&- gatewayConfigured &&- agentRuntimeMode === 'local' &&- !toolManifestMap[LocalSystemManifest.identifier]- ) {- toolManifestMap[LocalSystemManifest.identifier] = LocalSystemManifest as LobeToolManifest;+ for (const manifest of [LocalSystemManifest, AuvManifest]) {+ if (+ !disableLocalSystem &&+ isManifestIngestAllowed(manifest.identifier) &&+ gatewayConfigured &&+ agentRuntimeMode === 'local' &&+ !toolManifestMap[manifest.identifier]+ ) {+ toolManifestMap[manifest.identifier] = manifest as LobeToolManifest;+ }}// Include lobehub skill and composio manifests for activator discovery.diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.tsnew file mode 100644index 00000000000..b877062e76e--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts@@ -0,0 +1,77 @@+import { AuvApiName, AuvIdentifier } from '@lobechat/builtin-tool-auv';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { type ToolExecutionContext } from '../../types';++const executeToolCallMock = vi.fn();+const queryDeviceSystemInfoMock = vi.fn();+vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ queryDeviceSystemInfo: (...args: unknown[]) => queryDeviceSystemInfoMock(...args),+ executeToolCall: (...args: unknown[]) => executeToolCallMock(...args),+ },+}));++const { auvRuntime } = await import('../auv');++describe('auvRuntime', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ queryDeviceSystemInfoMock.mockResolvedValue({ supportedTools: [AuvIdentifier] });+ });++ it('requires a user and active device', () => {+ expect(() => auvRuntime.factory({ activeDeviceId: 'device-1', toolManifestMap: {} })).toThrow(+ 'userId is required for AUV device proxy execution',+ );+ expect(() => auvRuntime.factory({ toolManifestMap: {}, userId: 'user-1' })).toThrow(+ 'activeDeviceId is required for AUV device proxy execution',+ );+ });++ it('rejects old clients before forwarding a tool call', async () => {+ queryDeviceSystemInfoMock.mockResolvedValueOnce({ arch: 'arm64' });+ const runtime = auvRuntime.factory({+ userId: 'user-1',+ activeDeviceId: 'device-1',+ toolManifestMap: {},+ });+ await expect(runtime.runCommand({ argv: ['invoke', 'display.list'] })).rejects.toThrow(+ 'does not support Computer Use',+ );+ expect(executeToolCallMock).not.toHaveBeenCalled();+ });++ it('proxies runCommand to the active desktop device', async () => {+ const context: ToolExecutionContext = {+ activeDeviceId: 'device-1',+ operationId: 'operation-1',+ toolManifestMap: {},+ userId: 'user-1',+ workspaceId: 'workspace-1',+ };+ const args = { argv: ['invoke', 'display.capture'] };+ const expected = { content: 'ok', success: true };+ executeToolCallMock.mockResolvedValue(expected);++ const runtime = auvRuntime.factory(context);+ const result = await runtime.runCommand(args);++ expect(auvRuntime.identifier).toBe(AuvIdentifier);+ expect(executeToolCallMock).toHaveBeenCalledWith(+ {+ deviceId: 'device-1',+ operationId: 'operation-1',+ userId: 'user-1',+ workspaceId: 'workspace-1',+ },+ {+ apiName: AuvApiName.runCommand,+ arguments: JSON.stringify(args),+ identifier: AuvIdentifier,+ },+ undefined,+ );+ expect(result).toEqual(expected);+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts b/apps/server/src/services/toolExecution/serverRuntimes/auv.tsnew file mode 100644index 00000000000..30c96878b98--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/auv.ts@@ -0,0 +1,65 @@+import { AuvApiName, AuvIdentifier } from '@lobechat/builtin-tool-auv';++import { deviceGateway } from '@/server/services/deviceGateway';++import { resolveRunWorkspaceId } from './resolveWorkspaceScope';+import { type ServerRuntimeRegistration } from './types';++export const auvRuntime: ServerRuntimeRegistration = {+ factory: (context) => {+ if (!context.userId) throw new Error('userId is required for AUV device proxy execution');+ if (!context.activeDeviceId) {+ throw new Error('activeDeviceId is required for AUV device proxy execution');+ }++ let workspaceIdPromise: Promise<string | undefined> | undefined;+ const getDeviceWorkspaceId = () => (workspaceIdPromise ??= resolveRunWorkspaceId(context));++ return {+ /**+ * Proxies one typed AUV CLI command to the active desktop device.+ *+ * Triggering workflow:+ *+ * `BuiltinToolsExecutor.execute`+ * -> `lobe-computer-use/runCommand`+ * -> {@link deviceGateway.executeToolCall}+ *+ * Upstream:+ * - Server-side builtin tool execution for `lobe-computer-use/runCommand`+ *+ * Downstream:+ * - {@link deviceGateway.queryDeviceSystemInfo}+ * - {@link deviceGateway.executeToolCall}+ */+ runCommand: async (args: unknown) => {+ const workspaceId = await getDeviceWorkspaceId();+ const systemInfo = await deviceGateway.queryDeviceSystemInfo(+ context.userId!,+ context.activeDeviceId!,+ workspaceId,+ );+ if (!systemInfo?.supportedTools?.includes(AuvIdentifier)) {+ throw new Error(+ 'The selected device does not support Computer Use. Update the desktop app and reconnect.',+ );+ }+ return deviceGateway.executeToolCall(+ {+ deviceId: context.activeDeviceId!,+ operationId: context.operationId,+ userId: context.userId!,+ workspaceId,+ },+ {+ apiName: AuvApiName.runCommand,+ arguments: JSON.stringify(args ?? {}),+ identifier: AuvIdentifier,+ },+ context.executionTimeoutMs,+ );+ },+ };+ },+ identifier: AuvIdentifier,+};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.tsindex 32370fe59a0..31975916651 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts@@ -17,6 +17,7 @@ import { agentSignalFeedbackIntentRuntime } from './agentSignalFeedbackIntent';import { agentSignalReflectionRuntime } from './agentSignalReflection';import { agentSignalReviewRuntime } from './agentSignalReview';import { agentSignalSkillManagementRuntime } from './agentSignalSkillManagement';+import { auvRuntime } from './auv';import { briefRuntime } from './brief';import { browserRuntime } from './browser';import { calculatorRuntime } from './calculator';@@ -63,6 +64,7 @@ const registerRuntimes = (runtimes: ServerRuntimeRegistration[]) => {// Register all server runtimesregisterRuntimes([acceptanceEvidenceRuntime,+ auvRuntime,agentBuilderRuntime,webBrowsingRuntime,cloudSandboxRuntime,diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex b8c7de98b93..2044d7c903b 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -248,6 +248,24 @@"builtins.lobe-cloud-sandbox.apiName.writeLocalFile": "Write file","builtins.lobe-cloud-sandbox.inspector.noResults": "No results","builtins.lobe-cloud-sandbox.title": "Cloud Sandbox",+ "builtins.lobe-computer-use.apiName.runCommand": "Use computer",+ "builtins.lobe-computer-use.inspector.capture": "Capture screen",+ "builtins.lobe-computer-use.inspector.capture.loading": "Capturing screen…",+ "builtins.lobe-computer-use.inspector.focus": "Focus text field",+ "builtins.lobe-computer-use.inspector.focus.loading": "Focusing text field…",+ "builtins.lobe-computer-use.inspector.help": "View command help",+ "builtins.lobe-computer-use.inspector.help.loading": "Viewing command help…",+ "builtins.lobe-computer-use.inspector.input": "Enter text",+ "builtins.lobe-computer-use.inspector.input.loading": "Entering text…",+ "builtins.lobe-computer-use.inspector.inspect": "Inspect computer",+ "builtins.lobe-computer-use.inspector.inspect.loading": "Inspecting computer…",+ "builtins.lobe-computer-use.inspector.keyboard": "Use keyboard",+ "builtins.lobe-computer-use.inspector.keyboard.loading": "Using keyboard…",+ "builtins.lobe-computer-use.inspector.operate": "Use computer",+ "builtins.lobe-computer-use.inspector.operate.loading": "Using computer…",+ "builtins.lobe-computer-use.inspector.preview": "Check computer action",+ "builtins.lobe-computer-use.inspector.preview.loading": "Checking computer action…",+ "builtins.lobe-computer-use.title": "Computer Use","builtins.lobe-goal.apiName.createGoal": "Start goal","builtins.lobe-group-agent-builder.apiName.batchCreateAgents": "Batch create agents","builtins.lobe-group-agent-builder.apiName.createAgent": "Create agent",@@ -340,6 +358,8 @@"builtins.lobe-local-system.apiName.writeLocalFile": "Write file","builtins.lobe-local-system.inspector.noResults": "No results","builtins.lobe-local-system.inspector.rename.result": "<old>{{oldName}}</old> → <new>{{newName}}</new>",+ "builtins.lobe-local-system.inspector.viewImage": "View image",+ "builtins.lobe-local-system.inspector.viewImage.loading": "Viewing image…","builtins.lobe-local-system.title": "Local System","builtins.lobe-notebook.actions.collapse": "Collapse","builtins.lobe-notebook.actions.copy": "Copy",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex f63fe987fc5..ccbcb06430e 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1490,6 +1490,8 @@"tools.builtins.lobe-cloud-sandbox.description": "Execute code, run commands, and manage files in a secure cloud environment","tools.builtins.lobe-cloud-sandbox.readme": "Execute Python, JavaScript, and TypeScript code in an isolated cloud environment. Run shell commands, manage files, search content with regex, and export results securely.","tools.builtins.lobe-cloud-sandbox.title": "Cloud Sandbox",+ "tools.builtins.lobe-computer-use.description": "Use desktop applications, interact with controls, and capture the screen.",+ "tools.builtins.lobe-computer-use.title": "Computer Use","tools.builtins.lobe-creds.description": "Manage user credentials for authentication, environment variable injection, and API verification — handle API keys, OAuth tokens, and secrets for third-party integrations.","tools.builtins.lobe-creds.title": "Credentials","tools.builtins.lobe-group-agent-builder.description": "Configure group metadata, members, and shared content for multi-agent groups",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex d0bf21af153..e9b6a022ac5 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -248,6 +248,24 @@"builtins.lobe-cloud-sandbox.apiName.writeLocalFile": "写入文件","builtins.lobe-cloud-sandbox.inspector.noResults": "无结果","builtins.lobe-cloud-sandbox.title": "云端沙盒",+ "builtins.lobe-computer-use.apiName.runCommand": "操作电脑",+ "builtins.lobe-computer-use.inspector.capture": "截取屏幕",+ "builtins.lobe-computer-use.inspector.capture.loading": "截取屏幕中…",+ "builtins.lobe-computer-use.inspector.focus": "聚焦输入框",+ "builtins.lobe-computer-use.inspector.focus.loading": "聚焦输入框中…",+ "builtins.lobe-computer-use.inspector.help": "查看命令帮助",+ "builtins.lobe-computer-use.inspector.help.loading": "查看命令帮助中…",+ "builtins.lobe-computer-use.inspector.input": "输入内容",+ "builtins.lobe-computer-use.inspector.input.loading": "输入内容中…",+ "builtins.lobe-computer-use.inspector.inspect": "查看电脑状态",+ "builtins.lobe-computer-use.inspector.inspect.loading": "查看电脑状态中…",+ "builtins.lobe-computer-use.inspector.keyboard": "操作键盘",+ "builtins.lobe-computer-use.inspector.keyboard.loading": "操作键盘中…",+ "builtins.lobe-computer-use.inspector.operate": "操作电脑",+ "builtins.lobe-computer-use.inspector.operate.loading": "操作电脑中…",+ "builtins.lobe-computer-use.inspector.preview": "检查电脑操作",+ "builtins.lobe-computer-use.inspector.preview.loading": "检查电脑操作中…",+ "builtins.lobe-computer-use.title": "使用电脑","builtins.lobe-goal.apiName.createGoal": "启动目标","builtins.lobe-group-agent-builder.apiName.batchCreateAgents": "批量创建 Agent","builtins.lobe-group-agent-builder.apiName.createAgent": "创建助理",@@ -340,6 +358,8 @@"builtins.lobe-local-system.apiName.writeLocalFile": "写入文件","builtins.lobe-local-system.inspector.noResults": "无结果","builtins.lobe-local-system.inspector.rename.result": "<old>{{oldName}}</old> → <new>{{newName}}</new>",+ "builtins.lobe-local-system.inspector.viewImage": "查看图片",+ "builtins.lobe-local-system.inspector.viewImage.loading": "查看图片中…","builtins.lobe-local-system.title": "本地系统","builtins.lobe-notebook.actions.collapse": "收起","builtins.lobe-notebook.actions.copy": "复制",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex d68f4401352..a4a7e845e6d 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1490,6 +1490,8 @@"tools.builtins.lobe-cloud-sandbox.description": "在安全的云端环境中执行代码、运行命令和管理文件","tools.builtins.lobe-cloud-sandbox.readme": "在隔离的云端环境中执行 Python、JavaScript 和 TypeScript 代码。运行 Shell 命令、管理文件、使用正则搜索内容并安全导出结果。","tools.builtins.lobe-cloud-sandbox.title": "云沙盒",+ "tools.builtins.lobe-computer-use.description": "使用桌面应用、操作控件和截取屏幕。",+ "tools.builtins.lobe-computer-use.title": "使用电脑","tools.builtins.lobe-creds.description": "管理用于身份验证、环境变量注入和 API 调用的用户凭据 — 处理 API 密钥、OAuth 令牌以及第三方集成所需的密钥。","tools.builtins.lobe-creds.title": "凭据管理","tools.builtins.lobe-group-agent-builder.description": "配置群组的元信息、成员和共享内容,用于多助手群组",diff --git a/package.json b/package.jsonindex 441e09092c0..c9eace66909 100644--- a/package.json+++ b/package.json@@ -237,6 +237,7 @@"@lobechat/builtin-tool-agent-documents": "workspace:*","@lobechat/builtin-tool-agent-management": "workspace:*","@lobechat/builtin-tool-agent-signal": "workspace:*",+ "@lobechat/builtin-tool-auv": "workspace:*","@lobechat/builtin-tool-brief": "workspace:*","@lobechat/builtin-tool-browser": "workspace:*","@lobechat/builtin-tool-calculator": "workspace:*",diff --git a/packages/builtin-tool-auv/README.md b/packages/builtin-tool-auv/README.mdnew file mode 100644index 00000000000..4e49e9f8d0c--- /dev/null+++ b/packages/builtin-tool-auv/README.md@@ -0,0 +1,73 @@+# Computer Use builtin tool++Provides `lobe-computer-use/runCommand` for typed native computer commands on the active desktop device.++## Activation++Computer Use is available on demand through an active desktop device. By default it is not loaded in the initial tool set.+Explicit user pins and tools already activated in the conversation retain their existing behavior.+When a task needs native application controls, mouse/keyboard input, or screen capture,+the agent calls `lobe-activator.activateTools` with `identifiers: ["lobe-computer-use"]`+and a short `reason`. The next model call receives the API schema and operation guidance.+Ordinary conversation, web research, and file or shell work do not need this tool.++Web conversations can activate Computer Use when their execution target is a connected+desktop that reports support. A browser alone cannot execute native commands. Both the+Gateway route and direct Electron client execution retain their existing device gates.+Tool activation does not activate an application or verify a UI operation.++## Usage++Pass CLI arguments after the executable name, for example:++```json+{ "argv": ["invoke", "display.list"], "reasoning": "Find the screen to inspect" }+```++`reasoning` is an optional, brief purpose in the user's language. It is displayed in the+inspector and is never a CLI argument.+The desktop service owns the AUV connection and executes the command over private IPC.+Use `invoke --help` to discover commands. Image artifact paths can be opened with Local System+`readFile`.++The package root exports the manifest and types. The `/client` entry exports the inspector;+`/client/executor` exports desktop execution wiring. The inspector uses the shared command header+and accepts both final and streaming arguments. The enclosing chat header handles execution status. Mouse, keyboard, text, capture,+inspection, help, and dry-run calls get action-specific icons and labels. Active calls use+progress wording; completed and failed calls use neutral action labels, without claiming+that the intended UI effect was verified. Reasoning takes precedence over the command chip;+full argv remains in tool details. Computer Use and image-reading inspectors also+render in collapsed chat rows so their action labels are visible by default.++## When to use++Use Computer Use for native display, application, window, and input operations supported by the active device.+Preview command headers and lifecycle states in the Dev Dock's Render Gallery under Computer Use.++## When not to use++Use Local System for shell commands or file operations. AUV does not accept shell syntax and needs+a desktop client that supports its runtime.++The public identifier is `lobe-computer-use`; the private package and desktop service keep+the AUV backend name. Client, server, and Gateway routing use the new identifier. A read-only inspector+alias preserves historical `lobe-auv` messages; it does not enable old execution requests. Local+System image reads have a separate viewing label, including screenshot artifacts. They+are called images because the read-file result does not identify screenshot provenance.++## Runtime and compatibility++Desktop ships matching `@auv-js/cli` and `@auv-js/sdk` 0.0.16. The existing device+system-info response advertises `supportedTools: ['lobe-computer-use']`; the server+filters discovery/activation and checks again before forwarding a call. Older+Gateway clients omit this field and do not receive Computer Use. Standalone Electron+retains its existing in-process client execution path. Capability-query failures+also disable it. No gateway protocol migration or database migration is required.++`runCommand` returns `{ argv, exitCode, output, stderr? }`. `output` preserves AUV's+parsed JSON, including structured failures and artifacts on nonzero exits; help or+non-JSON diagnostics remain text. Both local and Gateway tool results set `success`+from `exitCode === 0`. Spawn and timeout errors remain host execution errors.+An exit code of zero does not verify the intended UI effect: preserve AUV's+`succeeded`, `verified`, and focus metadata and inspect the resulting application+state when semantic completion matters. The host does not retry input operations.diff --git a/packages/builtin-tool-auv/package.json b/packages/builtin-tool-auv/package.jsonnew file mode 100644index 00000000000..96e28f5ed96--- /dev/null+++ b/packages/builtin-tool-auv/package.json@@ -0,0 +1,21 @@+{+ "name": "@lobechat/builtin-tool-auv",+ "version": "1.0.0",+ "private": true,+ "exports": {+ ".": "./src/index.ts",+ "./client": "./src/client/index.ts",+ "./client/executor": "./src/client/executor/index.ts"+ },+ "main": "./src/index.ts",+ "dependencies": {+ "@lobechat/shared-tool-ui": "workspace:*"+ },+ "devDependencies": {+ "@lobechat/types": "workspace:*"+ },+ "peerDependencies": {+ "lucide-react": "*",+ "react": "*"+ }+}diff --git a/packages/builtin-tool-auv/src/client/Inspector/index.ts b/packages/builtin-tool-auv/src/client/Inspector/index.tsnew file mode 100644index 00000000000..3cf22a28077--- /dev/null+++ b/packages/builtin-tool-auv/src/client/Inspector/index.ts@@ -0,0 +1,7 @@+import { AuvApiName } from '../../types';+import { AuvRunCommandInspector } from './runCommand';++/** AUV command headers keyed by the stable builtin API name. */+export const AuvInspectors = {+ [AuvApiName.runCommand]: AuvRunCommandInspector,+};diff --git a/packages/builtin-tool-auv/src/client/Inspector/runCommand.tsx b/packages/builtin-tool-auv/src/client/Inspector/runCommand.tsxnew file mode 100644index 00000000000..2b85b8a172f--- /dev/null+++ b/packages/builtin-tool-auv/src/client/Inspector/runCommand.tsx@@ -0,0 +1,86 @@+'use client';++import { RunCommandInspector } from '@lobechat/shared-tool-ui/inspectors';+import type { BuiltinInspectorProps } from '@lobechat/types';+import {+ BookOpen,+ ClipboardCheck,+ Focus,+ Keyboard,+ Monitor,+ MousePointer2,+ ScanLine,+ TextCursorInput,+} from 'lucide-react';++import type { AuvRunCommandParams } from '../../types';++const activityIcons = {+ capture: ScanLine,+ focus: Focus,+ help: BookOpen,+ input: TextCursorInput,+ inspect: Monitor,+ keyboard: Keyboard,+ operate: MousePointer2,+ preview: ClipboardCheck,+};++// Presentation only: this does not validate argv or claim command support.+// Help/dry-run describe inspection even when the named command would send input.+function getActivity(argv: string[] = []): keyof typeof activityIcons {+ const separator = argv.indexOf('--');+ const options = separator < 0 ? argv : argv.slice(0, separator);+ if (options.includes('--help') || options.includes('-h')) return 'help';+ if (options.includes('--dry-run')) return 'preview';+ const command = argv[0] === 'invoke' ? (argv[1] ?? '') : '';+ if (['display.capture', 'window.capture', 'screen.captureRegion'].includes(command))+ return 'capture';+ if (['input.typeText', 'input.pasteText'].includes(command)) return 'input';+ if (['input.key', 'input.keys', 'input.keyboard'].includes(command)) return 'keyboard';+ if (['input.focusText', 'input.axFocusText'].includes(command)) return 'focus';+ if (+ [+ 'display.list',+ 'window.list',+ 'app.probePermissions',+ 'window.findText',+ 'window.waitForText',+ 'screen.findText',+ 'screen.waitForText',+ ].includes(command)+ )+ return 'inspect';+ return 'operate';+}++/**+ * Displays a Computer Use action through the shared command inspector.+ * Accepts final/streaming argv and a brief purpose; the enclosing tool header+ * owns failures. A completed label does not claim the UI effect was verified.+ */+export const AuvRunCommandInspector = ({+ args,+ partialArgs,+ pluginState: _pluginState,+ ...props+}: BuiltinInspectorProps<Partial<AuvRunCommandParams>, unknown>) => {+ const argv = args?.argv ?? partialArgs?.argv;+ const activity = getActivity(argv);+ const reasoning = args?.reasoning?.trim() || partialArgs?.reasoning?.trim();+ // Display text only. Preserve whitespace and empty arguments in the fallback;+ // the original tool arguments remain available in the expanded tool details.+ const command = argv?.length+ ? `auv ${argv.map((argument) => (/^[\w./:=+-]+$/.test(argument) ? argument : JSON.stringify(argument))).join(' ')}`+ : '';+ const loading = props.isArgumentsStreaming || props.isLoading;++ return (+ <RunCommandInspector+ {...props}+ args={{ command, description: reasoning }}+ icon={activityIcons[activity]}+ translationKey={`builtins.lobe-computer-use.inspector.${activity}${loading ? '.loading' : ''}`}+ />+ );+};diff --git a/packages/builtin-tool-auv/src/client/executor/index.test.ts b/packages/builtin-tool-auv/src/client/executor/index.test.tsnew file mode 100644index 00000000000..89e5fb91d46--- /dev/null+++ b/packages/builtin-tool-auv/src/client/executor/index.test.ts@@ -0,0 +1,60 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AuvApiName } from '../../types';+import { auvExecutor } from './index';++const { runCommandMock } = vi.hoisted(() => ({+ runCommandMock: vi.fn(),+}));++vi.mock('@/services/electron/auv', () => ({+ electronAuvService: {+ runCommand: runCommandMock,+ },+}));++describe('auvExecutor', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('forwards a typed CLI invocation through Electron IPC', async () => {+ const params = { argv: ['invoke', 'display.capture'] };+ const invocation = {+ argv: params.argv,+ exitCode: 0,+ output: { artifacts: [{ file_path: '/tmp/capture.png' }] },+ };+ runCommandMock.mockResolvedValue(invocation);++ const result = await auvExecutor.invoke(AuvApiName.runCommand, params, {+ messageId: 'test-message',+ });++ expect(runCommandMock).toHaveBeenCalledWith(params);+ expect(result).toEqual({+ content: JSON.stringify(invocation),+ state: invocation,+ success: true,+ });+ });+ it('preserves a nonzero CLI result as a failed tool call', async () => {+ const invocation = {+ argv: ['invoke', 'input.typeText'],+ exitCode: 1,+ output: { command_id: 'input.typeText', failure: { kind: 'target_resolution' } },+ stderr: 'target not found',+ };+ runCommandMock.mockResolvedValueOnce(invocation);+ const result = await auvExecutor.invoke(+ AuvApiName.runCommand,+ { argv: invocation.argv },+ { messageId: 'failure' },+ );+ expect(result).toMatchObject({+ content: JSON.stringify(invocation),+ state: invocation,+ success: false,+ });+ });+});diff --git a/packages/builtin-tool-auv/src/client/executor/index.ts b/packages/builtin-tool-auv/src/client/executor/index.tsnew file mode 100644index 00000000000..58842b92975--- /dev/null+++ b/packages/builtin-tool-auv/src/client/executor/index.ts@@ -0,0 +1,41 @@+import type { BuiltinToolResult } from '@lobechat/types';+import { BaseExecutor } from '@lobechat/types';++import { AuvApiName, AuvIdentifier, type AuvRunCommandParams } from '../../types';++class AuvExecutor extends BaseExecutor<typeof AuvApiName> {+ readonly identifier = AuvIdentifier;+ protected readonly apiEnum = AuvApiName;++ /**+ * Triggering workflow: {@link BaseExecutor.invoke} -> `runCommand`+ * -> Electron `auv.runCommand`; preserve CLI failures in the tool result.+ */+ runCommand = async (params: AuvRunCommandParams): Promise<BuiltinToolResult> => {+ try {+ const { electronAuvService } = await import('@/services/electron/auv');+ const result = await electronAuvService.runCommand(params);+ return {+ content: JSON.stringify(result),+ ...(result.exitCode !== 0 && {+ error: {+ body: result.output,+ message: result.stderr || `Computer Use exited with code ${result.exitCode}`,+ type: 'PluginServerError',+ },+ }),+ state: result,+ success: result.exitCode === 0,+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ return {+ content: message,+ error: { body: error, message, type: 'PluginServerError' },+ success: false,+ };+ }+ };+}++export const auvExecutor = new AuvExecutor();diff --git a/packages/builtin-tool-auv/src/client/index.ts b/packages/builtin-tool-auv/src/client/index.tsnew file mode 100644index 00000000000..644c998c8f1--- /dev/null+++ b/packages/builtin-tool-auv/src/client/index.ts@@ -0,0 +1,3 @@+export { AuvManifest } from '../manifest';+export * from '../types';+export { AuvInspectors } from './Inspector';diff --git a/packages/builtin-tool-auv/src/index.ts b/packages/builtin-tool-auv/src/index.tsnew file mode 100644index 00000000000..378a1ca074b--- /dev/null+++ b/packages/builtin-tool-auv/src/index.ts@@ -0,0 +1,3 @@+export { AuvManifest } from './manifest';+export { systemPrompt } from './systemRole';+export * from './types';diff --git a/packages/builtin-tool-auv/src/manifest.ts b/packages/builtin-tool-auv/src/manifest.tsnew file mode 100644index 00000000000..62949822ca5--- /dev/null+++ b/packages/builtin-tool-auv/src/manifest.ts@@ -0,0 +1,46 @@+import { type BuiltinToolManifest } from '@lobechat/types';++import { systemPrompt } from './systemRole';+import { AuvApiName, AuvIdentifier } from './types';++export const AuvManifest: BuiltinToolManifest = {+ executors: ['client', 'server'],+ api: [+ {+ defaultTimeoutMs: 120_000,+ description:+ 'Use the computer by running a typed AUV CLI invoke command on the active desktop device. Pass arguments after the auv executable, for example ["invoke", "display.list"]. Use ["invoke", "--help"] or ["invoke", "display.capture", "--help"] to inspect available commands and options. Results include exitCode and parsed output, preserving structured failures on nonzero exits and artifacts[].file_path for captured images. A zero exit code does not verify the intended UI effect.',+ humanIntervention: 'required',+ name: AuvApiName.runCommand,+ parameters: {+ properties: {+ reasoning: {+ description:+ 'Briefly describe the purpose of this action for the user, in their language. This is displayed in the tool inspector and is not a CLI argument.',+ type: 'string',+ },+ argv: {+ description:+ 'Arguments after the auv executable. The first argument must be "invoke". Do not include shell syntax or the executable name.',+ items: { type: 'string' },+ minItems: 2,+ type: 'array',+ },+ },+ required: ['argv'],+ type: 'object',+ },+ },+ ],+ identifier: AuvIdentifier,+ meta: {+ avatar: '🖱️',+ description:+ 'Uses the active desktop device, including from Web through a connected device. Activate lobe-computer-use with activateTools only when the task needs native application controls, mouse or keyboard input, or screenshots. Do not activate for ordinary conversation, web research, or file and shell operations.',+ readme:+ 'Interact with desktop applications, use mouse and keyboard controls, enter text, and capture the screen on the active device. View captured images to inspect the result of each step.',+ title: 'Computer Use',+ },+ systemRole: systemPrompt,+ type: 'builtin',+};diff --git a/packages/builtin-tool-auv/src/systemRole.ts b/packages/builtin-tool-auv/src/systemRole.tsnew file mode 100644index 00000000000..0bbfbcd9721--- /dev/null+++ b/packages/builtin-tool-auv/src/systemRole.ts@@ -0,0 +1,9 @@+export const systemPrompt = `Use Computer Use (lobe-computer-use) for native computer interaction and application automation on the active desktop device. This tool is activated on demand for tasks that need application controls, mouse or keyboard input, or screenshots. Stay within the requested task; use dedicated web, file, and shell tools for work that does not require native UI interaction.++- Include a brief reasoning phrase in the user's language describing the immediate purpose of the action. Do not include internal deliberation or put reasoning in argv.+- runCommand receives an argv array after the auv executable. The first argument must be "invoke".+- Use ["invoke", "--help"] to discover commands and ["invoke", "<command>", "--help"] to inspect exact options. Never guess flags.+- Example: ["invoke", "display.list"]. LobeHub adds --json and its private run store automatically.+- Capture commands return artifacts with a local file_path. To actually inspect a returned image, call lobe-local-system readFile with that exact file_path. If image upload is temporarily unavailable, retry readFile once with the same path. Do not infer image contents from capture metadata.+- Do not pass shell syntax, the auv executable name, --store-root, or connection options.+- Treat input, click, typing, activation, media-control, and overlay commands as state-changing computer actions. Verify important effects with a separate read-only observation when possible.`;diff --git a/packages/builtin-tool-auv/src/types.ts b/packages/builtin-tool-auv/src/types.tsnew file mode 100644index 00000000000..03475e3d541--- /dev/null+++ b/packages/builtin-tool-auv/src/types.ts@@ -0,0 +1,14 @@+export const AuvIdentifier = 'lobe-computer-use';++export const AuvApiName = {+ runCommand: 'runCommand',+} as const;++export type AuvApiNameType = (typeof AuvApiName)[keyof typeof AuvApiName];++export interface AuvRunCommandParams {+ /** AUV arguments after the executable name, for example ['invoke', 'display.list']. */+ argv: string[];+ /** Brief user-facing purpose of this action; never interpreted as CLI arguments. */+ reasoning?: string;+}diff --git a/packages/builtin-tool-auv/vitest.config.mts b/packages/builtin-tool-auv/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/builtin-tool-auv/vitest.config.mts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ },+});diff --git a/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsxindex 24620d58f01..55140c74abb 100644--- a/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx+++ b/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx@@ -4,4 +4,5 @@ import { createReadLocalFileInspector } from '@lobechat/shared-tool-ui/inspectorexport const ReadLocalFileInspector = createReadLocalFileInspector('builtins.lobe-local-system.apiName.readLocalFile',+ 'builtins.lobe-local-system.inspector.viewImage',);diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.jsonindex ff3b529bfb1..3065777d917 100644--- a/packages/builtin-tools/package.json+++ b/packages/builtin-tools/package.json@@ -27,6 +27,7 @@"@lobechat/builtin-tool-agent-documents": "workspace:*","@lobechat/builtin-tool-agent-management": "workspace:*","@lobechat/builtin-tool-agent-signal": "workspace:*",+ "@lobechat/builtin-tool-auv": "workspace:*","@lobechat/builtin-tool-brief": "workspace:*","@lobechat/builtin-tool-browser": "workspace:*","@lobechat/builtin-tool-claude-code": "workspace:*",diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex c7d60962cfb..05fc32fcea2 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -9,6 +9,7 @@ import {agentSignalReviewManifest,agentSignalSkillManagementManifest,} from '@lobechat/builtin-tool-agent-signal';+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { BrowserManifest } from '@lobechat/builtin-tool-browser';import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';@@ -37,6 +38,7 @@ export const builtinToolIdentifiers: string[] = [AgentBuilderManifest.identifier,AgentDocumentsManifest.identifier,AgentManagementManifest.identifier,+ AuvManifest.identifier,CalculatorManifest.identifier,CloudSandboxManifest.identifier,CredsManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex a32073de9e3..63b4108b748 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -12,6 +12,7 @@ import {agentSignalReviewManifest,agentSignalSkillManagementManifest,} from '@lobechat/builtin-tool-agent-signal';+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { BriefManifest } from '@lobechat/builtin-tool-brief';import { BrowserManifest } from '@lobechat/builtin-tool-browser';import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';@@ -352,6 +353,13 @@ const builtinToolRegistry: LobeBuiltinTool[] = [manifest: BrowserManifest,type: 'builtin',},+ {+ discoverable: isDesktop,+ hidden: true,+ identifier: AuvManifest.identifier,+ manifest: AuvManifest,+ type: 'builtin',+ },{discoverable: isDesktop,hidden: true,diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.tsindex 6a4273284c6..166b00ec021 100644--- a/packages/builtin-tools/src/register.ts+++ b/packages/builtin-tools/src/register.ts@@ -22,6 +22,7 @@ import {AgentManagementRenders,AgentManagementStreamings,} from '@lobechat/builtin-tool-agent-management/client';+import { AuvIdentifier, AuvInspectors } from '@lobechat/builtin-tool-auv/client';import {BrowserInspectors,BrowserManifest,@@ -262,6 +263,10 @@ export const registerBuiltinToolSurfaces = (): void => {});registerBuiltinInspectors({+ [AuvIdentifier]: AuvInspectors as Record<string, BuiltinInspector>,+ // Read-only alias for messages recorded by the original private desktop PR.+ // New manifests and execution routes only advertise lobe-computer-use.+ 'lobe-auv': AuvInspectors as Record<string, BuiltinInspector>,[AgentBuilderManifest.identifier]: AgentBuilderInspectors as Record<string, BuiltinInspector>,[AgentDocumentsManifest.identifier]: AgentDocumentsInspectors as Record<string,@@ -312,7 +317,7 @@ export const registerBuiltinToolSurfaces = (): void => {[OPENCODE_IDENTIFIER]: heterogeneousCliInspectors,[PI_IDENTIFIER]: heterogeneousCliInspectors,[KIMI_CODE_IDENTIFIER]: KimiCodeInspectors,- codex: CodexInspectors,+ 'codex': CodexInspectors,[GithubIdentifier]: GithubInspectors,[LinearIdentifier]: LinearInspectors,[TwitterIdentifier]: TwitterInspectors,diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex a087b8d11a5..dcb9d504c8f 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -38,6 +38,8 @@ export interface DeviceSystemInfo {homePath: string;musicPath: string;picturesPath: string;+ /** Opt-in tool identifiers supported by this client; absent on older clients. */+ supportedTools?: string[];userDataPath: string;videosPath: string;workingDirectory: string;diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex 81ad5f55e05..785fe42a120 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -1,6 +1,26 @@export default {'arguments.moreParams': '{{count}} params in total','arguments.title': 'Arguments',+ 'builtins.lobe-computer-use.apiName.runCommand': 'Use computer',+ 'builtins.lobe-computer-use.inspector.capture': 'Capture screen',+ 'builtins.lobe-computer-use.inspector.capture.loading': 'Capturing screen…',+ 'builtins.lobe-computer-use.inspector.focus': 'Focus text field',+ 'builtins.lobe-computer-use.inspector.focus.loading': 'Focusing text field…',+ 'builtins.lobe-computer-use.inspector.help': 'View command help',+ 'builtins.lobe-computer-use.inspector.help.loading': 'Viewing command help…',+ 'builtins.lobe-computer-use.inspector.input': 'Enter text',+ 'builtins.lobe-computer-use.inspector.input.loading': 'Entering text…',+ 'builtins.lobe-computer-use.inspector.inspect': 'Inspect computer',+ 'builtins.lobe-computer-use.inspector.inspect.loading': 'Inspecting computer…',+ 'builtins.lobe-computer-use.inspector.keyboard': 'Use keyboard',+ 'builtins.lobe-computer-use.inspector.keyboard.loading': 'Using keyboard…',+ 'builtins.lobe-computer-use.inspector.operate': 'Use computer',+ 'builtins.lobe-computer-use.inspector.operate.loading': 'Using computer…',+ 'builtins.lobe-computer-use.inspector.preview': 'Check computer action',+ 'builtins.lobe-computer-use.inspector.preview.loading': 'Checking computer action…',+ 'builtins.lobe-computer-use.title': 'Computer Use',+ 'builtins.lobe-local-system.inspector.viewImage': 'View image',+ 'builtins.lobe-local-system.inspector.viewImage.loading': 'Viewing image…','builtins.lobe-agent-builder.apiName.getAvailableModels': 'Get available models','builtins.lobe-agent-builder.apiName.getAvailableTools': 'Get available Skills','builtins.lobe-agent-builder.apiName.getConfig': 'Get config',diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex c766d70ee27..3490af29063 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -3470,6 +3470,9 @@ When I am ___, I need ___'tools.builtins.find-skills.description':'Helps users discover and install agent skills when they ask "how do I do X", "find a skill for X", or want to extend capabilities','tools.builtins.find-skills.title': 'Find Skills',+ 'tools.builtins.lobe-computer-use.title': 'Computer Use',+ 'tools.builtins.lobe-computer-use.description':+ 'Use desktop applications, interact with controls, and capture the screen.','tools.builtins.lobe-agent-browser.description':'Browser automation CLI for AI agents. Use when tasks involve website or Electron interaction such as navigation, form filling, clicking, screenshot capture, scraping data, login flows, and end-to-end app testing.','tools.builtins.lobe-agent-browser.title': 'Agent Browser',diff --git a/packages/shared-tool-ui/src/Inspector/ReadLocalFile/index.tsx b/packages/shared-tool-ui/src/Inspector/ReadLocalFile/index.tsxindex 4b742b2c8d7..95ec85d4d90 100644--- a/packages/shared-tool-ui/src/Inspector/ReadLocalFile/index.tsx+++ b/packages/shared-tool-ui/src/Inspector/ReadLocalFile/index.tsx@@ -6,7 +6,7 @@ import { cx } from 'antd-style';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { FilePathDisplay } from '../../components/FilePathDisplay';+import { FilePathDisplay, getFilePathDisplayInfo } from '../../components/FilePathDisplay';import { inspectorTextStyles, shinyTextStyles } from '../../styles';interface ReadFileArgs {@@ -20,9 +20,12 @@ interface ReadFileArgs {startLine?: number;}-export const createReadLocalFileInspector = (translationKey: string) => {+export const createReadLocalFileInspector = (+ translationKey: string,+ imageTranslationKey?: string,+) => {const Inspector = memo<BuiltinInspectorProps<ReadFileArgs, ReadFileState>>(- ({ args, partialArgs, isArgumentsStreaming, isLoading }) => {+ ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {const { t } = useTranslation('plugin');const filePath =@@ -32,7 +35,15 @@ export const createReadLocalFileInspector = (translationKey: string) => {partialArgs?.path ||partialArgs?.filePath ||partialArgs?.file_path ||+ pluginState?.path ||'';+ // File hints let streaming captures display as images; uploaded image state+ // also identifies extensionless files. No screenshot provenance is inferred.+ const isImage = getFilePathDisplayInfo(filePath).isImage || !!pluginState?.images?.length;+ const label =+ imageTranslationKey && isImage+ ? `${imageTranslationKey}${isArgumentsStreaming || isLoading ? '.loading' : ''}`+ : translationKey;const lineRange = useMemo(() => {const source = args || partialArgs;@@ -52,14 +63,14 @@ export const createReadLocalFileInspector = (translationKey: string) => {if (!filePath)return (<div className={inspectorTextStyles.root}>- <span className={shinyTextStyles.shinyText}>{t(translationKey as any)}</span>+ <span className={shinyTextStyles.shinyText}>{t(label as any)}</span></div>);return (<div className={inspectorTextStyles.root}><span className={shinyTextStyles.shinyText} style={{ marginInlineEnd: 6 }}>- {t(translationKey as any)}:+ {t(label as any)}:</span><FilePathDisplay filePath={filePath} /></div>@@ -72,7 +83,7 @@ export const createReadLocalFileInspector = (translationKey: string) => {className={cx(isLoading && shinyTextStyles.shinyText)}style={{ marginInlineEnd: 6 }}>- {t(translationKey as any)}:+ {t(label as any)}:</span><FilePathDisplay filePath={filePath} />{lineRange && <span style={{ marginInlineStart: 4 }}>({lineRange})</span>}diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsxindex a1c5bbf70b8..8c265d4cdd5 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx@@ -1,6 +1,9 @@import type { ActivateToolsState } from '@lobechat/builtin-tool-activator';import { ActivatorApiName, LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';+import { AuvApiName, AuvIdentifier } from '@lobechat/builtin-tool-auv';+import { LocalSystemApiName, LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';import { getBuiltinInspector } from '@lobechat/builtin-tools/inspectors';+import { getFilePathDisplayInfo } from '@lobechat/shared-tool-ui/components';import type { ToolIntervention } from '@lobechat/types';import { safeParseJSON, safeParsePartialJSON } from '@lobechat/utils';import { Flexbox } from '@lobehub/ui';@@ -26,7 +29,8 @@ interface InspectorProps {* Whether the tool detail is expanded. Collapsed rows show the plain* "<action> <keyword>" title; an expanded row restores the tool's own rich* inspector (full command, per-tool chips) since expanding means "show me- * the details".+ * the details". Computer Use and image reads keep their action-specific+ * inspector visible in both states.*/isExpanded?: boolean;/**@@ -91,7 +95,29 @@ const Inspectors = memo<InspectorProps>(// Collapsed rows read as one plain sentence ("<action> <keyword>") so a// finished run scans as prose; expanding a row is an explicit ask for the// details, so it restores the tool's own rich inspector when one exists.- const CustomInspector = isExpanded ? getBuiltinInspector(identifier, apiName) : undefined;+ // Computer Use multiplexes distinct actions behind runCommand; its inspector+ // carries the action/purpose even in the compact row. Image reads likewise+ // need their viewing label instead of the generic read-file title.+ const isComputerUse =+ (identifier === AuvIdentifier || identifier === 'lobe-auv') &&+ apiName === AuvApiName.runCommand;+ const readPath =+ args?.path ||+ args?.filePath ||+ args?.file_path ||+ partialJson?.path ||+ partialJson?.filePath ||+ partialJson?.file_path ||+ result?.state?.path;+ const isImageRead =+ identifier === LocalSystemIdentifier &&+ (apiName === LocalSystemApiName.readFile || apiName === 'readLocalFile') &&+ ((typeof readPath === 'string' && getFilePathDisplayInfo(readPath).isImage) ||+ (Array.isArray(result?.state?.images) && result.state.images.length > 0));+ const CustomInspector =+ isExpanded || isComputerUse || isImageRead+ ? getBuiltinInspector(identifier, apiName)+ : undefined;return (<Flexbox allowShrink horizontal align={'center'} gap={6}>diff --git a/src/features/DevPanel/RenderGallery/fixtures/index.ts b/src/features/DevPanel/RenderGallery/fixtures/index.tsindex 19dcf405528..0801e81d752 100644--- a/src/features/DevPanel/RenderGallery/fixtures/index.ts+++ b/src/features/DevPanel/RenderGallery/fixtures/index.ts@@ -32,6 +32,7 @@ import lobeUserInteraction from './lobe-user-interaction';import lobeUserMemory from './lobe-user-memory';import lobeWebBrowsing from './lobe-web-browsing';import lobeWebOnboarding from './lobe-web-onboarding';+import { lobeAuv } from './lobeAuv';export type { ToolRenderFixture, ToolRenderFixtureVariant } from '../lifecycleMode';@@ -92,6 +93,7 @@ const toolsetModules: ToolsetFixtureModule[] = [lobeAgentBuilder,lobeAgentDocuments,lobeAgentManagement,+ lobeAuv,lobeBrowser,lobeCloudSandbox,lobeGroupAgentBuilder,diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-local-system.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-local-system.tsindex 2428570ffe1..08c5de61f9c 100644--- a/src/features/DevPanel/RenderGallery/fixtures/lobe-local-system.ts+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-local-system.ts@@ -33,18 +33,26 @@ export default defineFixtures({],},}),- readFile: single({- args: { path: '/workspace/src/routes/(main)/devtools/index.tsx' },- pluginState: {- content:- 'export default function DevtoolsPage() {\n return <div>Render preview</div>;\n}\n',- endLine: 3,- fullPath: '/workspace/src/routes/(main)/devtools/index.tsx',- path: 'src/routes/(main)/devtools/index.tsx',- startLine: 1,- totalLines: 3,+ readFile: variants([+ {+ args: { path: '/tmp/capture.png' },+ label: 'View screenshot image',+ partialArgs: { path: '/tmp/capture.png' },},- }),+ {+ args: { path: '/workspace/src/routes/(main)/devtools/index.tsx' },+ label: 'Read source file',+ pluginState: {+ content:+ 'export default function DevtoolsPage() {\n return <div>Render preview</div>;\n}\n',+ endLine: 3,+ fullPath: '/workspace/src/routes/(main)/devtools/index.tsx',+ path: 'src/routes/(main)/devtools/index.tsx',+ startLine: 1,+ totalLines: 3,+ },+ },+ ]),runCommand: single({args: { command: 'bun run type-check' },content: 'Checked 1247 files in 2.3s\nNo type errors found.',diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobeAuv.ts b/src/features/DevPanel/RenderGallery/fixtures/lobeAuv.tsnew file mode 100644index 00000000000..a7b81ebb4c1--- /dev/null+++ b/src/features/DevPanel/RenderGallery/fixtures/lobeAuv.ts@@ -0,0 +1,79 @@+'use client';++import { AuvApiName, AuvIdentifier } from '@lobechat/builtin-tool-auv';++import { defineFixtures, variants } from './_helpers';++/** Computer Use action examples for the gallery's streaming, loading, result, and failure modes. */+export const lobeAuv = defineFixtures({+ identifier: AuvIdentifier,+ fixtures: {+ [AuvApiName.runCommand]: variants([+ {+ args: {+ argv: ['invoke', 'input.clickPoint', '100', '200'],+ reasoning: 'Focus the search field',+ },+ label: 'Mouse action with reasoning',+ partialArgs: { reasoning: 'Focus the search' },+ },+ {+ args: {+ argv: ['invoke', 'input.typeText', "Arielle's Wish"],+ reasoning: 'Enter the song title',+ },+ label: 'Text input',+ },+ {+ args: { argv: ['invoke', 'input.key', 'return'], reasoning: 'Submit the search' },+ label: 'Keyboard action',+ },+ {+ args: { argv: ['invoke', 'display.capture'], reasoning: 'Check the current screen' },+ label: 'Capture screen',+ },+ {+ args: { argv: ['invoke', 'input.key', 'return', '--dry-run'] },+ label: 'Validate without input',+ },+ {+ args: { argv: ['invoke', 'display.list'] },+ label: 'List displays',+ partialArgs: { argv: ['invoke', 'display.'] },+ pluginState: {+ argv: ['invoke', 'display.list', '--json'],+ output: { displays: [{ id: 'display-1', name: 'Built-in display' }] },+ },+ },+ {+ args: { argv: ['invoke', '--help'] },+ label: 'Command help',+ pluginState: { argv: ['invoke', '--help'], output: 'Available commands: display.list' },+ },+ {+ args: {},+ label: 'Waiting for arguments',+ partialArgs: {},+ },+ {+ args: { argv: ['invoke', 'display.capture'] },+ label: 'Capture permission denied',+ pluginError: {+ message: 'Screen recording permission is required to capture this display.',+ type: 'PluginServerError',+ },+ },+ {+ args: {+ argv: [+ 'invoke',+ 'display.capture',+ '--help',+ 'Long argument with spaces and "quotes" to preview clipping inside a narrow tool header.',+ ],+ },+ label: 'Long arguments',+ },+ ]),+ },+});diff --git a/src/features/Settings/skill/features/SkillDetail/localization.test.ts b/src/features/Settings/skill/features/SkillDetail/localization.test.tsindex e20e7741f5b..200f015a0e4 100644--- a/src/features/Settings/skill/features/SkillDetail/localization.test.ts+++ b/src/features/Settings/skill/features/SkillDetail/localization.test.ts@@ -1,6 +1,9 @@+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { type TFunction } from 'i18next';import { describe, expect, it, vi } from 'vitest';+import enUS from '../../../../../../locales/en-US/setting.json';+import zhCN from '../../../../../../locales/zh-CN/setting.json';import { getLocalizedBuiltinSkillDetail, getNoPermissionsTitle } from './localization';const createTranslator = (translations: Record<string, string> = {}) =>@@ -10,6 +13,27 @@ const createTranslator = (translations: Record<string, string> = {}) =>) as unknown as TFunction<'setting'>;describe('SkillDetail localization helpers', () => {+ it.each([+ [enUS, 'Computer Use'],+ [zhCN, '使用电脑'],+ ] as const)(+ 'localizes the Computer Use skill from shipped translations',+ (translations, title) => {+ const result = getLocalizedBuiltinSkillDetail(+ {+ content: AuvManifest.meta.readme ?? '',+ description: AuvManifest.meta.description ?? '',+ identifier: AuvManifest.identifier,+ name: AuvManifest.meta.title,+ source: 'builtin',+ },+ AuvManifest.identifier,+ createTranslator(translations),+ );+ expect(result.title).toBe(title);+ },+ );+it('localizes builtin skill title and description', () => {const t = createTranslator({'tools.builtins.lobe-agent-browser.description': '浏览器自动化命令行工具',diff --git a/src/helpers/toolAvailability.test.ts b/src/helpers/toolAvailability.test.tsindex 10ad2eaf2eb..f281e71f7cc 100644--- a/src/helpers/toolAvailability.test.ts+++ b/src/helpers/toolAvailability.test.ts@@ -49,5 +49,6 @@ describe('toolAvailability', () => {isDesktop: false,}),).toBe(false);+ expect(isToolAvailableInCurrentEnv('lobe-computer-use')).toBe(false);});});diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.tsindex 8e0976ce6ae..e0b283cab7c 100644--- a/src/helpers/toolEngineering/index.test.ts+++ b/src/helpers/toolEngineering/index.test.ts@@ -1,13 +1,27 @@+import { AuvManifest } from '@lobechat/builtin-tool-auv';+import type * as ConstModule from '@lobechat/const';import { type ToolManifest } from '@lobechat/types';import { afterEach, describe, expect, it, vi } from 'vitest';import { createAgentToolsEngine, createToolsEngine, getEnabledTools } from './index';+const desktopEnv = vi.hoisted(() => ({ enabled: false }));+vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<typeof ConstModule>()),+ get isDesktop() {+ return desktopEnv.enabled;+ },+}));+afterEach(() => {+ desktopEnv.enabled = false;+});+// Mock the store and helper dependenciesvi.mock('@/store/tool', () => ({getToolStoreState: () => ({connectors: [],builtinTools: [+ { identifier: AuvManifest.identifier, manifest: AuvManifest, type: 'builtin' as const },{identifier: 'search',manifest: {@@ -168,7 +182,7 @@ vi.mock('@/store/agent/selectors', () => ({agentChatConfigSelectors: {currentChatConfig: () => mockCurrentChatConfig,isCloudSandboxEnabled: () => false,- isLocalSystemEnabled: () => false,+ isLocalSystemEnabled: () => desktopEnv.enabled,isMemoryToolEnabled: () => false,},}));@@ -720,3 +734,35 @@ describe('toolEngineering', () => {});});});++// https://github.com/lobehub/lobehub/pull/19051+describe('Computer Use activation', () => {+ it('loads the native API only after activation in standalone Electron', () => {+ desktopEnv.enabled = true;+ const engine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });+ expect(+ engine.generateToolsDetailed({ model: 'gpt-4', provider: 'openai', toolIds: [] })+ .enabledToolIds,+ ).not.toContain(AuvManifest.identifier);+ expect(+ engine.generateToolsDetailed({+ model: 'gpt-4',+ provider: 'openai',+ toolIds: [AuvManifest.identifier],+ context: { isExplicitActivation: true },+ }).enabledToolIds,+ ).toContain(AuvManifest.identifier);+ });+ it('does not let explicit activation bypass the Web platform restriction', () => {+ desktopEnv.enabled = false;+ const engine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });+ expect(+ engine.generateToolsDetailed({+ model: 'gpt-4',+ provider: 'openai',+ toolIds: [AuvManifest.identifier],+ context: { isExplicitActivation: true },+ }).enabledToolIds,+ ).not.toContain(AuvManifest.identifier);+ });+});diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.tsindex 1f7d05f7e72..117f7844c08 100644--- a/src/helpers/toolEngineering/index.ts+++ b/src/helpers/toolEngineering/index.ts@@ -1,6 +1,7 @@/*** Tools Engineering - Unified tools processing using ToolsEngine*/+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { BrowserManifest } from '@lobechat/builtin-tool-browser';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { ImageGenerationManifest } from '@lobechat/builtin-tool-image-generation';@@ -195,10 +196,13 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =// enableChecker rules) — a plugin, skill, connector, or user-toggleable// builtin tool the agent has explicitly disabled must not be discoverable/// activatable at all, matching the server-side (aiAgent gateway) treatment.- const allManifests =- disabledPluginIds.length === 0- ? combinedManifests- : combinedManifests.filter((m) => !disabledPluginIds.includes(m.identifier));+ // Explicit activation bypasses enable rules; a plain Web client must not+ // acquire the Electron IPC executor. Gateway execution uses the server engine.+ const allManifests = combinedManifests.filter(+ (m) =>+ !disabledPluginIds.includes(m.identifier) &&+ (m.identifier !== AuvManifest.identifier || isToolAvailableInCurrentEnv(m.identifier)),+ );return new ToolsEngine({defaultToolIds,diff --git a/src/helpers/toolFilters.ts b/src/helpers/toolFilters.tsindex d44af3cf3bd..59ccc7d47c3 100644--- a/src/helpers/toolFilters.ts+++ b/src/helpers/toolFilters.ts@@ -2,6 +2,7 @@* Shared tool filtering logic used across both runtime (ToolsEngine)* and display layer (selectors)*/+import { AuvManifest } from '@lobechat/builtin-tool-auv';import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { isDesktop } from '@lobechat/const';@@ -11,8 +12,8 @@ import { isDesktop } from '@lobechat/const';* @returns true if the tool should be enabled, false otherwise*/export const shouldEnableTool = (toolId: string): boolean => {- // Filter LocalSystem tool in non-desktop environment- if (toolId === LocalSystemManifest.identifier) {+ // These executors call Electron IPC and cannot run in a plain web client.+ if (toolId === LocalSystemManifest.identifier || toolId === AuvManifest.identifier) {return isDesktop;}diff --git a/src/services/electron/auv.ts b/src/services/electron/auv.tsnew file mode 100644index 00000000000..1085b064272--- /dev/null+++ b/src/services/electron/auv.ts@@ -0,0 +1,7 @@+import { type AuvRunCommandParams } from '@lobechat/builtin-tool-auv';++import { ensureElectronIpc } from '@/utils/electron/ipc';++export const electronAuvService = {+ runCommand: (params: AuvRunCommandParams) => ensureElectronIpc().auv.runCommand(params),+};diff --git a/src/store/tool/builtinToolRegistry.test.ts b/src/store/tool/builtinToolRegistry.test.tsindex 2fc5b03bec5..f065c990cac 100644--- a/src/store/tool/builtinToolRegistry.test.ts+++ b/src/store/tool/builtinToolRegistry.test.ts@@ -1,4 +1,5 @@import { WEB_ONBOARDING } from '@lobechat/builtin-agents';+import { AuvApiName, AuvIdentifier, AuvManifest } from '@lobechat/builtin-tool-auv/client';import {BrowserApiName,BrowserIdentifier,@@ -20,6 +21,7 @@ import { GroupAgentBuilderInspectors } from '@lobechat/builtin-tool-group-agent-import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';import {LocalSystemApiName,+ LocalSystemIdentifier,LocalSystemRenders,LocalSystemStreamings,} from '@lobechat/builtin-tool-local-system/client';@@ -35,6 +37,7 @@ import {WebOnboardingIdentifier,WebOnboardingManifest,} from '@lobechat/builtin-tool-web-onboarding';+import { alwaysOnToolIds } from '@lobechat/builtin-tools';import { getBuiltinRenderDisplayControl } from '@lobechat/builtin-tools/displayControls';import { builtinToolIdentifiers } from '@lobechat/builtin-tools/identifiers';import { getBuiltinInspector } from '@lobechat/builtin-tools/inspectors';@@ -42,9 +45,16 @@ import { getBuiltinIntervention } from '@lobechat/builtin-tools/interventions';import { registerBuiltinToolSurfaces } from '@lobechat/builtin-tools/register';import { getBuiltinRender } from '@lobechat/builtin-tools/renders';import { getBuiltinStreaming } from '@lobechat/builtin-tools/streamings';-import { beforeAll, describe, expect, it } from 'vitest';+import { shinyTextStyles } from '@lobechat/shared-tool-ui/styles';+import { cleanup, render } from '@testing-library/react';+import { createElement } from 'react';+import { afterEach, beforeAll, describe, expect, it } from 'vitest';++import ToolInspector from '@/features/Conversation/Messages/AssistantGroup/Tool/Inspector';describe('builtin tool registry', () => {+ afterEach(cleanup);+beforeAll(() => {registerBuiltinToolSurfaces();});@@ -57,6 +67,251 @@ describe('builtin tool registry', () => {expect(builtinToolIdentifiers).toContain(WebOnboardingIdentifier);});+ it('includes AUV in builtin identifiers', () => {+ expect(AuvIdentifier).toBe('lobe-computer-use');+ expect(AuvManifest.meta.title).toBe('Computer Use');+ expect(AuvManifest.api[0].parameters.properties).toHaveProperty('reasoning');+ expect(AuvManifest.api[0].parameters.required).toEqual(['argv']);+ expect(builtinToolIdentifiers).toContain(AuvIdentifier);+ });++ /** @example AUV command calls resolve a custom header instead of the generic API label. */+ it('registers an inspector for the AUV CLI entry point', () => {+ // ROOT CAUSE:+ //+ // AUV was registered as a builtin without a matching inspector registration.+ // The chat therefore fell back to the API name and hid the command being invoked.+ // Registering the AUV inspector makes command context available in every lifecycle phase.+ /** @example lobe-computer-use/runCommand resolves a component in the central registry. */+ expect(getBuiltinInspector(AuvIdentifier, AuvApiName.runCommand)).toBeDefined();+ });++ /** @example A command with a spaced argument stays readable after execution. */+ it('renders AUV argv through its registered inspector without losing argument boundaries', () => {+ const Inspector = getBuiltinInspector(AuvIdentifier, AuvApiName.runCommand);+ if (!Inspector) throw new Error('AUV inspector is not registered');++ const view = render(+ createElement(Inspector, {+ apiName: AuvApiName.runCommand,+ args: { argv: ['invoke', 'input.typeText', 'hello world', ''] },+ identifier: AuvIdentifier,+ pluginState: { output: { ok: true } },+ }),+ );++ /** @example A single "hello world" argument and an empty argument remain distinguishable. */+ expect(view.getByText('auv invoke input.typeText "hello world" ""')).toBeVisible();+ /** @example AUV uses a localized command label instead of the raw runCommand API name. */+ expect(view.getByText('builtins.lobe-computer-use.inspector.input:')).toBeVisible();+ });++ /** @example Streaming begins with a label and progressively reveals the AUV command. */+ it('keeps the AUV header visible while arguments stream and execution loads', () => {+ const Inspector = getBuiltinInspector(AuvIdentifier, AuvApiName.runCommand);+ if (!Inspector) throw new Error('AUV inspector is not registered');++ const baseProps = { apiName: AuvApiName.runCommand, args: {}, identifier: AuvIdentifier };+ const view = render(createElement(Inspector, { ...baseProps, isArgumentsStreaming: true }));+ /** @example The empty streaming phase pulses a non-empty localized title. */+ expect(view.getByText('builtins.lobe-computer-use.inspector.operate.loading')).toHaveClass(+ shinyTextStyles.shinyText,+ );++ view.rerender(+ createElement(Inspector, {+ ...baseProps,+ isArgumentsStreaming: true,+ partialArgs: { argv: ['invoke', 'display.'] },+ }),+ );+ /** @example Partial argv is displayed before final arguments are available. */+ expect(view.getByText('auv invoke display.')).toBeVisible();++ view.rerender(+ createElement(Inspector, {+ ...baseProps,+ args: { argv: ['invoke', 'display.list'] },+ isLoading: true,+ partialArgs: { argv: ['invoke', 'display.'] },+ }),+ );+ /** @example Completed arguments supersede the partial command during execution. */+ expect(view.getByText('auv invoke display.list')).toBeVisible();+ /** @example Execution keeps the shared loading animation. */+ expect(view.getByText('builtins.lobe-computer-use.inspector.inspect.loading:')).toHaveClass(+ shinyTextStyles.shinyText,+ );+ });++ /** @example Failed calls retain their command context even without pluginState. */+ it('renders failed AUV calls without requiring a successful result payload', () => {+ const Inspector = getBuiltinInspector(AuvIdentifier, AuvApiName.runCommand);+ if (!Inspector) throw new Error('AUV inspector is not registered');++ const view = render(+ createElement(Inspector, {+ apiName: AuvApiName.runCommand,+ args: { argv: ['invoke', 'display.capture'] },+ identifier: AuvIdentifier,+ result: { content: null, error: { message: 'Screen recording permission denied' } },+ }),+ );+ /** @example The failed command is still identifiable in conversation history. */+ expect(view.getByText('auv invoke display.capture')).toBeVisible();+ /** @example A finished failure does not keep pulsing as if it were running. */+ expect(view.getByText('builtins.lobe-computer-use.inspector.capture:')).not.toHaveClass(+ shinyTextStyles.shinyText,+ );+ });++ // PR #19051: one CLI entry point must still describe the actual computer action.+ it.each([+ ['input.clickPoint', 'operate'],+ ['input.typeText', 'input'],+ ['input.pasteText', 'input'],+ ['input.key', 'keyboard'],+ ['input.keyboard', 'keyboard'],+ ['input.focusText', 'focus'],+ ['display.capture', 'capture'],+ ['window.capture', 'capture'],+ ['screen.captureRegion', 'capture'],+ ['window.list', 'inspect'],+ ['future.command', 'operate'],+ ])('describes %s while it executes', (command, activity) => {+ const Inspector = getBuiltinInspector(AuvIdentifier, AuvApiName.runCommand)!;+ const view = render(+ createElement(Inspector, {+ apiName: AuvApiName.runCommand,+ args: { argv: ['invoke', command], reasoning: 'Find the search field' },+ identifier: AuvIdentifier,+ isLoading: true,+ }),+ );+ expect(+ view.getByText(`builtins.lobe-computer-use.inspector.${activity}.loading:`),+ ).toBeVisible();+ expect(view.getByText('Find the search field')).toBeVisible();+ expect(view.queryByText(`auv invoke ${command}`)).toBeNull();+ });++ it('keeps streamed reasoning and uses help or dry-run labels before action labels', () => {+ const Inspector = getBuiltinInspector(AuvIdentifier, AuvApiName.runCommand)!;+ const base = { apiName: AuvApiName.runCommand, identifier: AuvIdentifier, args: {} };+ const view = render(+ createElement(Inspector, {+ ...base,+ isArgumentsStreaming: true,+ partialArgs: {+ argv: ['invoke', 'display.capture', '--help'],+ reasoning: 'Check capture options',+ },+ }),+ );+ expect(view.getByText('builtins.lobe-computer-use.inspector.help.loading:')).toBeVisible();+ expect(view.getByText('Check capture options')).toBeVisible();+ view.rerender(+ createElement(Inspector, {+ ...base,+ args: { argv: ['invoke', 'input.typeText', 'hello', '--dry-run'] },+ isLoading: true,+ }),+ );+ expect(view.getByText('builtins.lobe-computer-use.inspector.preview.loading:')).toBeVisible();+ view.rerender(+ createElement(Inspector, {+ ...base,+ args: { argv: ['invoke', 'input.typeText', '--', '--help'] },+ isLoading: true,+ }),+ );+ expect(view.getByText('builtins.lobe-computer-use.inspector.input.loading:')).toBeVisible();+ });++ it('distinguishes reading an image from reading a text file', () => {+ const Inspector = getBuiltinInspector(LocalSystemIdentifier, LocalSystemApiName.readFile)!;+ const base = { apiName: LocalSystemApiName.readFile, identifier: LocalSystemIdentifier };+ const view = render(+ createElement(Inspector, {+ ...base,+ args: {},+ partialArgs: { path: '/tmp/capture.PNG' },+ isArgumentsStreaming: true,+ }),+ );+ expect(view.getByText('builtins.lobe-local-system.inspector.viewImage.loading:')).toBeVisible();+ view.rerender(+ createElement(Inspector, {+ ...base,+ args: { path: '/tmp/capture' },+ pluginState: { images: [{ mediaType: 'image/png', url: 'https://example.test/capture' }] },+ }),+ );+ expect(view.getByText('builtins.lobe-local-system.inspector.viewImage:')).toBeVisible();+ view.rerender(+ createElement(Inspector, {+ ...base,+ args: { path: '/tmp/notes.md' },+ }),+ );+ expect(view.getByText('builtins.lobe-local-system.apiName.readLocalFile:')).toBeVisible();+ });++ // PR #19051: collapsed chat rows bypassed the registered inspector entirely.+ it('keeps action labels and reasoning in collapsed Computer Use chat rows', () => {+ const view = render(+ createElement(ToolInspector, {+ apiName: AuvApiName.runCommand,+ arguments: JSON.stringify({+ argv: ['invoke', 'display.capture'],+ reasoning: 'Check the search result',+ }),+ identifier: AuvIdentifier,+ isExpanded: false,+ isToolCalling: true,+ toolCallId: 'computer-use-capture',+ }),+ );+ expect(view.getByText('builtins.lobe-computer-use.inspector.capture.loading:')).toBeVisible();+ expect(view.getByText('Check the search result')).toBeVisible();+ });++ it('keeps the image-reading label in collapsed chat rows', () => {+ const view = render(+ createElement(ToolInspector, {+ apiName: LocalSystemApiName.readFile,+ arguments: JSON.stringify({ path: '/tmp/capture.png' }),+ identifier: LocalSystemIdentifier,+ isExpanded: false,+ isToolCalling: true,+ toolCallId: 'computer-use-image',+ }),+ );+ expect(view.getByText('builtins.lobe-local-system.inspector.viewImage.loading:')).toBeVisible();+ });++ it('renders historical AUV calls without advertising the retired identifier', () => {+ expect(getBuiltinInspector('lobe-auv', AuvApiName.runCommand)).toBe(+ getBuiltinInspector(AuvIdentifier, AuvApiName.runCommand),+ );+ expect(builtinToolIdentifiers).not.toContain('lobe-auv');+ const view = render(+ createElement(ToolInspector, {+ apiName: AuvApiName.runCommand,+ arguments: JSON.stringify({ argv: ['invoke', 'input.key', 'return'] }),+ identifier: 'lobe-auv',+ isExpanded: false,+ result: { content: null, error: { message: 'Input failed' } },+ toolCallId: 'historical-auv',+ }),+ );+ expect(view.getByText('builtins.lobe-computer-use.inspector.keyboard:')).toBeVisible();+ });++ it('keeps Computer Use out of the always-on tools', () => {+ expect(alwaysOnToolIds).not.toContain(AuvIdentifier);+ });+it('registers skill store inspectors and renders for market flows', () => {expect(SkillStoreInspectors[SkillStoreApiName.importFromMarket]).toBeDefined();expect(SkillStoreInspectors[SkillStoreApiName.searchSkill]).toBeDefined();diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.tsindex 95be705a4df..90ea04f300e 100644--- a/src/store/tool/slices/builtin/executors/catalog.ts+++ b/src/store/tool/slices/builtin/executors/catalog.ts@@ -1,5 +1,6 @@import { agentBuilderExecutor } from '@lobechat/builtin-tool-agent-builder/executor';import { agentManagementExecutor } from '@lobechat/builtin-tool-agent-management/executor';+import { auvExecutor } from '@lobechat/builtin-tool-auv/client/executor';import { browserExecutor } from '@lobechat/builtin-tool-browser/client/executor';import { calculatorExecutor } from '@lobechat/builtin-tool-calculator/executor';import { cloudSandboxExecutor } from '@lobechat/builtin-tool-cloud-sandbox/executor';@@ -59,6 +60,7 @@ export const builtinToolExecutors = [agentBuilderExecutor,agentDocumentsExecutor,agentManagementExecutor,+ auvExecutor,calculatorExecutor,cloudSandboxExecutor,credsExecutor,