🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(device): wake managed cloud devices before dispatch (#22276)
Nekoe084b7f0d137
diff --git a/apps/server/src/routers/lambda/__tests__/deviceWakeManaged.test.ts b/apps/server/src/routers/lambda/__tests__/deviceWakeManaged.test.tsnew file mode 100644index 00000000000..8d50a96c186--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/deviceWakeManaged.test.ts@@ -0,0 +1,79 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceRouter } from '../device';++const mocks = vi.hoisted(() => ({+ findWorkspaceDeviceById: vi.fn(),+ requestManagedDeviceWake: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/device', () => ({+ DeviceModel: class {+ findWorkspaceDeviceById = mocks.findWorkspaceDeviceById;+ },+}));+vi.mock('@/server/services/deviceGateway/managedDeviceWake', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ requestManagedDeviceWake: mocks.requestManagedDeviceWake,+}));++const personalCaller = () => deviceRouter.createCaller({ userId: 'user-1' } as never);+const workspaceCaller = (userId: string, workspaceRole: 'member' | 'viewer') =>+ deviceRouter.createCaller({ userId, workspaceId: 'workspace', workspaceRole } as never);++describe('device.wakeManagedDevice', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.requestManagedDeviceWake.mockResolvedValue('accepted');+ mocks.findWorkspaceDeviceById.mockResolvedValue({+ deviceId: 'managed-a',+ userId: 'enroller',+ visibility: 'public',+ });+ });++ it('asks the provider to wake a personal managed device', async () => {+ await expect(personalCaller().wakeManagedDevice({ deviceId: 'managed-a' })).resolves.toEqual({+ success: true,+ });+ expect(mocks.requestManagedDeviceWake).toHaveBeenCalledWith(+ expect.objectContaining({ userId: 'user-1', workspaceId: undefined }),+ 'managed-a',+ );+ });++ it('wakes a public workspace device for any member', async () => {+ await expect(+ workspaceCaller('member', 'member').wakeManagedDevice({ deviceId: 'managed-a' }),+ ).resolves.toEqual({ success: true });+ expect(mocks.requestManagedDeviceWake).toHaveBeenCalledWith(+ expect.objectContaining({ userId: 'member', workspaceId: 'workspace' }),+ 'managed-a',+ );+ });++ it('refuses a workspace viewer', async () => {+ await expect(+ workspaceCaller('viewer', 'viewer').wakeManagedDevice({ deviceId: 'managed-a' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mocks.requestManagedDeviceWake).not.toHaveBeenCalled();+ });++ it('answers NOT_FOUND for a device that is not a managed cloud device', async () => {+ mocks.requestManagedDeviceWake.mockResolvedValue('not-managed');++ await expect(+ personalCaller().wakeManagedDevice({ deviceId: 'desktop-a' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('answers BAD_GATEWAY when the provider refuses the wake', async () => {+ mocks.requestManagedDeviceWake.mockRejectedValue(new Error('limit reached'));++ await expect(+ personalCaller().wakeManagedDevice({ deviceId: 'managed-a' }),+ ).rejects.toMatchObject({ code: 'BAD_GATEWAY' });+ });+});diff --git a/apps/server/src/routers/lambda/device/index.procedures.test.ts b/apps/server/src/routers/lambda/device/index.procedures.test.tsindex 40ccfdcf571..0460671f1dc 100644--- a/apps/server/src/routers/lambda/device/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/device/index.procedures.test.ts@@ -102,6 +102,7 @@ function expected(): Array<['updateDevice', 'mutation', 12],['updateDeviceInfo', 'mutation', 12],['updateWorkspaceDevice', 'mutation', 12],+ ['wakeManagedDevice', 'mutation', 12],['writeProjectFile', 'mutation', 15],['writeTerminal', 'mutation', 12],];diff --git a/apps/server/src/routers/lambda/device/operate.ts b/apps/server/src/routers/lambda/device/operate.tsindex e7f522e8148..f2f5633d8e9 100644--- a/apps/server/src/routers/lambda/device/operate.ts+++ b/apps/server/src/routers/lambda/device/operate.ts@@ -5,6 +5,7 @@ import { z } from 'zod';import { router } from '@/libs/trpc/lambda';import { signTunnelAccessToken } from '@/libs/trpc/utils/internalJwt';import { deviceGateway } from '@/server/services/deviceGateway';+import { requestManagedDeviceWake } from '@/server/services/deviceGateway/managedDeviceWake';import { deviceTunnels, TUNNEL_MAX_TTL_SECONDS } from '@/server/services/deviceGateway/tunnels';import { assertDeviceOperable } from './guards';@@ -310,4 +311,33 @@ export const operateRouter = router({}return { success: true };}),+ /**+ * Ask a managed cloud device to start, for the device picker's wake+ * control. Resolves when the provider accepts the request, not when the+ * device is online: the caller watches the device list for that. Not gated+ * on the create-time feature flag, so existing devices stay usable.+ */+ wakeManagedDevice: deviceProcedure+ .input(z.object({ deviceId: z.string().min(1).max(64) }))+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'wake the device');++ let outcome: Awaited<ReturnType<typeof requestManagedDeviceWake>>;+ try {+ outcome = await requestManagedDeviceWake(+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },+ input.deviceId,+ );+ } catch (error) {+ console.warn('[device] Managed device wake failed', {+ deviceId: input.deviceId,+ error: error instanceof Error ? error.message : String(error),+ });+ throw new TRPCError({ code: 'BAD_GATEWAY', message: 'Could not wake the device.' });+ }+ if (outcome === 'not-managed') {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Managed cloud device not found.' });+ }+ return { success: true };+ }),});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.tsindex 116c7722fed..88923790926 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts@@ -3,12 +3,19 @@ import type { ExecAgentResult } from '@lobechat/types';import { getWorkingDirSourcePath } from '@lobechat/types';import debug from 'debug';+import { AgentOperationModel } from '@/database/models/agentOperation';import { DeviceModel } from '@/database/models/device';import type { ExecutionPlan } from '@/helpers/executionTarget';import { AgentQuotaService } from '@/server/services/agentQuota';import { deviceGateway } from '@/server/services/deviceGateway';import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';+import {+ type ManagedDeviceTarget,+ waitForManagedDeviceOnline,+ wakeManagedDevice,+} from '@/server/services/deviceGateway/managedDeviceWake';import { buildRemoteDeviceHeteroContext } from '@/server/services/heterogeneousAgent/remoteDeviceHeteroContext';+import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';import {humanizeHeteroDispatchError,@@ -26,6 +33,11 @@ import { failHeteroDispatch } from './utils';const log = debug('lobe-server:ai-agent-service');+/** A plan `dispatchToCliDevice` can act on: a waking device is woken first. */+type CliDispatchPlan = Exclude<ExecutionPlan, { kind: 'device-wakeable' }>;++type CliDispatchParams = Parameters<typeof dispatchToCliDevice>[2];+/*** The Claude Code account the agent's Manage-accounts choice routes this run* to. The device maps it to one of its own logins: without it the device@@ -77,7 +89,7 @@ export const dispatchToCliDevice = async (agentConfig: ExecRunContext['agentConfig'];appContext: ExecRunContext['appContext'];cliDeviceWorkspaceId?: string;- heteroPlan: ExecutionPlan;+ heteroPlan: CliDispatchPlan;heteroType: HeteroDispatchInput['heteroType'];heterogeneousProvider: HeteroDispatchInput['heterogeneousProvider'];prepared: PreparedHeteroRun;@@ -296,3 +308,90 @@ export const dispatchToCliDevice = async (return undefined;};++/**+ * Wake a managed cloud device, then dispatch to it once it is online.+ *+ * The wake request is sent before the response. The wait (see+ * `waitForManagedDeviceOnline`) and the dispatch run after the response, like+ * the timed-out dispatch confirmation. If the device does not come online in+ * time, the dispatch still runs. The gateway refuses it as offline, and the+ * existing offline handling (the device error on the run, the goal's device+ * wait) takes over. A run stopped during the wait is not dispatched.+ *+ * If the provider refuses the wake, the device will not come online. The run+ * then dispatches at once, with no wait, and the offline handling takes over+ * as for any offline device.+ *+ * Returns `undefined` after an accepted wake: the run counts as started. A+ * later failure settles it through the same path as an immediate dispatch+ * failure.+ */+export const dispatchToWakingCliDevice = async (+ deps: HeteroDispatchDeps,+ run: HeteroRun,+ params: Omit<CliDispatchParams, 'heteroPlan'> & {+ device: ManagedDeviceTarget;+ heteroPlan: Extract<ExecutionPlan, { kind: 'device-wakeable' }>;+ },+): Promise<ExecAgentResult | undefined> => {+ const { device, heteroPlan, ...dispatchParams } = params;++ const devicePlan = {+ deviceId: heteroPlan.deviceId,+ kind: 'device' as const,+ target: heteroPlan.target,+ };++ if (!(await wakeManagedDevice(deps.userId, device))) {+ log(+ 'execAgent: wake refused for managed device %s, dispatching op=%s now',+ heteroPlan.deviceId,+ run.operationId,+ );+ return dispatchToCliDevice(deps, run, { ...dispatchParams, heteroPlan: devicePlan });+ }++ const operationModel = new AgentOperationModel(deps.db, deps.userId, deps.workspaceId);+ const isStopped = async () =>+ !(await operationModel.isRunningOnTopic(run.operationId, run.topicId));++ const dispatchWhenOnline = async () => {+ try {+ const online = await waitForManagedDeviceOnline(deps.userId, device, {+ shouldStop: isStopped,+ });+ if (await isStopped()) {+ log(+ 'execAgent: op=%s settled while its managed device woke, not dispatching',+ run.operationId,+ );+ return;+ }+ log(+ 'execAgent: managed device %s online=%s, dispatching op=%s',+ heteroPlan.deviceId,+ online,+ run.operationId,+ );+ await dispatchToCliDevice(deps, run, { ...dispatchParams, heteroPlan: devicePlan });+ } catch (error) {+ // Off the request path nothing else would settle the run.+ const message = error instanceof Error ? error.message : String(error);+ console.error('[HeteroDispatch] Dispatch to a woken managed device failed', {+ deviceId: heteroPlan.deviceId,+ error: message,+ operationId: run.operationId,+ });+ await failHeteroDispatch(+ deps,+ run,+ { detail: message, message: 'Hetero agent device dispatch failed' },+ { error: message, message: 'Hetero agent device dispatch failed' },+ );+ }+ };++ afterUnscoped(dispatchWhenOnline);+ return undefined;+};diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.wake.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.wake.test.tsnew file mode 100644index 00000000000..8800f59d707--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.wake.test.ts@@ -0,0 +1,221 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ExecRunContext } from '../../types';+import { dispatchToWakingCliDevice } from './device';+import type { PreparedHeteroRun } from './prepare';+import type { HeteroDispatchDeps, HeteroRun } from './types';++const mocks = vi.hoisted(() => ({+ afterWork: [] as (() => Promise<unknown> | unknown)[],+ dispatchAgentRun: vi.fn(),+ finalizeHeteroDispatchError: vi.fn(),+ isRunningOnTopic: vi.fn(),+ readDeviceSystemInfo: vi.fn(),+ resolveDeviceDispatchAuthorizationFailure: vi.fn(),+ selectCodexDeviceDispatch: vi.fn(),+ waitForManagedDeviceOnline: vi.fn(),+ wakeManagedDevice: vi.fn(),+}));++vi.mock('@/server/utils/scheduleAfterResponse', () => ({+ afterUnscoped: (work: () => Promise<unknown> | unknown) => {+ mocks.afterWork.push(work);+ },+}));++vi.mock('@/server/services/deviceGateway/managedDeviceWake', () => ({+ waitForManagedDeviceOnline: mocks.waitForManagedDeviceOnline,+ wakeManagedDevice: mocks.wakeManagedDevice,+}));++vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn().mockImplementation(function () {+ return { isRunningOnTopic: mocks.isRunningOnTopic };+ }),+}));++vi.mock('@/database/models/device', () => ({+ DeviceModel: vi.fn().mockImplementation(function () {+ return {+ findByDeviceId: vi.fn().mockResolvedValue(undefined),+ findWorkspaceDeviceById: vi.fn().mockResolvedValue(undefined),+ };+ }),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ dispatchAgentRun: mocks.dispatchAgentRun,+ readDeviceSystemInfo: mocks.readDeviceSystemInfo,+ },+}));++vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({+ resolveDeviceDispatchAuthorizationFailure: mocks.resolveDeviceDispatchAuthorizationFailure,+}));++vi.mock('@/server/services/agentQuota', () => ({+ AgentQuotaService: vi.fn(function () {+ return {+ planDeviceRouting: vi.fn().mockResolvedValue(null),+ resolveDeviceRowId: async (id?: string) => id,+ };+ }),+}));++vi.mock('../codexDeviceRuntime', () => ({+ selectCodexDeviceDispatch: mocks.selectCodexDeviceDispatch,+}));++vi.mock('../finalizeHeteroDispatchError', () => ({+ finalizeHeteroDispatchError: mocks.finalizeHeteroDispatchError,+}));++const device = { deviceId: 'managed-a', scope: 'personal' as const };+const run: HeteroRun = {+ agentId: 'agent-1',+ assistantMessageId: 'asst-1',+ operationId: 'op-1',+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+};++const createDeps = () => {+ const topicModel = {+ patchRunningOperation: vi.fn().mockResolvedValue(true),+ };+ const deps = {+ bindTopicWorkingDirectory: vi.fn().mockResolvedValue(undefined),+ db: {} as any,+ getMarketService: vi.fn(),+ messageModel: {} as any,+ resolveDeviceWorkspaceId: vi.fn().mockResolvedValue(undefined),+ topicModel: topicModel as any,+ userId: 'user-1',+ withholdGatewayToken: false,+ } satisfies HeteroDispatchDeps;+ return { deps, topicModel };+};++const dispatch = (deps: HeteroDispatchDeps) =>+ dispatchToWakingCliDevice(deps, run, {+ agentConfig: { agencyConfig: {}, id: 'agent-1' } as unknown as ExecRunContext['agentConfig'],+ appContext: undefined,+ device,+ heteroPlan: { deviceId: 'managed-a', kind: 'device-wakeable', target: 'device' },+ heteroType: 'claude-code',+ heterogeneousProvider: { type: 'claude-code' },+ prepared: { heteroParams: {} } as unknown as PreparedHeteroRun,+ });++const runScheduledWork = async () => {+ const work = mocks.afterWork.splice(0);+ for (const item of work) await item();+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.afterWork.length = 0;+ mocks.dispatchAgentRun.mockResolvedValue({ success: true });+ mocks.finalizeHeteroDispatchError.mockResolvedValue(true);+ mocks.isRunningOnTopic.mockResolvedValue(true);+ mocks.resolveDeviceDispatchAuthorizationFailure.mockResolvedValue(undefined);+ mocks.selectCodexDeviceDispatch.mockResolvedValue({ kind: 'exec' });+ mocks.waitForManagedDeviceOnline.mockResolvedValue(true);+ mocks.wakeManagedDevice.mockResolvedValue(true);+});++describe('dispatchToWakingCliDevice', () => {+ it('wakes the device before returning and dispatches only after the response', async () => {+ const { deps, topicModel } = createDeps();++ await expect(dispatch(deps)).resolves.toBeUndefined();++ expect(mocks.wakeManagedDevice).toHaveBeenCalledWith('user-1', device);+ expect(mocks.waitForManagedDeviceOnline).not.toHaveBeenCalled();+ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();++ await runScheduledWork();++ expect(mocks.waitForManagedDeviceOnline).toHaveBeenCalledWith(+ 'user-1',+ device,+ expect.objectContaining({ shouldStop: expect.any(Function) }),+ );+ expect(mocks.dispatchAgentRun).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'managed-a' }),+ );+ expect(topicModel.patchRunningOperation).toHaveBeenCalledWith(+ 'topic-1',+ 'op-1',+ expect.objectContaining({ deviceId: 'managed-a' }),+ );+ });++ it('dispatches after a timed-out wait so the offline handling takes over', async () => {+ mocks.waitForManagedDeviceOnline.mockResolvedValue(false);+ mocks.dispatchAgentRun.mockResolvedValue({ error: 'DEVICE_OFFLINE', success: false });+ const { deps } = createDeps();++ await dispatch(deps);+ await runScheduledWork();++ expect(mocks.dispatchAgentRun).toHaveBeenCalledTimes(1);+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(+ deps,+ expect.objectContaining({+ deviceRoute: expect.objectContaining({ deviceId: 'managed-a' }),+ operationId: 'op-1',+ }),+ );+ });++ it('dispatches at once without waiting when the provider refuses the wake', async () => {+ mocks.wakeManagedDevice.mockResolvedValue(false);+ mocks.dispatchAgentRun.mockResolvedValue({ error: 'DEVICE_OFFLINE', success: false });+ const { deps } = createDeps();++ await dispatch(deps);++ expect(mocks.afterWork).toHaveLength(0);+ expect(mocks.waitForManagedDeviceOnline).not.toHaveBeenCalled();+ expect(mocks.dispatchAgentRun).toHaveBeenCalledTimes(1);+ expect(mocks.dispatchAgentRun).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'managed-a' }),+ );+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(+ deps,+ expect.objectContaining({+ deviceRoute: expect.objectContaining({ deviceId: 'managed-a' }),+ operationId: 'op-1',+ }),+ );+ });++ it('does not dispatch a run that was stopped while the device woke', async () => {+ mocks.isRunningOnTopic.mockResolvedValue(false);+ const { deps } = createDeps();++ await dispatch(deps);+ await runScheduledWork();++ expect(mocks.isRunningOnTopic).toHaveBeenCalledWith('op-1', 'topic-1');+ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();+ expect(mocks.finalizeHeteroDispatchError).not.toHaveBeenCalled();+ });++ it('settles the run when the background dispatch throws', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ mocks.selectCodexDeviceDispatch.mockRejectedValue(new Error('db down'));+ const { deps } = createDeps();++ await dispatch(deps);+ await runScheduledWork();++ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(+ deps,+ expect.objectContaining({ detail: 'db down', operationId: 'op-1' }),+ );+ error.mockRestore();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.tsindex 8e5ebdfedf2..7a6e107681b 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts@@ -15,10 +15,11 @@ import {} from '@/server/modules/AgentRuntime/factory';import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';import { hookDispatcher } from '@/server/services/agentRuntime/hooks';+import { findWakeableManagedDevices } from '@/server/services/deviceGateway/managedDeviceWake';import { supportsCloudHeterogeneousSandbox } from '../../helpers/heteroErrors';import type { ExecRunContext } from '../../types';-import { dispatchToCliDevice } from './device';+import { dispatchToCliDevice, dispatchToWakingCliDevice } from './device';import { prepareHeteroRun } from './prepare';import { dispatchToPlatformDevice } from './remote';import { spawnInCloudSandbox } from './sandbox';@@ -186,6 +187,15 @@ export const dispatchHeteroAgent = async (// Resolve CLI-device routing before persisting the marker. Cancellation// must address the same device even though local CLI agents use a different// dispatch transport from notify-based platform agents.+ // A bound managed cloud device that is offline resolves to+ // `device-wakeable`: it is woken and the dispatch waits for it.+ const wakeableCliDevices =+ !isRemoteHetero && canUseDevice+ ? await findWakeableManagedDevices(+ { db: deps.db, userId: deps.userId, workspaceId: deps.workspaceId },+ [requestedDeviceId, agentConfig.agencyConfig?.boundDeviceId],+ )+ : [];const cliPlanParams = {agencyConfig: agentConfig.agencyConfig,clientExecutionAvailable: false,@@ -193,18 +203,24 @@ export const dispatchHeteroAgent = async (requestedDeviceId,sandboxExecutionAvailable: supportsCloudHeterogeneousSandbox(heteroType),trigger: requestTrigger,+ wakeableDeviceIds: wakeableCliDevices.map((device) => device.deviceId),};const deviceHeteroPlan = !isRemoteHetero? resolveExecutionPlan({ ...cliPlanParams, canUseDevice }): undefined;- const cliDeviceId = deviceHeteroPlan?.kind === 'device' ? deviceHeteroPlan.deviceId : undefined;+ const cliDeviceId =+ deviceHeteroPlan?.kind === 'device' || deviceHeteroPlan?.kind === 'device-wakeable'+ ? deviceHeteroPlan.deviceId+ : undefined;// Whether the sandbox is a fallback for a sender denied the agent's device:// with access the same request would have routed to a device. Lets a failed// sandbox run tell the sender why it ran there instead.const deviceAccessDenied =deviceHeteroPlan?.kind === 'sandbox' &&!canUseDevice &&- resolveExecutionPlan({ ...cliPlanParams, canUseDevice: true }).kind === 'device';+ ['device', 'device-wakeable'].includes(+ resolveExecutionPlan({ ...cliPlanParams, canUseDevice: true }).kind,+ );const cliDeviceWorkspaceId = cliDeviceId? await deps.resolveDeviceWorkspaceId(cliDeviceId): undefined;@@ -404,18 +420,38 @@ export const dispatchHeteroAgent = async (}const heteroPlan = deviceHeteroPlan!;- const failure =- heteroPlan.kind !== 'sandbox'- ? await dispatchToCliDevice(deps, run, {- agentConfig,- appContext,- cliDeviceWorkspaceId,- heteroPlan,- heteroType,- heterogeneousProvider,- prepared,- })- : await spawnInCloudSandbox(deps, run, { deviceAccessDenied, heteroType, prepared });+ const cliDispatchParams = {+ agentConfig,+ appContext,+ cliDeviceWorkspaceId,+ heteroType,+ heterogeneousProvider,+ prepared,+ };+ let failure: ExecAgentResult | undefined;+ switch (heteroPlan.kind) {+ case 'sandbox': {+ failure = await spawnInCloudSandbox(deps, run, {+ deviceAccessDenied,+ heteroType,+ prepared,+ });+ break;+ }+ case 'device-wakeable': {+ // Wakes the device and dispatches after the response, once it is+ // online (or when the wait times out, through the offline handling).+ failure = await dispatchToWakingCliDevice(deps, run, {+ ...cliDispatchParams,+ device: wakeableCliDevices.find((device) => device.deviceId === heteroPlan.deviceId)!,+ heteroPlan,+ });+ break;+ }+ default: {+ failure = await dispatchToCliDevice(deps, run, { ...cliDispatchParams, heteroPlan });+ }+ }if (failure) return failure;}diff --git a/apps/server/src/services/aiAgent/pipeline/operationInitSlots.test.ts b/apps/server/src/services/aiAgent/pipeline/operationInitSlots.test.tsnew file mode 100644index 00000000000..a15f9a2f6db--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/operationInitSlots.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import { resolveOperationInitSlots } from './operationInitSlots';++const discovery = (overrides: Record<string, unknown>) =>+ ({+ credentialFactsPromise: Promise.resolve(undefined),+ modelMediaCapabilities: {},+ toolsResult: { enabledToolIds: [] },+ ...overrides,+ }) as any;+const prep = { deviceSystemInfo: { workingDirectory: '/srv/project' } } as any;++describe('resolveOperationInitSlots — device binding', () => {+ it('binds a waking managed device to the operation', async () => {+ const slots = await resolveOperationInitSlots({+ discovery: discovery({+ executionPlan: { deviceId: 'managed-a', kind: 'device-wakeable', target: 'device' },+ }),+ initialContext: undefined as any,+ prep,+ });++ expect(slots.activeDeviceId).toBe('managed-a');+ expect(slots.deviceSystemInfo).toEqual({ workingDirectory: '/srv/project' });+ });++ it('keeps the routed device and binds nothing for an unrouted plan', async () => {+ const routed = await resolveOperationInitSlots({+ discovery: discovery({+ activeDeviceId: 'device-a',+ executionPlan: { deviceId: 'device-a', kind: 'device', target: 'device' },+ }),+ initialContext: undefined as any,+ prep,+ });+ const unrouted = await resolveOperationInitSlots({+ discovery: discovery({+ executionPlan: {+ kind: 'device-unrouted',+ reason: 'bound-device-offline',+ target: 'device',+ },+ }),+ initialContext: undefined as any,+ prep,+ });++ expect(routed.activeDeviceId).toBe('device-a');+ expect(unrouted.activeDeviceId).toBeUndefined();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts b/apps/server/src/services/aiAgent/pipeline/operationInitSlots.tsindex 7f72fb765a8..3245a1fffad 100644--- a/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts@@ -22,8 +22,15 @@ export const resolveOperationInitSlots = async ({}): Promise<OperationInitSlots> => {const { audio, video, vision } = discovery.modelMediaCapabilities;+ const { executionPlan } = discovery;+return {- activeDeviceId: discovery.activeDeviceId,+ // A waking managed device is bound to the operation but not to the prep+ // above, so its tool calls go to it (and answer `DEVICE_WAKING` until it+ // is online) without any device RPC on the request path.+ activeDeviceId:+ discovery.activeDeviceId ??+ (executionPlan?.kind === 'device-wakeable' ? executionPlan.deviceId : undefined),activeDeviceScope: discovery.activeDeviceScope,agentGroup: discovery.operationAgentGroup,// Run context the context engine injects into the system message —@@ -31,7 +38,7 @@ export const resolveOperationInitSlots = async ({connectorOwnershipNote: discovery.connectorOwnershipNote,deviceSystemInfo:Object.keys(prep.deviceSystemInfo).length > 0 ? prep.deviceSystemInfo : undefined,- executionPlan: discovery.executionPlan,+ executionPlan,expertise: prep.expertise,initialContext,initialMessages: prep.allMessages,diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex 5149030a0ed..f08c9679acf 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -230,11 +230,17 @@ const resolveWorkspaceInit = async (params: {activeDeviceId: string | undefined;agencyConfig?: LobeAgentAgencyConfig;+ /**+ * The device is not online yet (a managed cloud device that is waking).+ * The bound directory still resolves from the persisted rows, but the+ * device is never scanned: only a cached scan is served.+ */+ deviceWaking?: boolean;topicId: string;},): Promise<ResolvedWorkspaceInit> => {const empty: WorkspaceInitResult = { instructions: [], skills: [] };- const { activeDeviceId, agencyConfig, topicId } = params;+ const { activeDeviceId, agencyConfig, deviceWaking, topicId } = params;if (!activeDeviceId) return { workspace: empty };try {@@ -290,6 +296,8 @@ const resolveWorkspaceInit = async ((dir) => dir.path === boundCwd || getWorkingDirEffectivePath(dir) === boundCwd,);+ if (deviceWaking) return { ...resolved, workspace: cached?.workspace ?? empty };+if (isWorkspaceCacheFresh(cached, Date.now()) && cached?.workspace) {log('execAgent: reusing cached workspace init for %s', boundCwd);return { ...resolved, workspace: cached.workspace };@@ -735,9 +743,14 @@ export const prepareOperation = async (// re-gates on `activeDeviceId`). Only `location` (the absolute SKILL.md// path) flows through; the directory tree is enumerated lazily, keeping the// op-param payload small.+ // A waking managed device is not bound yet (see `resolveDevicePlan`), but+ // its directory is known from the persisted rows, and the run will reach it.+ const wakingDeviceId =+ executionPlan?.kind === 'device-wakeable' ? executionPlan.deviceId : undefined;const workspaceInit = await resolveWorkspaceInit(deps, {- activeDeviceId,+ activeDeviceId: activeDeviceId ?? wakingDeviceId,agencyConfig: agentConfig.agencyConfig ?? undefined,+ deviceWaking: !activeDeviceId && !!wakingDeviceId,topicId,});@@ -760,7 +773,7 @@ export const prepareOperation = async (config: workspaceInit.boundCwdConfig,currentDeviceId: workspaceInit.topicDeviceId,currentWorkingDirectory: workspaceInit.topicWorkingDirectory,- deviceId: activeDeviceId,+ deviceId: activeDeviceId ?? wakingDeviceId,topicId,});diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.test.tsnew file mode 100644index 00000000000..d3573d73760--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.test.ts@@ -0,0 +1,158 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveDevicePlan } from './devicePlan';++const mocks = vi.hoisted(() => ({+ deviceSystemInfo: vi.fn(),+ findWakeableManagedDevices: vi.fn(),+ updateMessage: vi.fn(),+ wakeManagedDevice: vi.fn(),+}));++vi.mock('@/server/utils/scheduleAfterResponse', () => ({+ afterUnscoped: (work: () => unknown) => work(),+}));++vi.mock('@/server/services/deviceGateway/managedDeviceWake', () => ({+ findWakeableManagedDevices: mocks.findWakeableManagedDevices,+ wakeManagedDevice: mocks.wakeManagedDevice,+}));++const deps = {+ db: {},+ messageModel: { update: mocks.updateMessage },+ userId: 'user-1',+} as any;++const ctx = (agencyConfig: Record<string, unknown>) =>+ ({+ agentConfig: { agencyConfig },+ assistantMessageId: 'asst-1',+ canUseDevice: true,+ runFacts: { deviceSystemInfo: mocks.deviceSystemInfo },+ topicId: 'topic-1',+ }) as any;++const input = (overrides: Record<string, unknown> = {}) =>+ ({+ isFixedDeviceTarget: false,+ ...overrides,+ }) as any;++const online = (deviceId: string) => ({+ deviceId,+ hostname: deviceId,+ lastSeen: '2026-01-01T00:00:00.000Z',+ online: true,+ platform: 'linux',+});++beforeEach(() => {+ vi.clearAllMocks();+ mocks.findWakeableManagedDevices.mockResolvedValue([]);+ mocks.wakeManagedDevice.mockResolvedValue(true);+ mocks.deviceSystemInfo.mockResolvedValue({ supportedTools: [] });+});++describe('resolveDevicePlan — managed cloud devices', () => {+ it('wakes an offline bound managed device and keeps the run on it', async () => {+ mocks.findWakeableManagedDevices.mockResolvedValue([+ { deviceId: 'managed-a', scope: 'personal' },+ ]);++ const result = await resolveDevicePlan(+ deps,+ ctx({ boundDeviceId: 'managed-a', executionTarget: 'device' }),+ input(),+ {+ boundDeviceId: 'managed-a',+ gatewayConfigured: true,+ onlineDevices: [online('device-b')],+ },+ );++ expect(mocks.findWakeableManagedDevices).toHaveBeenCalledWith(+ { db: deps.db, userId: 'user-1', workspaceId: undefined },+ [undefined, 'managed-a', undefined],+ ['device-b'],+ );+ expect(result.executionPlan).toEqual({+ deviceId: 'managed-a',+ kind: 'device-wakeable',+ target: 'device',+ });+ expect(mocks.wakeManagedDevice).toHaveBeenCalledWith('user-1', {+ deviceId: 'managed-a',+ scope: 'personal',+ });+ // The waking device is bound by the operation, never probed on the request path.+ expect(result.activeDeviceId).toBeUndefined();+ expect(result.activeDeviceScope).toBe('personal');+ expect(mocks.deviceSystemInfo).not.toHaveBeenCalled();+ expect(result.deviceCapable).toBe(true);+ expect(result.deviceLocked).toBe(true);+ });++ it('does not fail a fixed device target while its managed device wakes', async () => {+ mocks.findWakeableManagedDevices.mockResolvedValue([+ { deviceId: 'managed-a', scope: 'personal' },+ ]);++ const result = await resolveDevicePlan(+ deps,+ ctx({+ boundDeviceId: 'managed-a',+ executionTarget: 'device',+ executionTargetSelectionPolicy: 'fixed',+ }),+ input({ isFixedDeviceTarget: true }),+ {+ boundDeviceId: 'managed-a',+ gatewayConfigured: true,+ onlineDevices: [],+ },+ );++ expect(result.executionPlan.kind).toBe('device-wakeable');+ expect(mocks.updateMessage).not.toHaveBeenCalled();+ });++ it('keeps an offline ordinary device unrouted and wakes nothing', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ const result = await resolveDevicePlan(+ deps,+ ctx({ boundDeviceId: 'device-x', executionTarget: 'device' }),+ input(),+ {+ boundDeviceId: 'device-x',+ gatewayConfigured: true,+ onlineDevices: [],+ },+ );++ expect(result.executionPlan).toEqual({+ kind: 'device-unrouted',+ reason: 'bound-device-offline',+ target: 'device',+ });+ expect(mocks.wakeManagedDevice).not.toHaveBeenCalled();+ warn.mockRestore();+ });++ it('does not look for managed devices when the sender may not use a device', async () => {+ await resolveDevicePlan(+ deps,+ { ...ctx({ boundDeviceId: 'managed-a', executionTarget: 'device' }), canUseDevice: false },+ input(),+ {+ boundDeviceId: 'managed-a',+ gatewayConfigured: true,+ onlineDevices: [],+ },+ );++ expect(mocks.findWakeableManagedDevices).not.toHaveBeenCalled();+ expect(mocks.wakeManagedDevice).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.tsindex 0d551f092a3..eefc0e03dbb 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.ts@@ -9,6 +9,11 @@ import {resolveExecutionPlan,resolveToolMode,} from '@/helpers/executionTarget';+import {+ findWakeableManagedDevices,+ wakeManagedDevice,+} from '@/server/services/deviceGateway/managedDeviceWake';+import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';import { shareGateGrantsCloudSandbox } from '../../shareGate';import type { ExecRunContext } from '../../types';@@ -76,6 +81,18 @@ export const resolveDevicePlan = async (requireDevice,} = input;const { boundDeviceId, gatewayConfigured, onlineDevices } = devices;+ const onlineDeviceIds = onlineDevices.map((device) => device.deviceId);++ // A bound managed cloud device that is offline is woken instead of leaving+ // the run unrouted. Only the ids the resolver can bind are candidates.+ const wakeableDevices =+ gatewayConfigured && canUseDevice+ ? await findWakeableManagedDevices(+ { db: deps.db, userId: deps.userId, workspaceId: deps.workspaceId },+ [requestedDeviceId, agentConfig.agencyConfig?.boundDeviceId, localDeviceId],+ onlineDeviceIds,+ )+ : [];const executionPlan = resolveExecutionPlan({agencyConfig: agentConfig.agencyConfig,@@ -83,11 +100,23 @@ export const resolveDevicePlan = async (chatConfig: agentConfig.chatConfig ?? undefined,clientExecutionAvailable: gatewayConfigured,localDeviceId,- onlineDeviceIds: onlineDevices.map((device) => device.deviceId),+ onlineDeviceIds,requestedDeviceId,sandboxFallback: shareGate ? shareGateGrantsCloudSandbox(shareGate) : false,trigger: requestTrigger,+ wakeableDeviceIds: wakeableDevices.map((device) => device.deviceId),});+ const wakingDevice =+ executionPlan.kind === 'device-wakeable'+ ? wakeableDevices.find((device) => device.deviceId === executionPlan.deviceId)+ : undefined;+ if (wakingDevice) {+ // Start the device after the response, without holding the request: the+ // first step is an LLM call, and device tools wait for it (or answer+ // `DEVICE_WAKING`) until it is online.+ afterUnscoped(() => wakeManagedDevice(deps.userId, wakingDevice));+ log('execAgent: waking managed device %s for this run', wakingDevice.deviceId);+ }// Persist a visible assistant error and fail the RPC before tool/runtime// preparation, so no operation can start somewhere it must not run.const failUnroutedDevice = async (deviceId: string, message: string, detail: string) => {@@ -116,9 +145,13 @@ export const resolveDevicePlan = async (const deviceOffline =executionPlan.kind === 'device-unrouted' && executionPlan.reason === 'bound-device-offline';+ // A waking managed device is still the run's device: it is not a degrade.+ const routedToDevice =+ executionPlan.kind === 'device' || executionPlan.kind === 'device-wakeable';+// A fixed device target must never degrade to the cloud sandbox or a// different device.- if (isFixedDeviceTarget && boundDeviceId && !isChatMode && executionPlan.kind !== 'device') {+ if (isFixedDeviceTarget && boundDeviceId && !isChatMode && !routedToDevice) {await failUnroutedDevice(boundDeviceId,'Fixed agent device unavailable',@@ -134,7 +167,7 @@ export const resolveDevicePlan = async (requireDevice &&requestedDeviceId &&!isChatMode &&- !(executionPlan.kind === 'device' && executionPlan.deviceId === requestedDeviceId)+ !(routedToDevice && executionPlan.deviceId === requestedDeviceId)) {await failUnroutedDevice(requestedDeviceId,@@ -153,6 +186,9 @@ export const resolveDevicePlan = async (// physically stripped (here and in the engine walls) — the model must// follow the user's choice, never re-list or switch machines mid-run.const deviceLocked = isDeviceLockedPlan(executionPlan);+ // A waking device is not bound here: operation prep would make device RPCs+ // to it on the request path. The operation binds it instead (see+ // `resolveOperationInitSlots`), so its tool calls reach it once it is online.const activeDeviceId = executionPlan.kind === 'device' ? executionPlan.deviceId : undefined;// Which principal pool the routed device lives in. A workspace run with a// per-user `local` override routes to the caller's PERSONAL@@ -163,7 +199,7 @@ export const resolveDevicePlan = async (// `resolveRunWorkspaceId`.const activeDeviceScope = activeDeviceId? onlineDevices.find((d) => d.deviceId === activeDeviceId)?.scope- : undefined;+ : wakingDevice?.scope;log('execAgent: execution plan → kind=%s deviceId=%s scope=%s',executionPlan.kind,diff --git a/apps/server/src/services/deviceGateway/managedDeviceWake.test.ts b/apps/server/src/services/deviceGateway/managedDeviceWake.test.tsnew file mode 100644index 00000000000..47923f835f4--- /dev/null+++ b/apps/server/src/services/deviceGateway/managedDeviceWake.test.ts@@ -0,0 +1,327 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ findPersonalByDeviceId: vi.fn(),+ findWorkspaceDeviceById: vi.fn(),+ isAvailable: vi.fn(),+ queryDeviceList: vi.fn(),+ wake: vi.fn(),+}));++vi.mock('@/business/server/managedDevice', () => ({+ managedDeviceProvider: {+ isAvailable: mocks.isAvailable,+ listStates: vi.fn(),+ wake: mocks.wake,+ },+}));++vi.mock('@/database/models/device', () => ({+ DeviceModel: vi.fn().mockImplementation(function () {+ return {+ findPersonalByDeviceId: mocks.findPersonalByDeviceId,+ findWorkspaceDeviceById: mocks.findWorkspaceDeviceById,+ };+ }),+}));++vi.mock('./index', () => ({+ deviceGateway: { isConfigured: true, queryDeviceList: mocks.queryDeviceList },+}));++const {+ DEVICE_WAKING_ERROR_CODE,+ MANAGED_DEVICE_TOOL_CALL_WAIT_MS,+ MANAGED_DEVICE_WAKE_POLL_INTERVAL_MS,+ MANAGED_DEVICE_WAKE_REQUEST_TIMEOUT_MS,+ MANAGED_DEVICE_WAKE_TIMEOUT_MS,+ awaitManagedDeviceForToolCall,+ findWakeableManagedDevices,+ isDeviceUnreachableResult,+ requestManagedDeviceWake,+ waitForManagedDeviceOnline,+ wakeManagedDevice,+} = await import('./managedDeviceWake');++const db = {} as unknown as LobeChatDatabase;+const caller = { db, userId: 'user-1' };+const managedRow = (deviceId: string, workspaceId: string | null = null) => ({+ deviceId,+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ workspaceId,+});+const connectedRow = (deviceId: string) => ({+ deviceId,+ identitySource: 'machine-id',+ workspaceId: null,+});+const live = (deviceId: string) => ({ deviceId, online: true });++beforeEach(() => {+ vi.clearAllMocks();+ mocks.isAvailable.mockReturnValue(true);+ mocks.findPersonalByDeviceId.mockResolvedValue(undefined);+ mocks.findWorkspaceDeviceById.mockResolvedValue(undefined);+ mocks.queryDeviceList.mockResolvedValue([]);+ mocks.wake.mockResolvedValue(undefined);+});++afterEach(() => {+ vi.useRealTimers();+});++describe('findWakeableManagedDevices', () => {+ it('returns nothing and reads nothing when managed devices are not available', async () => {+ mocks.isAvailable.mockReturnValue(false);++ await expect(findWakeableManagedDevices(caller, ['managed-a'])).resolves.toEqual([]);+ expect(mocks.findPersonalByDeviceId).not.toHaveBeenCalled();+ expect(mocks.queryDeviceList).not.toHaveBeenCalled();+ });++ it('keeps only offline managed devices, using the online set it is given', async () => {+ mocks.findPersonalByDeviceId.mockImplementation(async (deviceId: string) =>+ deviceId === 'device-x' ? connectedRow(deviceId) : managedRow(deviceId),+ );++ const result = await findWakeableManagedDevices(+ caller,+ ['managed-a', 'managed-online', 'device-x', undefined, 'managed-a'],+ ['managed-online'],+ );++ expect(result).toEqual([{ deviceId: 'managed-a', scope: 'personal' }]);+ expect(mocks.queryDeviceList).not.toHaveBeenCalled();+ });++ it('asks the gateway when no online set is given', async () => {+ mocks.findPersonalByDeviceId.mockImplementation(async (deviceId: string) =>+ managedRow(deviceId),+ );+ mocks.queryDeviceList.mockResolvedValue([live('managed-online')]);++ const result = await findWakeableManagedDevices(caller, ['managed-a', 'managed-online']);++ expect(result).toEqual([{ deviceId: 'managed-a', scope: 'personal' }]);+ });++ it('addresses a workspace managed device through its workspace pool', async () => {+ mocks.findWorkspaceDeviceById.mockResolvedValue(managedRow('managed-w', 'ws-1'));++ const result = await findWakeableManagedDevices({ ...caller, workspaceId: 'ws-1' }, [+ 'managed-w',+ ]);++ expect(result).toEqual([{ deviceId: 'managed-w', scope: 'workspace', workspaceId: 'ws-1' }]);+ expect(mocks.queryDeviceList).toHaveBeenCalledWith('user-1', 'ws-1');+ });+});++describe('wakeManagedDevice', () => {+ it('passes the owner scope of the device to the provider and reports the acceptance', async () => {+ await expect(+ wakeManagedDevice('user-1', {+ deviceId: 'managed-w',+ scope: 'workspace',+ workspaceId: 'ws-1',+ }),+ ).resolves.toBe(true);++ expect(mocks.wake).toHaveBeenCalledWith({ userId: 'user-1', workspaceId: 'ws-1' }, 'managed-w');+ });++ it('logs a refused wake instead of throwing', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ mocks.wake.mockRejectedValue(new Error('quota'));++ await expect(+ wakeManagedDevice('user-1', { deviceId: 'managed-a', scope: 'personal' }),+ ).resolves.toBe(false);+ expect(mocks.wake).toHaveBeenCalledWith({ userId: 'user-1' }, 'managed-a');+ expect(warn).toHaveBeenCalledOnce();+ warn.mockRestore();+ });++ it('gives up on a wake request that hangs', async () => {+ vi.useFakeTimers();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ mocks.wake.mockReturnValue(new Promise(() => {}));++ const pending = wakeManagedDevice('user-1', { deviceId: 'managed-a', scope: 'personal' });+ await vi.advanceTimersByTimeAsync(MANAGED_DEVICE_WAKE_REQUEST_TIMEOUT_MS);++ await expect(pending).resolves.toBe(false);+ expect(warn).toHaveBeenCalledOnce();+ warn.mockRestore();+ });+});++describe('requestManagedDeviceWake', () => {+ it('wakes a managed device the caller can see and reports the acceptance', async () => {+ mocks.findPersonalByDeviceId.mockResolvedValue(managedRow('managed-a'));++ await expect(requestManagedDeviceWake(caller, 'managed-a')).resolves.toBe('accepted');+ expect(mocks.wake).toHaveBeenCalledWith({ userId: 'user-1' }, 'managed-a');+ });++ it('never wakes an ordinary connected device', async () => {+ mocks.findPersonalByDeviceId.mockResolvedValue(connectedRow('desktop-a'));++ await expect(requestManagedDeviceWake(caller, 'desktop-a')).resolves.toBe('not-managed');+ expect(mocks.wake).not.toHaveBeenCalled();+ });++ it('passes a refused wake to the caller', async () => {+ mocks.findPersonalByDeviceId.mockResolvedValue(managedRow('managed-a'));+ mocks.wake.mockRejectedValue(new Error('limit reached'));++ await expect(requestManagedDeviceWake(caller, 'managed-a')).rejects.toThrow('limit reached');+ });+});++describe('waitForManagedDeviceOnline', () => {+ const target = { deviceId: 'managed-a', scope: 'personal' } as const;++ it('resolves true once the device comes online within the timeout', async () => {+ vi.useFakeTimers();+ mocks.queryDeviceList+ .mockResolvedValueOnce([])+ .mockRejectedValueOnce(new Error('gateway blip'))+ .mockResolvedValueOnce([])+ .mockResolvedValue([live('managed-a')]);++ const pending = waitForManagedDeviceOnline('user-1', target);+ await vi.advanceTimersByTimeAsync(MANAGED_DEVICE_WAKE_POLL_INTERVAL_MS * 3);++ await expect(pending).resolves.toBe(true);+ expect(mocks.queryDeviceList).toHaveBeenCalledTimes(4);+ expect(mocks.queryDeviceList).toHaveBeenCalledWith('user-1', undefined);+ });++ it('resolves false when the device stays offline until the timeout', async () => {+ vi.useFakeTimers();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ const pending = waitForManagedDeviceOnline('user-1', target);+ await vi.advanceTimersByTimeAsync(MANAGED_DEVICE_WAKE_TIMEOUT_MS);++ await expect(pending).resolves.toBe(false);+ // One poll at the start, then one per interval until the deadline.+ expect(mocks.queryDeviceList).toHaveBeenCalledTimes(+ MANAGED_DEVICE_WAKE_TIMEOUT_MS / MANAGED_DEVICE_WAKE_POLL_INTERVAL_MS + 1,+ );+ expect(warn).toHaveBeenCalledOnce();+ warn.mockRestore();+ });++ it('ends early when the caller stops waiting', async () => {+ vi.useFakeTimers();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const shouldStop = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true);++ const pending = waitForManagedDeviceOnline('user-1', target, { shouldStop });+ await vi.advanceTimersByTimeAsync(MANAGED_DEVICE_WAKE_POLL_INTERVAL_MS);++ await expect(pending).resolves.toBe(false);+ expect(mocks.queryDeviceList).toHaveBeenCalledTimes(1);+ warn.mockRestore();+ });+});++describe('isDeviceUnreachableResult', () => {+ it('matches only failures where the device has no live connection', () => {+ expect(isDeviceUnreachableResult({ error: 'DEVICE_OFFLINE', success: false })).toBe(true);+ expect(+ isDeviceUnreachableResult({ errorData: { code: 'DEVICE_NOT_FOUND' }, success: false }),+ ).toBe(true);+ expect(isDeviceUnreachableResult({ error: 'File not found', success: false })).toBe(false);+ expect(isDeviceUnreachableResult({ error: 'DEVICE_OFFLINE', success: true })).toBe(false);+ });+});++describe('awaitManagedDeviceForToolCall', () => {+ it('wakes a starting managed device and returns DEVICE_WAKING with a retry hint', async () => {+ vi.useFakeTimers();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ mocks.findPersonalByDeviceId.mockResolvedValue(managedRow('managed-a'));++ const pending = awaitManagedDeviceForToolCall(caller, 'managed-a');+ await vi.advanceTimersByTimeAsync(MANAGED_DEVICE_TOOL_CALL_WAIT_MS);+ const result = await pending;++ expect(mocks.wake).toHaveBeenCalledWith({ userId: 'user-1' }, 'managed-a');+ expect(result).toMatchObject({+ error: {+ code: DEVICE_WAKING_ERROR_CODE,+ deviceId: 'managed-a',+ retryAfterSeconds: expect.any(Number),+ },+ success: false,+ });+ expect(typeof result === 'object' && result.content).toContain('Retry');+ warn.mockRestore();+ });++ it('answers online when the device connects during the wait', async () => {+ vi.useFakeTimers();+ mocks.findPersonalByDeviceId.mockResolvedValue(managedRow('managed-a'));+ mocks.queryDeviceList+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([])+ .mockResolvedValue([live('managed-a')]);++ const pending = awaitManagedDeviceForToolCall(caller, 'managed-a');+ await vi.advanceTimersByTimeAsync(MANAGED_DEVICE_WAKE_POLL_INTERVAL_MS);++ await expect(pending).resolves.toBe('online');+ });++ it('returns at once without waiting when the provider refuses the wake', async () => {+ vi.useFakeTimers();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ mocks.findPersonalByDeviceId.mockResolvedValue(managedRow('managed-a'));+ mocks.wake.mockRejectedValue(new Error('device is being deleted'));++ const settled = vi.fn();+ void awaitManagedDeviceForToolCall(caller, 'managed-a').then(settled);+ await vi.advanceTimersByTimeAsync(0);++ expect(settled).toHaveBeenCalledWith(undefined);+ expect(mocks.wake).toHaveBeenCalledOnce();+ // Only the online check before the wake; the wait loop never polls.+ expect(mocks.queryDeviceList).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ warn.mockRestore();+ });++ it('still waits for the device after an accepted wake', async () => {+ vi.useFakeTimers();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ mocks.findPersonalByDeviceId.mockResolvedValue(managedRow('managed-a'));++ const settled = vi.fn();+ const pending = awaitManagedDeviceForToolCall(caller, 'managed-a').then(settled);+ await vi.advanceTimersByTimeAsync(0);++ expect(settled).not.toHaveBeenCalled();+ expect(mocks.queryDeviceList.mock.calls.length).toBeGreaterThan(1);++ await vi.advanceTimersByTimeAsync(MANAGED_DEVICE_TOOL_CALL_WAIT_MS);+ await pending;+ expect(settled).toHaveBeenCalledWith(+ expect.objectContaining({+ error: expect.objectContaining({ code: DEVICE_WAKING_ERROR_CODE }),+ }),+ );+ warn.mockRestore();+ });++ it('leaves ordinary devices alone', async () => {+ mocks.findPersonalByDeviceId.mockResolvedValueOnce(connectedRow('device-x'));++ await expect(awaitManagedDeviceForToolCall(caller, 'device-x')).resolves.toBeUndefined();+ expect(mocks.wake).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/deviceGateway/managedDeviceWake.ts b/apps/server/src/services/deviceGateway/managedDeviceWake.tsnew file mode 100644index 00000000000..2be5625f3c6--- /dev/null+++ b/apps/server/src/services/deviceGateway/managedDeviceWake.ts@@ -0,0 +1,323 @@+import { type LobeChatDatabase } from '@lobechat/database';+import { isManagedCloudDevice } from '@lobechat/types';+import debug from 'debug';+import pMap from 'p-map';++import { managedDeviceProvider } from '@/business/server/managedDevice';+import { DeviceModel } from '@/database/models/device';++import { deviceGateway } from './index';++const log = debug('lobe-server:managed-device-wake');++/** How often a dispatch that waits for a woken managed device asks the gateway. */+export const MANAGED_DEVICE_WAKE_POLL_INTERVAL_MS = 2000;++/** How long a dispatch waits for a woken managed device before it gives up. */+export const MANAGED_DEVICE_WAKE_TIMEOUT_MS = 120_000;++/** The retry delay a `DEVICE_WAKING` tool result asks the model to wait. */+export const MANAGED_DEVICE_WAKING_RETRY_AFTER_SECONDS = 15;++/**+ * How long a tool call that reached a starting managed device waits for it+ * before answering `DEVICE_WAKING`. The model has no way to wait on its own,+ * so a short wait here saves a model step per retry.+ */+export const MANAGED_DEVICE_TOOL_CALL_WAIT_MS = 30_000;++/** The longest a wake request may hold its caller. */+export const MANAGED_DEVICE_WAKE_REQUEST_TIMEOUT_MS = 10_000;++/** Error code of a tool call that reached a managed cloud device while it starts. */+export const DEVICE_WAKING_ERROR_CODE = 'DEVICE_WAKING';++/** A managed cloud device as a run addresses it. */+export interface ManagedDeviceTarget {+ deviceId: string;+ /** Which principal pool holds the device. */+ scope: 'personal' | 'workspace';+ /** The device's workspace, set only for a workspace device (its gateway pool). */+ workspaceId?: string;+}++interface CallerScope {+ db: LobeChatDatabase;+ userId: string;+ /** The run's workspace; a personal device of the caller is still found. */+ workspaceId?: string;+}++/**+ * The managed cloud device behind `deviceId`, as the caller sees it.+ *+ * Returns `undefined` when the deployment offers no managed devices, the row+ * is not visible to the caller, or the device is an ordinary connected one.+ * A workspace row wins over a personal row with the same id, the same order+ * the dispatch paths use.+ */+const findManagedDevice = async (+ { db, userId, workspaceId }: CallerScope,+ deviceId: string,+): Promise<ManagedDeviceTarget | undefined> => {+ if (!managedDeviceProvider.isAvailable()) return;++ try {+ const model = new DeviceModel(db, userId, workspaceId);+ const workspaceRow = workspaceId ? await model.findWorkspaceDeviceById(deviceId) : undefined;+ const row = workspaceRow ?? (await model.findPersonalByDeviceId(deviceId));+ if (!row || !isManagedCloudDevice(row)) return;++ return row.workspaceId+ ? { deviceId, scope: 'workspace', workspaceId: row.workspaceId }+ : { deviceId, scope: 'personal' };+ } catch (error) {+ log('findManagedDevice: lookup failed for deviceId=%s: %O', deviceId, error);+ return;+ }+};++/** Whether the gateway has a live connection for this managed device now. */+const isManagedDeviceOnline = async (+ userId: string,+ target: ManagedDeviceTarget,+): Promise<boolean> => {+ const online = await deviceGateway.queryDeviceList(userId, target.workspaceId);+ return online.some((device) => device.deviceId === target.deviceId);+};++/**+ * The managed cloud devices among `candidateIds` that are offline and can be+ * woken. Feed the ids to `resolveExecutionPlan({ wakeableDeviceIds })`.+ *+ * Costs nothing when the deployment has no managed devices. When the caller+ * already knows the online set, pass it so no gateway read is made; otherwise+ * each managed candidate is checked with the gateway.+ */+export const findWakeableManagedDevices = async (+ caller: CallerScope,+ candidateIds: (string | null | undefined)[],+ onlineDeviceIds?: string[],+): Promise<ManagedDeviceTarget[]> => {+ // Without a gateway a woken device could never be reached.+ if (!managedDeviceProvider.isAvailable() || !deviceGateway.isConfigured) return [];++ const ids = [...new Set(candidateIds.filter((id): id is string => !!id))].filter(+ (id) => !onlineDeviceIds?.includes(id),+ );+ const targets = await pMap(+ ids,+ async (deviceId) => {+ const target = await findManagedDevice(caller, deviceId);+ if (!target) return;+ if (!onlineDeviceIds && (await isManagedDeviceOnline(caller.userId, target))) return;+ return target;+ },+ { concurrency: 3 },+ );++ return targets.filter((target): target is ManagedDeviceTarget => !!target);+};++/**+ * Ask the provider to start a managed device and wait until it accepts the+ * request. Throws when the provider refuses it or takes longer than+ * `MANAGED_DEVICE_WAKE_REQUEST_TIMEOUT_MS`.+ */+const requestProviderWake = async (userId: string, target: ManagedDeviceTarget): Promise<void> => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ managedDeviceProvider.wake(+ target.workspaceId ? { userId, workspaceId: target.workspaceId } : { userId },+ target.deviceId,+ ),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('Wake request timed out')),+ MANAGED_DEVICE_WAKE_REQUEST_TIMEOUT_MS,+ );+ }),+ ]);+ } finally {+ clearTimeout(timer);+ }+};++/**+ * Ask the provider to start a managed device. Resolves `true` when the provider+ * accepted the request, and `false` when it refused it (for example, the+ * device is being deleted) or did not answer in time. A failure is logged, not+ * thrown: the device stays offline, and every caller already handles an+ * offline device. A caller must not wait for a device after `false`, because+ * it will not come online. Never holds the caller longer than+ * `MANAGED_DEVICE_WAKE_REQUEST_TIMEOUT_MS`.+ */+export const wakeManagedDevice = async (+ userId: string,+ target: ManagedDeviceTarget,+): Promise<boolean> => {+ try {+ await requestProviderWake(userId, target);+ log('wakeManagedDevice: wake accepted for deviceId=%s', target.deviceId);+ return true;+ } catch (error) {+ console.warn('[ManagedDeviceWake] Wake request failed', {+ deviceId: target.deviceId,+ error: error instanceof Error ? error.message : String(error),+ userId,+ });+ return false;+ }+};++/**+ * Wake a managed cloud device because the user asked for it (the device+ * picker's wake control). Unlike {@link wakeManagedDevice}, the caller needs+ * the result:+ *+ * - `'not-managed'`: the deployment offers no managed devices, the row is not+ * visible to the caller, or the device is an ordinary connected one.+ * - `'accepted'`: the provider accepted the request. The device is not online+ * yet; watch the device list for that.+ *+ * Throws when the provider refuses the request or does not answer in time.+ */+export const requestManagedDeviceWake = async (+ caller: CallerScope,+ deviceId: string,+): Promise<'accepted' | 'not-managed'> => {+ const target = await findManagedDevice(caller, deviceId);+ if (!target) return 'not-managed';++ await requestProviderWake(caller.userId, target);+ log('requestManagedDeviceWake: wake accepted for deviceId=%s', deviceId);+ return 'accepted';+};++/**+ * Poll the gateway until a woken managed device connects. Resolves `true` when+ * it is online, and `false` when `timeoutMs` passes or `shouldStop` (asked+ * before each poll) answers true. A failed poll counts as "not online yet".+ *+ * The default timeout is long: call it with that default only off the request+ * path (after the response, or in a background job).+ */+export const waitForManagedDeviceOnline = async (+ userId: string,+ target: ManagedDeviceTarget,+ {+ shouldStop,+ timeoutMs = MANAGED_DEVICE_WAKE_TIMEOUT_MS,+ }: { shouldStop?: () => Promise<boolean>; timeoutMs?: number } = {},+): Promise<boolean> => {+ const startedAt = Date.now();+ const deadline = startedAt + timeoutMs;++ while (true) {+ try {+ if (await shouldStop?.()) return false;+ if (await isManagedDeviceOnline(userId, target)) {+ log(+ 'waitForManagedDeviceOnline: deviceId=%s online after %dms',+ target.deviceId,+ Date.now() - startedAt,+ );+ return true;+ }+ } catch (error) {+ log('waitForManagedDeviceOnline: poll failed: %O', error);+ }+ const remaining = deadline - Date.now();+ if (remaining <= 0) break;+ await new Promise<void>((resolve) =>+ setTimeout(resolve, Math.min(MANAGED_DEVICE_WAKE_POLL_INTERVAL_MS, remaining)),+ );+ }++ console.warn('[ManagedDeviceWake] Managed device did not come online in time', {+ deviceId: target.deviceId,+ scope: target.scope,+ userId,+ waitedMs: Date.now() - startedAt,+ workspaceId: target.workspaceId,+ });+ return false;+};++/** The structured tool result for a call that reached a managed device while it starts. */+export const buildDeviceWakingResult = (+ deviceId: string,+): {+ content: string;+ error: {+ code: typeof DEVICE_WAKING_ERROR_CODE;+ deviceId: string;+ message: string;+ retryAfterSeconds: number;+ };+ success: false;+} => {+ const message = `Device "${deviceId}" is a managed cloud device and is still starting. Nothing ran on it. Retry the same call in about ${MANAGED_DEVICE_WAKING_RETRY_AFTER_SECONDS} seconds; do not ask the user to reconnect it.`;++ return {+ content: message,+ error: {+ code: DEVICE_WAKING_ERROR_CODE,+ deviceId,+ message,+ retryAfterSeconds: MANAGED_DEVICE_WAKING_RETRY_AFTER_SECONDS,+ },+ success: false,+ };+};++const DEVICE_UNREACHABLE_CODES = [+ 'DEVICE_OFFLINE',+ 'DEVICE_NOT_FOUND',+ 'DEVICE_CHANNEL_UNAVAILABLE',+];++/**+ * Whether a failed device call failed because the device has no live+ * connection, as opposed to the tool itself failing on the device.+ */+export const isDeviceUnreachableResult = (result: {+ error?: unknown;+ errorData?: { code?: string } | null;+ success?: boolean;+}): boolean => {+ if (result.success) return false;+ if (result.errorData?.code && DEVICE_UNREACHABLE_CODES.includes(result.errorData.code))+ return true;+ return (+ typeof result.error === 'string' &&+ DEVICE_UNREACHABLE_CODES.some((code) => (result.error as string).includes(code))+ );+};++/**+ * Handle a call that reached a managed cloud device without a live+ * connection: wake the device and wait up to+ * `MANAGED_DEVICE_TOOL_CALL_WAIT_MS` for it.+ *+ * - `undefined`: not a managed device, none is available, or the provider+ * refused the wake. Report the failure as before.+ * - `'online'`: the device is online now. The caller can retry the call once.+ * - otherwise the `DEVICE_WAKING` result to return, so the model retries.+ */+export const awaitManagedDeviceForToolCall = async (+ caller: CallerScope,+ deviceId: string,+): Promise<'online' | ReturnType<typeof buildDeviceWakingResult> | undefined> => {+ const target = await findManagedDevice(caller, deviceId);+ if (!target) return;+ if (await isManagedDeviceOnline(caller.userId, target)) return 'online';++ // A refused wake will not bring the device online, so do not wait for it.+ if (!(await wakeManagedDevice(caller.userId, target))) return;+ const online = await waitForManagedDeviceOnline(caller.userId, target, {+ timeoutMs: MANAGED_DEVICE_TOOL_CALL_WAIT_MS,+ });+ return online ? 'online' : buildDeviceWakingResult(deviceId);+};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.managedDevice.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.managedDevice.test.tsnew file mode 100644index 00000000000..d7228e4ab97--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.managedDevice.test.ts@@ -0,0 +1,101 @@+import { LocalSystemApiName } from '@lobechat/builtin-tool-local-system';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as ManagedDeviceWake from '@/server/services/deviceGateway/managedDeviceWake';++import { type ToolExecutionContext } from '../../types';++const mocks = vi.hoisted(() => ({+ awaitManagedDeviceForToolCall: vi.fn(),+ executeToolCall: vi.fn(),+}));++vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({+ executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>+ mocks.executeToolCall(...args),+}));++vi.mock('@/server/services/deviceGateway/managedDeviceWake', async (importOriginal) => ({+ ...(await importOriginal<typeof ManagedDeviceWake>()),+ awaitManagedDeviceForToolCall: mocks.awaitManagedDeviceForToolCall,+}));++const { localSystemRuntime } = await import('../localSystem');++const context: ToolExecutionContext = {+ activeDeviceId: 'managed-a',+ activeDeviceScope: 'personal',+ serverDB: {} as any,+ toolManifestMap: {},+ userId: 'user-1',+};+const callReadFile = () => {+ const proxy = localSystemRuntime.factory(context) as Record<string, (args: any) => Promise<any>>;+ return proxy[LocalSystemApiName.readFile]({ path: '/tmp/a.txt' });+};+const offline = { content: 'offline', error: 'DEVICE_OFFLINE', success: false };++beforeEach(() => {+ vi.clearAllMocks();+});++describe('localSystemRuntime — managed cloud devices', () => {+ it('returns DEVICE_WAKING when the managed device is still starting', async () => {+ mocks.executeToolCall.mockResolvedValue(offline);+ mocks.awaitManagedDeviceForToolCall.mockResolvedValue({+ content: 'starting',+ error: {+ code: 'DEVICE_WAKING',+ deviceId: 'managed-a',+ message: 'starting',+ retryAfterSeconds: 15,+ },+ success: false,+ });++ const result = await callReadFile();++ expect(mocks.awaitManagedDeviceForToolCall).toHaveBeenCalledWith(+ expect.objectContaining({ userId: 'user-1' }),+ 'managed-a',+ );+ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ code: 'DEVICE_WAKING', kind: 'stop' });+ expect(mocks.executeToolCall).toHaveBeenCalledTimes(1);+ });++ it('sends the call once more when the device comes online during the wait', async () => {+ mocks.executeToolCall+ .mockResolvedValueOnce(offline)+ .mockResolvedValueOnce({ content: 'file body', success: true });+ mocks.awaitManagedDeviceForToolCall.mockResolvedValue('online');++ const result = await callReadFile();++ expect(mocks.executeToolCall).toHaveBeenCalledTimes(2);+ expect(result).toMatchObject({ content: 'file body', success: true });+ });++ it('keeps a tool failure on an online device as it was', async () => {+ mocks.executeToolCall.mockResolvedValue({+ content: 'ENOENT',+ error: 'File not found',+ success: false,+ });++ const result = await callReadFile();++ expect(mocks.awaitManagedDeviceForToolCall).not.toHaveBeenCalled();+ expect(result.content).toBe('ENOENT');+ });++ it('keeps the offline failure of an ordinary device', async () => {+ mocks.executeToolCall.mockResolvedValue(offline);+ mocks.awaitManagedDeviceForToolCall.mockResolvedValue(undefined);++ const result = await callReadFile();++ expect(result.content).toBe('offline');+ expect(mocks.executeToolCall).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.managedDevice.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.managedDevice.test.tsnew file mode 100644index 00000000000..89a958b7203--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.managedDevice.test.ts@@ -0,0 +1,77 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { type ToolExecutionContext } from '../../types';++const mocks = vi.hoisted(() => ({+ awaitManagedDeviceForToolCall: vi.fn(),+ getScopedOnlineDevices: vi.fn(),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: { queryDeviceList: vi.fn().mockResolvedValue([]) },+}));++vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({+ getScopedOnlineDevices: mocks.getScopedOnlineDevices,+}));++vi.mock('@/server/services/deviceGateway/managedDeviceWake', () => ({+ awaitManagedDeviceForToolCall: mocks.awaitManagedDeviceForToolCall,+}));++const { remoteDeviceRuntime } = await import('../remoteDevice');++const context: ToolExecutionContext = {+ activeDeviceScope: 'personal',+ serverDB: {} as any,+ toolManifestMap: {},+ userId: 'user-1',+};+const managedOnline = {+ deviceId: 'managed-a',+ hostname: 'managed-a',+ lastSeen: '2026-01-01T00:00:00.000Z',+ online: true,+ platform: 'linux',+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.getScopedOnlineDevices.mockResolvedValue([]);+});++describe('remoteDeviceRuntime — managed cloud devices', () => {+ it('wakes an offline managed device on activateDevice and reports DEVICE_WAKING', async () => {+ const waking = {+ content: 'starting',+ error: {+ code: 'DEVICE_WAKING',+ deviceId: 'managed-a',+ message: 'starting',+ retryAfterSeconds: 15,+ },+ success: false,+ };+ mocks.awaitManagedDeviceForToolCall.mockResolvedValue(waking);++ const runtime = remoteDeviceRuntime.factory(context) as any;+ const result = await runtime.activateDevice({ deviceId: 'managed-a' });++ expect(mocks.awaitManagedDeviceForToolCall).toHaveBeenCalledWith(+ { db: context.serverDB, userId: 'user-1', workspaceId: undefined },+ 'managed-a',+ );+ expect(result).toEqual(waking);+ });++ it('activates the managed device when it comes online during the wait', async () => {+ mocks.getScopedOnlineDevices.mockResolvedValueOnce([]).mockResolvedValue([managedOnline]);+ mocks.awaitManagedDeviceForToolCall.mockResolvedValue('online');++ const runtime = remoteDeviceRuntime.factory(context) as any;+ const result = await runtime.activateDevice({ deviceId: 'managed-a' });++ expect(result.success).toBe(true);+ expect(result.state).toMatchObject({ metadata: { activeDeviceId: 'managed-a' } });+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.tsindex e76ff81ef43..5f368374fe4 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts@@ -5,6 +5,10 @@ import {} from '@lobechat/builtin-tool-local-system';import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';+import {+ awaitManagedDeviceForToolCall,+ isDeviceUnreachableResult,+} from '@/server/services/deviceGateway/managedDeviceWake';import { buildDeviceLhEnv } from '@/server/services/toolExecution/preprocessLhCommand';import { buildNoActiveDeviceResult, REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';@@ -157,24 +161,40 @@ export const localSystemRuntime: ServerRuntimeRegistration = {}}- const result = await executeAuthorizedDeviceToolCall(- context.serverDB,- {- deviceId: context.activeDeviceId!,- operationId: context.operationId,- userId: context.userId!,- // Workspace devices live under the `workspace:<id>` principal in- // the gateway, so the relay needs the workspaceId to address the- // right DO pool. Personal device runs resolve to undefined.- workspaceId: await getDeviceWorkspaceId(),- },- {- apiName: api.name,- arguments: JSON.stringify(finalArgs),- identifier: LocalSystemIdentifier,- },- context.executionTimeoutMs,- );+ const deviceWorkspaceId = await getDeviceWorkspaceId();+ const execute = () =>+ executeAuthorizedDeviceToolCall(+ context.serverDB,+ {+ deviceId: context.activeDeviceId!,+ operationId: context.operationId,+ userId: context.userId!,+ // Workspace devices live under the `workspace:<id>` principal in+ // the gateway, so the relay needs the workspaceId to address the+ // right DO pool. Personal device runs resolve to undefined.+ workspaceId: deviceWorkspaceId,+ },+ {+ apiName: api.name,+ arguments: JSON.stringify(finalArgs),+ identifier: LocalSystemIdentifier,+ },+ context.executionTimeoutMs,+ );+ let result = await execute();++ // A managed cloud device that is asleep or still starting is woken and+ // waited for briefly. Nothing ran on it, so the call is sent once more+ // when it comes online; otherwise the model is told to retry rather+ // than to ask the user to reconnect a machine.+ if (isDeviceUnreachableResult(result) && context.serverDB) {+ const managed = await awaitManagedDeviceForToolCall(+ { db: context.serverDB, userId: context.userId!, workspaceId: deviceWorkspaceId },+ context.activeDeviceId!,+ );+ if (managed === 'online') result = await execute();+ else if (managed) return withoutDeviceReplay(managed);+ }return withoutDeviceReplay(result);};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts b/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.tsindex 27787e8cd58..d44ad576cde 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts@@ -6,6 +6,7 @@ import { RemoteDeviceExecutionRuntime } from '@lobechat/builtin-tool-remote-deviimport debug from 'debug';import { deviceGateway } from '@/server/services/deviceGateway';+import { awaitManagedDeviceForToolCall } from '@/server/services/deviceGateway/managedDeviceWake';import {filterAuthorizedDevicePresence,isGatewayOnlyDevicePresenceAllowed,@@ -88,6 +89,19 @@ export const remoteDeviceRuntime: ServerRuntimeRegistration = {);return devices;},+ // Activating an offline managed cloud device wakes it and waits briefly;+ // if it is still starting, the model is told to retry the activation.+ resolveOfflineDevice: async (deviceId) => {+ if (!serverDB) return;+ return awaitManagedDeviceForToolCall(+ {+ db: serverDB,+ userId,+ workspaceId: await resolveRunWorkspaceId(context),+ },+ deviceId,+ );+ },});},identifier: RemoteDeviceIdentifier,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex b46f3edd50f..ebc4cc693c8 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1555,6 +1555,10 @@"heteroAgent.executionTarget.title": "Execution Environment","heteroAgent.executionTarget.topicTag": "This topic","heteroAgent.executionTarget.unknownDevice": "Unknown device",+ "heteroAgent.executionTarget.wake": "Wake now",+ "heteroAgent.executionTarget.wakeFailed": "Could not wake this cloud device. Try again.",+ "heteroAgent.executionTarget.wakeStarting": "The cloud device is still starting. A run on it waits until it is ready.",+ "heteroAgent.executionTarget.wakesWhenUsed": "Wakes when used","heteroAgent.executionTarget.workspaceGroup": "Workspace Devices","heteroAgent.fullAccess.label": "Full access","heteroAgent.fullAccess.tooltip": "The local coding agent runs with full read/write access to the working directory. Switching permission modes is not available yet.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex b9e02891a0f..bd8c609d09c 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1555,6 +1555,10 @@"heteroAgent.executionTarget.title": "执行环境","heteroAgent.executionTarget.topicTag": "本话题","heteroAgent.executionTarget.unknownDevice": "未知设备",+ "heteroAgent.executionTarget.wake": "立即唤醒",+ "heteroAgent.executionTarget.wakeFailed": "无法唤醒此云端设备,请重试。",+ "heteroAgent.executionTarget.wakeStarting": "云端设备仍在启动,使用它的运行会等待其就绪。",+ "heteroAgent.executionTarget.wakesWhenUsed": "使用时自动唤醒","heteroAgent.executionTarget.workspaceGroup": "工作区设备","heteroAgent.fullAccess.label": "完全访问权限","heteroAgent.fullAccess.tooltip": "本地编码 Agent 运行时对工作目录拥有完全的读写权限。当前暂不支持切换权限模式。",diff --git a/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.test.tsindex 6b2e22c8c48..c57b2023241 100644--- a/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { RemoteDeviceExecutionRuntime } from './index';@@ -71,5 +71,35 @@ describe('RemoteDeviceExecutionRuntime', () => {expect(result.success).toBe(false);expect(result.content).toContain('listOnlineDevices');});++ it('reports what the host answers for an offline device it can start', async () => {+ const waking = {+ content: 'Device "managed-a" is starting now. Retry the same call.',+ error: { code: 'DEVICE_WAKING', message: 'starting' },+ success: false,+ };+ const resolveOfflineDevice = vi.fn().mockResolvedValue(waking);+ const runtime = new RemoteDeviceExecutionRuntime({+ queryDeviceList: async () => [],+ resolveOfflineDevice,+ });++ const result = await runtime.activateDevice({ deviceId: 'managed-a' });++ expect(resolveOfflineDevice).toHaveBeenCalledWith('managed-a');+ expect(result).toEqual(waking);+ });++ it('keeps the default answer when the host cannot start the device', async () => {+ const runtime = new RemoteDeviceExecutionRuntime({+ queryDeviceList: async () => [],+ resolveOfflineDevice: async () => undefined,+ });++ const result = await runtime.activateDevice({ deviceId: 'ghost' });++ expect(result.success).toBe(false);+ expect(result.content).toContain('listOnlineDevices');+ });});});diff --git a/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts b/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.tsindex 9164418ecfc..e8d67d07a6d 100644--- a/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts@@ -4,6 +4,16 @@ import { type DeviceAttachment } from './types';export interface RemoteDeviceRuntimeService {queryDeviceList: () => Promise<DeviceAttachment[]>;+ /**+ * Called when the model activates a device that is not online. A host that+ * can start the device (a managed cloud device) starts it, then returns+ * `'online'` when it came online (the list is read again), or the result to+ * report instead, such as a `DEVICE_WAKING` error that tells the model to+ * retry. Returning `undefined` keeps the default offline answer.+ */+ resolveOfflineDevice?: (+ deviceId: string,+ ) => Promise<BuiltinServerRuntimeOutput | 'online' | undefined>;}export class RemoteDeviceExecutionRuntime {@@ -37,8 +47,17 @@ export class RemoteDeviceExecutionRuntime {async activateDevice(args: { deviceId: string }): Promise<BuiltinServerRuntimeOutput> {try {- const devices = await this.service.queryDeviceList();- const target = devices.find((d) => d.deviceId === args.deviceId && d.online);+ const findOnline = async () =>+ (await this.service.queryDeviceList()).find(+ (d) => d.deviceId === args.deviceId && d.online,+ );+ let target = await findOnline();++ if (!target) {+ const resolved = await this.service.resolveOfflineDevice?.(args.deviceId);+ if (resolved === 'online') target = await findOnline();+ else if (resolved) return resolved;+ }if (!target) {// The device list can go stale between listOnlineDevices and this calldiff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex b7c64b27f4e..30406311918 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -963,6 +963,11 @@ export default {'heteroAgent.executionTarget.switchTopic.ok': 'Switch','heteroAgent.executionTarget.switchTopic.title': 'Move this topic to another environment?','heteroAgent.executionTarget.unknownDevice': 'Unknown device',+ 'heteroAgent.executionTarget.wake': 'Wake now',+ 'heteroAgent.executionTarget.wakeFailed': 'Could not wake this cloud device. Try again.',+ 'heteroAgent.executionTarget.wakeStarting':+ 'The cloud device is still starting. A run on it waits until it is ready.',+ 'heteroAgent.executionTarget.wakesWhenUsed': 'Wakes when used','hideForYou':"Direct message content is hidden. Please enable 'Show Direct Message Content' in settings to view.",'history.title': 'The Agent will keep only the latest {{count}} messages.',diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex db4e31f1b55..e1ec8ab3e73 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -491,6 +491,12 @@ export type ExecutionPlan = { target: DeviceExecutionTarget } &* (hetero dispatch).*/| { kind: 'device-unrouted'; reason: ExecutionPlanUnroutedReason }+ /**+ * Bound to a managed cloud device that is not online yet but can be woken.+ * The run stays on this device: callers wake it before they dispatch to it,+ * and tool calls that reach it while it starts answer `DEVICE_WAKING`.+ */+ | { deviceId: string; kind: 'device-wakeable' }/** plain chat — no execution environment, no run tools, no device ever */| { kind: 'none' }/** ephemeral cloud sandbox */diff --git a/packages/types/src/agent/executionTargetRules.test.ts b/packages/types/src/agent/executionTargetRules.test.tsindex 785b767e78b..f3b6217998c 100644--- a/packages/types/src/agent/executionTargetRules.test.ts+++ b/packages/types/src/agent/executionTargetRules.test.ts@@ -44,4 +44,16 @@ describe('describeLockedDevicePicker', () => {expect(hint).toContain('Tell the user to reconnect it (Acme desktop app or `lh connect`).');expect(hint).not.toContain('LobeHub');});++ it('tells the model to retry while a managed device starts', async () => {+ const describeLockedDevicePicker = await loadDescribe();+ const hint = describeLockedDevicePicker({+ deviceId: 'managed-a',+ kind: 'device-wakeable',+ target: 'device',+ });++ expect(hint).toContain('managed cloud device "managed-a", which is starting');+ expect(hint).toContain('DEVICE_WAKING');+ });});diff --git a/packages/types/src/agent/executionTargetRules.ts b/packages/types/src/agent/executionTargetRules.tsindex 86dd936ffe7..20e43222323 100644--- a/packages/types/src/agent/executionTargetRules.ts+++ b/packages/types/src/agent/executionTargetRules.ts@@ -31,19 +31,21 @@ export const executionTargetToRuntimeMode = (target: DeviceExecutionTarget): Run};export const isDeviceCapablePlan = (plan: ExecutionPlan): boolean =>- plan.kind === 'device' || plan.kind === 'device-unrouted';+ plan.kind === 'device' || plan.kind === 'device-unrouted' || plan.kind === 'device-wakeable';/*** The run is committed to ONE device: either already routed (`device`, which- * includes the opt-in `auto` single-online activation) or locked to an- * explicit binding that is currently offline (`bound-device-offline` waits for- * that machine rather than hopping elsewhere). A locked run has no device+ * includes the opt-in `auto` single-online activation), bound to a managed+ * cloud device that is starting (`device-wakeable`), or locked to an explicit+ * binding that is currently offline (`bound-device-offline` waits for that+ * machine rather than hopping elsewhere). A locked run has no device* decision left, so the remote-device picker must not exist for it — not even* as an activator-discoverable manifest, since explicit activation bypasses* the rule-layer gates.*/export const isDeviceLockedPlan = (plan: ExecutionPlan): boolean =>plan.kind === 'device' ||+ plan.kind === 'device-wakeable' ||(plan.kind === 'device-unrouted' && plan.reason === 'bound-device-offline');/**@@ -59,7 +61,15 @@ export const describeLockedDevicePicker = (plan: ExecutionPlan): string | undeficonst switchHint ='You cannot activate another device from here. If the user wants a different device, tell them to pick it in the device selector of the chat input and send the message again.';- return plan.kind === 'device'- ? `Device switching is off for this run: it is locked to device "${plan.deviceId}", where the Local System tools already run. ${switchHint}`- : `Device switching is off for this run: it is locked to the user's bound device, which is offline. Tell the user to reconnect it (${BRANDING_NAME} desktop app or \`lh connect\`). ${switchHint}`;+ switch (plan.kind) {+ case 'device': {+ return `Device switching is off for this run: it is locked to device "${plan.deviceId}", where the Local System tools already run. ${switchHint}`;+ }+ case 'device-wakeable': {+ return `Device switching is off for this run: it is locked to the managed cloud device "${plan.deviceId}", which is starting. Its tools answer DEVICE_WAKING until it is online; wait and retry them. ${switchHint}`;+ }+ default: {+ return `Device switching is off for this run: it is locked to the user's bound device, which is offline. Tell the user to reconnect it (${BRANDING_NAME} desktop app or \`lh connect\`). ${switchHint}`;+ }+ }};diff --git a/packages/types/src/managedDevice.test.ts b/packages/types/src/managedDevice.test.tsindex 65059b68d0b..4b511a7feb2 100644--- a/packages/types/src/managedDevice.test.ts+++ b/packages/types/src/managedDevice.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from 'vitest';-import { isManagedCloudDevice, MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from './managedDevice';+import {+ isManagedCloudDevice,+ isWakeableManagedDevice,+ MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+} from './managedDevice';describe('isManagedCloudDevice', () => {it('recognises only the managed identity source', () => {@@ -13,3 +17,24 @@ describe('isManagedCloudDevice', () => {expect(isManagedCloudDevice({})).toBe(false);});});++describe('isWakeableManagedDevice', () => {+ const managed = { identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE, online: false };++ it('accepts an offline managed device that sleeps, starts, or has no known phase', () => {+ expect(isWakeableManagedDevice({ ...managed, managedPhase: 'suspended' })).toBe(true);+ expect(isWakeableManagedDevice({ ...managed, managedPhase: 'suspending' })).toBe(true);+ expect(isWakeableManagedDevice({ ...managed, managedPhase: 'waking' })).toBe(true);+ expect(isWakeableManagedDevice(managed)).toBe(true);+ });++ it('refuses a managed device that failed or is being deleted', () => {+ expect(isWakeableManagedDevice({ ...managed, managedPhase: 'failed' })).toBe(false);+ expect(isWakeableManagedDevice({ ...managed, managedPhase: 'deleting' })).toBe(false);+ });++ it('refuses an online managed device and every ordinary device', () => {+ expect(isWakeableManagedDevice({ ...managed, online: true })).toBe(false);+ expect(isWakeableManagedDevice({ identitySource: 'machine-id', online: false })).toBe(false);+ });+});diff --git a/packages/types/src/managedDevice.ts b/packages/types/src/managedDevice.tsindex c0fbc3fca70..11b9100aa0d 100644--- a/packages/types/src/managedDevice.ts+++ b/packages/types/src/managedDevice.ts@@ -41,3 +41,21 @@ export type ManagedDevicePhase = (typeof MANAGED_DEVICE_PHASES)[number];/** Whether a device row is a managed cloud device. */export const isManagedCloudDevice = (device: { identitySource?: string | null }): boolean =>device.identitySource === MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE;++/** Phases from which the provider cannot bring a managed device online. */+const UNWAKEABLE_MANAGED_DEVICE_PHASES: readonly ManagedDevicePhase[] = ['deleting', 'failed'];++/**+ * Whether a device is a managed cloud device that is not online now but that+ * a run can wake. Such a device is a valid choice in a device picker: binding+ * it makes the run wake it before dispatch. An unknown phase counts as+ * wakeable, the same as the server's wake path.+ */+export const isWakeableManagedDevice = (device: {+ identitySource?: string | null;+ managedPhase?: ManagedDevicePhase;+ online: boolean;+}): boolean =>+ !device.online &&+ isManagedCloudDevice(device) &&+ !(device.managedPhase && UNWAKEABLE_MANAGED_DEVICE_PHASES.includes(device.managedPhase));diff --git a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsxindex 2fbc1f8942e..c8878f3283c 100644--- a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx+++ b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx@@ -11,6 +11,7 @@ import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/Exeimport { isDevicePresenceUnknown } from '@/store/device';import DeviceDetailPopover from './DeviceDetailPopover';+import { getDeviceOptionState } from './deviceOptionState';import { handleDeviceRowKeyDown } from './deviceRowKeyDown';import OptionRow from './OptionRow';@@ -45,16 +46,20 @@ const DeviceOptionRow = ({const { t } = useTranslation('chat');// A row restored from the persisted list is neither online nor offline yet.const presenceUnknown = isDevicePresenceUnknown(device);+ const { offlineLabelKey, reconnectLabelKey, selectable, showReconnect } = getDeviceOptionState(+ device,+ { presenceUnknown },+ );return (<DeviceDetailPopover device={device}><divdata-testid={`device-option-${device.deviceId}`}- onKeyDown={(event) => handleDeviceRowKeyDown(event, { disabled: !device.online, onSelect })}+ onKeyDown={(event) => handleDeviceRowKeyDown(event, { disabled: !selectable, onSelect })}><OptionRowactive={active}- disabled={!device.online}+ disabled={!selectable}icon={<ExecutionTargetIcon devicePlatform={device.platform} target={'device'} />}label={device.friendlyName || device.hostname || device.deviceId}tags={tags}@@ -64,7 +69,7 @@ const DeviceOptionRow = ({t('heteroAgent.executionTarget.gatewayDesc')) : (<ExecutionTargetDeviceStatus- offlineLabel={t('heteroAgent.executionTarget.offline')}+ offlineLabel={t(offlineLabelKey)}online={device.online}unknown={presenceUnknown}unknownLabel={t('heteroAgent.executionTarget.presenceChecking')}@@ -73,7 +78,7 @@ const DeviceOptionRow = ({})}/>)}- {device.online || presenceUnknown ? null : (+ {showReconnect ? (<ButtonclassName={stylex.props(styles.reconnectButton).className}icon={<Icon icon={RefreshCwIcon} size={10} />}@@ -85,9 +90,9 @@ const DeviceOptionRow = ({onReconnect();}}>- {t('heteroAgent.executionTarget.reconnect')}+ {t(reconnectLabelKey)}</Button>- )}+ ) : null}</>}onClick={onSelect}diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex f9e9b07c8bb..a00a45534a4 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -2,7 +2,8 @@import { isDesktop } from '@lobechat/const';import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';-import type { DeviceExecutionTarget } from '@lobechat/types';+import type { DeviceExecutionTarget, DeviceListItem } from '@lobechat/types';+import { isManagedCloudDevice } from '@lobechat/types';import { Button, Flexbox, Icon, Popover, toast, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';@@ -36,6 +37,7 @@ import {} from '@/helpers/executionTarget';import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { deviceService } from '@/services/device';import { localFileService } from '@/services/electron/localFileService';import { useAgentStore } from '@/store/agent';import { useDeviceList } from '@/store/device';@@ -46,6 +48,7 @@ import { formatLockedControlTooltip } from '../utils/lockedControlTooltip';import DeviceOptionRow from './DeviceOptionRow';import { getDevicePoolStatus } from './devicePoolStatus';import OptionRow from './OptionRow';+import { reconnectDevice } from './reconnectDevice';import { useSandboxNetworkToggle } from './useSandboxNetworkToggle';import { useTopicAwareTargetSelect } from './useTopicAwareTargetSelect';@@ -245,31 +248,36 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {const [reconnectingDeviceId, setReconnectingDeviceId] = useState<string>();const handleReconnectDevice = useCallback(- async (deviceId: string) => {- setReconnectingDeviceId(deviceId);+ async (device: DeviceListItem) => {+ const managed = isManagedCloudDevice(device);+ setReconnectingDeviceId(device.deviceId);try {- if (isDesktop && deviceId === currentDeviceId) {- await useElectronStore.getState().connectGateway();- } else {- window.location.href = `lobehub://device/reconnect?deviceId=${encodeURIComponent(deviceId)}`;- }-- // The deep link crosses browser → desktop → gateway → server, so give- // the live device registry a short window to converge instead of- // making the user close and reopen the picker to see the result.- let connected = false;- for (let attempt = 0; attempt < 8; attempt += 1) {- const nextDevices = await refreshDevices();- if (nextDevices?.some((device) => device.deviceId === deviceId && device.online)) {- connected = true;- break;- }- await new Promise((resolve) => setTimeout(resolve, 1000));- }- if (!connected) toast.error(t('heteroAgent.executionTarget.reconnectFailed'));+ // A connected device's deep link crosses browser → desktop → gateway →+ // server, and a woken managed device needs time to start, so poll the+ // device list instead of making the user close and reopen the picker.+ const outcome = await reconnectDevice(+ device,+ { isCurrentMachine: isDesktop && device.deviceId === currentDeviceId },+ {+ connectGateway: () => useElectronStore.getState().connectGateway(),+ openDeepLink: (url) => {+ window.location.href = url;+ },+ refreshDevices,+ wakeManagedDevice: (input) => deviceService.wakeManagedDevice(input),+ },+ );+ if (outcome === 'failed') toast.error(t('heteroAgent.executionTarget.reconnectFailed'));+ if (outcome === 'starting') toast.info(t('heteroAgent.executionTarget.wakeStarting'));} catch (error) {console.error('Device reconnect failed:', error);- toast.error(t('heteroAgent.executionTarget.reconnectFailed'));+ toast.error(+ t(+ managed+ ? 'heteroAgent.executionTarget.wakeFailed'+ : 'heteroAgent.executionTarget.reconnectFailed',+ ),+ );} finally {setReconnectingDeviceId(undefined);}@@ -533,7 +541,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {isActive('device', d.deviceId),isCurrentMachine ? [t('heteroAgent.executionTarget.gateway')] : [],)}- onReconnect={() => void handleReconnectDevice(d.deviceId)}+ onReconnect={() => void handleReconnectDevice(d)}onSelect={() => void handleSelect('device', d.deviceId)}/>);diff --git a/src/features/ChatInput/ControlBar/__tests__/deviceOptionState.test.ts b/src/features/ChatInput/ControlBar/__tests__/deviceOptionState.test.tsnew file mode 100644index 00000000000..56f95083bf0--- /dev/null+++ b/src/features/ChatInput/ControlBar/__tests__/deviceOptionState.test.ts@@ -0,0 +1,64 @@+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { resolveExecutionPlan } from '@/helpers/executionTarget';++import { getDeviceOptionState } from '../deviceOptionState';++const sleepingManaged = {+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ managedPhase: 'suspended' as const,+ online: false,+};+const known = { presenceUnknown: false };++describe('getDeviceOptionState', () => {+ // Regression: a sleeping managed device was disabled like an offline+ // machine, so the run fell back to the cloud sandbox and never woke it.+ it('lets the user pick a sleeping managed device, and the bound run wakes it', () => {+ expect(getDeviceOptionState(sleepingManaged, known)).toEqual({+ offlineLabelKey: 'heteroAgent.executionTarget.wakesWhenUsed',+ reconnectLabelKey: 'heteroAgent.executionTarget.wake',+ selectable: true,+ showReconnect: true,+ });++ // Picking the row binds the device. The server lists the bound device as+ // wakeable, so the plan wakes it instead of falling back to the sandbox.+ expect(+ resolveExecutionPlan({+ agencyConfig: { boundDeviceId: 'managed-a', executionTarget: 'device' },+ clientExecutionAvailable: true,+ onlineDeviceIds: [],+ wakeableDeviceIds: ['managed-a'],+ }),+ ).toEqual({ deviceId: 'managed-a', kind: 'device-wakeable', target: 'device' });+ });++ it('keeps a managed device that cannot be woken unselectable and without a control', () => {+ expect(getDeviceOptionState({ ...sleepingManaged, managedPhase: 'failed' }, known)).toEqual({+ offlineLabelKey: 'heteroAgent.executionTarget.offline',+ reconnectLabelKey: 'heteroAgent.executionTarget.reconnect',+ selectable: false,+ showReconnect: false,+ });+ });++ it('keeps an offline connected device unselectable with its desktop reconnect', () => {+ expect(getDeviceOptionState({ identitySource: 'machine-id', online: false }, known)).toEqual({+ offlineLabelKey: 'heteroAgent.executionTarget.offline',+ reconnectLabelKey: 'heteroAgent.executionTarget.reconnect',+ selectable: false,+ showReconnect: true,+ });+ });++ it('shows no control on an online device or a row whose presence is unknown', () => {+ expect(+ getDeviceOptionState({ identitySource: 'machine-id', online: true }, known),+ ).toMatchObject({ selectable: true, showReconnect: false });+ expect(getDeviceOptionState(sleepingManaged, { presenceUnknown: true }).showReconnect).toBe(+ false,+ );+ });+});diff --git a/src/features/ChatInput/ControlBar/__tests__/reconnectDevice.test.ts b/src/features/ChatInput/ControlBar/__tests__/reconnectDevice.test.tsnew file mode 100644index 00000000000..cbdb06107c7--- /dev/null+++ b/src/features/ChatInput/ControlBar/__tests__/reconnectDevice.test.ts@@ -0,0 +1,117 @@+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { MANAGED_DEVICE_WAKE_POLL, reconnectDevice } from '../reconnectDevice';++const managed = {+ deviceId: 'managed-a',+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ scope: 'workspace' as const,+};+const desktop = { deviceId: 'desktop-a', identitySource: 'machine-id', scope: 'personal' as const };++const deps = (onlineAfter = 1) => {+ let calls = 0;+ return {+ connectGateway: vi.fn().mockResolvedValue(undefined),+ openDeepLink: vi.fn(),+ refreshDevices: vi.fn(async () => {+ calls += 1;+ return calls >= onlineAfter+ ? [+ { deviceId: 'managed-a', online: true },+ { deviceId: 'desktop-a', online: true },+ ]+ : [];+ }) as never,+ sleep: vi.fn().mockResolvedValue(undefined),+ wakeManagedDevice: vi.fn().mockResolvedValue({ success: true }),+ };+};++describe('reconnectDevice', () => {+ it('wakes a managed cloud device through the server, not the desktop deep link', async () => {+ const d = deps(3);++ await expect(reconnectDevice(managed, { isCurrentMachine: false }, d)).resolves.toBe(+ 'connected',+ );+ expect(d.wakeManagedDevice).toHaveBeenCalledWith({ deviceId: 'managed-a', scope: 'workspace' });+ expect(d.openDeepLink).not.toHaveBeenCalled();+ expect(d.connectGateway).not.toHaveBeenCalled();+ // The list refresh is also what shows the device's new phase.+ expect(d.refreshDevices).toHaveBeenCalledTimes(3);+ });++ it('reports a managed device that is still starting after the wait', async () => {+ const d = deps(Number.POSITIVE_INFINITY);++ await expect(reconnectDevice(managed, { isCurrentMachine: false }, d)).resolves.toBe(+ 'starting',+ );+ expect(d.refreshDevices).toHaveBeenCalledTimes(MANAGED_DEVICE_WAKE_POLL.attempts);+ expect(d.sleep).toHaveBeenCalledWith(MANAGED_DEVICE_WAKE_POLL.intervalMs);+ });++ it('keeps polling after a failed list refresh and reports the device online', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const d = deps();+ const refreshDevices = d.refreshDevices as unknown as ReturnType<typeof vi.fn>;+ refreshDevices.mockRejectedValueOnce(new Error('network'));++ await expect(reconnectDevice(managed, { isCurrentMachine: false }, d)).resolves.toBe(+ 'connected',+ );+ expect(d.refreshDevices).toHaveBeenCalledTimes(2);+ expect(d.wakeManagedDevice).toHaveBeenCalledOnce();+ warn.mockRestore();+ });++ it('reports starting, not a failed wake, when every list refresh fails', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const d = deps();+ const refreshDevices = d.refreshDevices as unknown as ReturnType<typeof vi.fn>;+ refreshDevices.mockRejectedValue(new Error('network'));++ await expect(reconnectDevice(managed, { isCurrentMachine: false }, d)).resolves.toBe(+ 'starting',+ );+ expect(d.refreshDevices).toHaveBeenCalledTimes(MANAGED_DEVICE_WAKE_POLL.attempts);+ expect(d.wakeManagedDevice).toHaveBeenCalledOnce();+ warn.mockRestore();+ });++ it('passes a refused wake to the caller', async () => {+ const d = deps();+ d.wakeManagedDevice.mockRejectedValue(new Error('refused'));++ await expect(reconnectDevice(managed, { isCurrentMachine: false }, d)).rejects.toThrow(+ 'refused',+ );+ expect(d.openDeepLink).not.toHaveBeenCalled();+ });++ it('keeps the desktop deep link for a connected device', async () => {+ const d = deps();++ await expect(reconnectDevice(desktop, { isCurrentMachine: false }, d)).resolves.toBe(+ 'connected',+ );+ expect(d.openDeepLink).toHaveBeenCalledWith('lobehub://device/reconnect?deviceId=desktop-a');+ expect(d.wakeManagedDevice).not.toHaveBeenCalled();+ });++ it("reconnects this desktop app's own gateway connection", async () => {+ const d = deps();++ await reconnectDevice(desktop, { isCurrentMachine: true }, d);+ expect(d.connectGateway).toHaveBeenCalledOnce();+ expect(d.openDeepLink).not.toHaveBeenCalled();+ });++ it('reports a connected device that did not come back', async () => {+ const d = deps(Number.POSITIVE_INFINITY);++ await expect(reconnectDevice(desktop, { isCurrentMachine: false }, d)).resolves.toBe('failed');+ });+});diff --git a/src/features/ChatInput/ControlBar/deviceOptionState.ts b/src/features/ChatInput/ControlBar/deviceOptionState.tsnew file mode 100644index 00000000000..30922faf911--- /dev/null+++ b/src/features/ChatInput/ControlBar/deviceOptionState.ts@@ -0,0 +1,45 @@+import { isManagedCloudDevice, isWakeableManagedDevice } from '@lobechat/types';++export interface DeviceOptionState {+ /** Locale key (namespace `chat`) for an offline row's status. */+ offlineLabelKey:+ 'heteroAgent.executionTarget.offline' | 'heteroAgent.executionTarget.wakesWhenUsed';+ /** Locale key (namespace `chat`) for the row's reconnect or wake control. */+ reconnectLabelKey: 'heteroAgent.executionTarget.reconnect' | 'heteroAgent.executionTarget.wake';+ /** Whether the user may pick the row. */+ selectable: boolean;+ /** Whether the row shows its reconnect or wake control. */+ showReconnect: boolean;+}++/**+ * How one device row of the execution environment picker behaves.+ *+ * - An online device is selectable.+ * - A managed cloud device that sleeps is selectable too: a run bound to it+ * wakes it before dispatch. It reads "Wakes when used", and its control+ * wakes it through the server.+ * - Any other offline device is not selectable, and its control reconnects+ * it through the desktop app.+ * - A managed device that cannot be woken (failed, deleting) has no control:+ * the desktop app cannot reach it.+ */+export const getDeviceOptionState = (+ // Structural, so a `managedPhase` on the list row narrows it when present.+ device: Parameters<typeof isWakeableManagedDevice>[0],+ { presenceUnknown }: { presenceUnknown: boolean },+): DeviceOptionState => {+ const wakeable = isWakeableManagedDevice(device);++ return {+ offlineLabelKey: wakeable+ ? 'heteroAgent.executionTarget.wakesWhenUsed'+ : 'heteroAgent.executionTarget.offline',+ reconnectLabelKey: wakeable+ ? 'heteroAgent.executionTarget.wake'+ : 'heteroAgent.executionTarget.reconnect',+ selectable: device.online || wakeable,+ showReconnect:+ !device.online && !presenceUnknown && (wakeable || !isManagedCloudDevice(device)),+ };+};diff --git a/src/features/ChatInput/ControlBar/reconnectDevice.ts b/src/features/ChatInput/ControlBar/reconnectDevice.tsnew file mode 100644index 00000000000..b30ae79d817--- /dev/null+++ b/src/features/ChatInput/ControlBar/reconnectDevice.ts@@ -0,0 +1,78 @@+import type { DeviceListItem, DeviceScope } from '@lobechat/types';+import { isManagedCloudDevice } from '@lobechat/types';++/**+ * How the picker's reconnect control ended:+ * - `connected`: the device is online now.+ * - `starting`: a managed cloud device accepted the wake but is not online+ * yet. A run bound to it still wakes it and waits.+ * - `failed`: a connected device did not come back.+ */+export type ReconnectOutcome = 'connected' | 'failed' | 'starting';++export interface ReconnectDeviceDeps {+ /** Reconnect this desktop app's own gateway connection. */+ connectGateway: () => Promise<unknown>;+ /** Open a desktop deep link. */+ openDeepLink: (url: string) => void;+ /** Fetch the device list again; resolves with the new list. */+ refreshDevices: () => Promise<DeviceListItem[] | undefined>;+ sleep?: (ms: number) => Promise<void>;+ /** Ask a managed cloud device to start. */+ wakeManagedDevice: (input: { deviceId: string; scope: DeviceScope }) => Promise<unknown>;+}++/** A connected device comes back in seconds once its app gets the deep link. */+export const DEVICE_RECONNECT_POLL = { attempts: 8, intervalMs: 1000 };++/** A managed cloud device can take up to two minutes to start. */+export const MANAGED_DEVICE_WAKE_POLL = { attempts: 40, intervalMs: 3000 };++const defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));++/**+ * Bring a device back online from the device picker, then poll the device+ * list until it is online. The list refresh also refreshes a managed+ * device's phase.+ *+ * - A managed cloud device is woken through the server. It has no desktop app,+ * so the desktop deep link cannot reach it.+ * - This desktop app's own device reconnects its gateway connection.+ * - Any other device gets the `lobehub://` deep link for its desktop app.+ *+ * A failed wake or reconnect request throws. A failed list refresh does not:+ * it counts as one poll in which the device is not online yet, so a passing+ * network error after an accepted wake still ends as `starting`, and the user+ * is not asked to send a second wake.+ */+export const reconnectDevice = async (+ device: Pick<DeviceListItem, 'deviceId' | 'identitySource' | 'scope'>,+ { isCurrentMachine }: { isCurrentMachine: boolean },+ deps: ReconnectDeviceDeps,+): Promise<ReconnectOutcome> => {+ const { deviceId } = device;+ const managed = isManagedCloudDevice(device);+ const sleep = deps.sleep ?? defaultSleep;++ if (managed) {+ await deps.wakeManagedDevice({ deviceId, scope: device.scope });+ } else if (isCurrentMachine) {+ await deps.connectGateway();+ } else {+ deps.openDeepLink(`lobehub://device/reconnect?deviceId=${encodeURIComponent(deviceId)}`);+ }++ const poll = managed ? MANAGED_DEVICE_WAKE_POLL : DEVICE_RECONNECT_POLL;+ for (let attempt = 0; attempt < poll.attempts; attempt += 1) {+ let nextDevices: DeviceListItem[] | undefined;+ try {+ nextDevices = await deps.refreshDevices();+ } catch (error) {+ console.warn('Device list refresh failed while waiting for a device:', error);+ }+ if (nextDevices?.some((item) => item.deviceId === deviceId && item.online)) return 'connected';+ await sleep(poll.intervalMs);+ }++ return managed ? 'starting' : 'failed';+};diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.tsindex f84bdf76fc5..793d9983f31 100644--- a/src/helpers/executionTarget.ts+++ b/src/helpers/executionTarget.ts@@ -389,7 +389,8 @@ export const resolveRuntimeMode = (export type { ExecutionPlan, ExecutionPlanUnroutedReason } from '@lobechat/types';-export type ExecutionManifestEnvironment = ExecutionPlan['kind'] | 'local';+export type ExecutionManifestEnvironment =+ Exclude<ExecutionPlan['kind'], 'device-wakeable'> | 'local';/*** Preserve the desktop-local capability signal after the server resolves that@@ -401,10 +402,21 @@ export type ExecutionManifestEnvironment = ExecutionPlan['kind'] | 'local';export const executionPlanToManifestExecutionEnv = (plan: ExecutionPlan,localDeviceId?: string,-): ExecutionManifestEnvironment =>- plan.kind === 'device' && plan.target === 'local' && plan.deviceId === localDeviceId- ? 'local'- : plan.kind;+): ExecutionManifestEnvironment => {+ switch (plan.kind) {+ case 'device': {+ return plan.target === 'local' && plan.deviceId === localDeviceId ? 'local' : 'device';+ }+ // A waking managed device is where commands run once it is online; until+ // then its tools answer `DEVICE_WAKING` instead of falling back elsewhere.+ case 'device-wakeable': {+ return 'device';+ }+ default: {+ return plan.kind;+ }+ }+};export interface ResolveExecutionPlanParams {agencyConfig: LobeAgentAgencyConfig | undefined;@@ -462,6 +474,15 @@ export interface ResolveExecutionPlanParams {* `resolveExecutionPlan`.*/trigger?: RequestTrigger;+ /**+ * Managed cloud devices this run could wake: devices that are not online+ * now but that the managed device provider can start. A bound or requested+ * device in this list resolves to `device-wakeable` instead of+ * `bound-device-offline` (or, without online info, instead of a `device`+ * dispatch that would fail at the gateway). Server callers compute it; it is+ * empty when the deployment has no managed devices.+ */+ wakeableDeviceIds?: string[];/** See {@link ResolveExecutionTargetOptions.workspaceScoped}. */workspaceScoped?: boolean;}@@ -483,6 +504,9 @@ export interface ResolveExecutionPlanParams {* run auto-activates ONLY in the opt-in `auto` mode (single device → use it;* several → stay unrouted so the model picks one). `local` / `device` never* silently grab a device — they stay unrouted until one is bound/requested.+ * 5. A bound device that is not online but is listed in `wakeableDeviceIds`+ * (a managed cloud device) resolves to `device-wakeable`: the caller wakes+ * it and the run stays on it.* Bot triggers coerce a `local` target to `auto` upstream in* `resolveExecutionTarget` (not here) — by the time the plan resolves, a bot* run already carries `target: 'auto'` and follows the auto-activation rules@@ -501,6 +525,7 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): ExecutsandboxExecutionAvailable,sandboxFallback,trigger,+ wakeableDeviceIds,workspaceScoped,} = params;@@ -563,6 +588,11 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut// keep `auto` / `local` distinct, everything else collapses to `device`.const effectiveTarget = target === 'local' ? 'local' : target === 'auto' ? 'auto' : 'device';+ const isOnline = (deviceId: string) => !!onlineDeviceIds?.includes(deviceId);+ if (boundDeviceId && !isOnline(boundDeviceId) && wakeableDeviceIds?.includes(boundDeviceId)) {+ return { deviceId: boundDeviceId, kind: 'device-wakeable', target: effectiveTarget };+ }+// No online info: trust the binding (the gateway errors on dispatch if the// device is offline). No auto-activation without visibility.if (!onlineDeviceIds) {diff --git a/src/helpers/executionTarget.wakeable.test.ts b/src/helpers/executionTarget.wakeable.test.tsnew file mode 100644index 00000000000..279897f9de7--- /dev/null+++ b/src/helpers/executionTarget.wakeable.test.ts@@ -0,0 +1,119 @@+import type { LobeAgentAgencyConfig } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ type ExecutionPlan,+ executionPlanToManifestExecutionEnv,+ isDeviceCapablePlan,+ isDeviceLockedPlan,+ resolveExecutionPlan,+} from './executionTarget';++const cfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfig => ({ ...over });+const ONLINE_AB = ['device-a', 'device-b'];++describe('resolveExecutionPlan — wakeableDeviceIds (managed cloud devices)', () => {+ it('wakes an offline bound managed device instead of leaving the run unrouted', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'managed-a', executionTarget: 'device' }),+ clientExecutionAvailable: true,+ onlineDeviceIds: ONLINE_AB,+ wakeableDeviceIds: ['managed-a'],+ }),+ ).toEqual({ deviceId: 'managed-a', kind: 'device-wakeable', target: 'device' });+ });++ it('wakes a requested managed device and keeps the local target', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ executionTarget: 'local' }),+ clientExecutionAvailable: true,+ onlineDeviceIds: [],+ requestedDeviceId: 'managed-a',+ wakeableDeviceIds: ['managed-a'],+ }),+ ).toEqual({ deviceId: 'managed-a', kind: 'device-wakeable', target: 'local' });+ });++ it('wakes the bound managed device for hetero dispatch without online info', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'managed-a', executionTarget: 'device' }),+ clientExecutionAvailable: false,+ isHetero: true,+ wakeableDeviceIds: ['managed-a'],+ }),+ ).toEqual({ deviceId: 'managed-a', kind: 'device-wakeable', target: 'device' });+ });++ it('routes to the device when it is already online', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'device' }),+ clientExecutionAvailable: true,+ onlineDeviceIds: ONLINE_AB,+ wakeableDeviceIds: ['device-a'],+ }),+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'device' });+ });++ it('keeps an offline ordinary device unrouted', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-x', executionTarget: 'device' }),+ clientExecutionAvailable: true,+ onlineDeviceIds: ONLINE_AB,+ wakeableDeviceIds: ['managed-a'],+ }),+ ).toEqual({ kind: 'device-unrouted', reason: 'bound-device-offline', target: 'device' });+ });++ it('never wakes a device for a run that may not use one', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'managed-a', executionTarget: 'device' }),+ canUseDevice: false,+ clientExecutionAvailable: true,+ onlineDeviceIds: [],+ wakeableDeviceIds: ['managed-a'],+ }),+ ).toEqual({ kind: 'none', target: 'none' });+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'managed-a', executionTarget: 'sandbox' }),+ clientExecutionAvailable: true,+ onlineDeviceIds: [],+ wakeableDeviceIds: ['managed-a'],+ }),+ ).toEqual({ kind: 'sandbox', target: 'sandbox' });+ });++ it('ignores a stale binding in auto mode', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'managed-a', executionTarget: 'auto' }),+ clientExecutionAvailable: true,+ onlineDeviceIds: [],+ wakeableDeviceIds: ['managed-a'],+ }),+ ).toEqual({ kind: 'device-unrouted', reason: 'no-online-device', target: 'auto' });+ });+});++describe('device-wakeable plan consumers', () => {+ const plan: ExecutionPlan = {+ deviceId: 'managed-a',+ kind: 'device-wakeable',+ target: 'device',+ };++ it('locks the run to the waking device and keeps it device-capable', () => {+ expect(isDeviceLockedPlan(plan)).toBe(true);+ expect(isDeviceCapablePlan(plan)).toBe(true);+ });++ it('describes the waking device as the device it runs on, not as unrouted', () => {+ expect(executionPlanToManifestExecutionEnv(plan)).toBe('device');+ });+});diff --git a/src/hooks/useRemoteAgentDeviceGuard.test.ts b/src/hooks/useRemoteAgentDeviceGuard.test.tsindex 9303f9a3867..06f4864daff 100644--- a/src/hooks/useRemoteAgentDeviceGuard.test.ts+++ b/src/hooks/useRemoteAgentDeviceGuard.test.ts@@ -3,6 +3,7 @@*/import { randomUUID } from 'node:crypto';+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';import { act, renderHook, waitFor } from '@testing-library/react';import type { PropsWithChildren } from 'react';import { createElement, useEffect } from 'react';@@ -320,4 +321,36 @@ describe('useRemoteAgentDeviceGuard', () => {await waitFor(() => expect(result.current.status).toBe('ok'));});+ // Regression: a sleeping managed cloud device raised the offline banner, so+ // the run never reached the dispatch that wakes it.+ it('lets a CLI agent send to a sleeping managed cloud device', async () => {+ bindCodexTo('managed-a');+ mockedListDevices.mockResolvedValue([+ {+ deviceId: 'managed-a',+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ managedPhase: 'suspended',+ online: false,+ },+ ] as never);++ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {+ wrapper,+ });++ await waitFor(() => expect(result.current.status).toBe('ok'));+ });++ it('still blocks an offline ordinary device next to that rule', async () => {+ bindCodexTo('desktop-a');+ mockedListDevices.mockResolvedValue([+ { deviceId: 'desktop-a', identitySource: 'machine-id', online: false },+ ] as never);++ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {+ wrapper,+ });++ await waitFor(() => expect(result.current.status).toBe('device-offline'));+ });});diff --git a/src/hooks/useRemoteAgentDeviceGuard.ts b/src/hooks/useRemoteAgentDeviceGuard.tsindex 504b2a23dd9..bd21829784a 100644--- a/src/hooks/useRemoteAgentDeviceGuard.ts+++ b/src/hooks/useRemoteAgentDeviceGuard.ts@@ -1,4 +1,5 @@import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';+import { isWakeableManagedDevice } from '@lobechat/types';import { useCallback, useEffect, useState } from 'react';import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';@@ -75,7 +76,11 @@ export const useRemoteAgentDeviceGuard = ({// which is intentionally absent from the caller-scoped device list. The// server owns that routing decision; absence here is not proof of offline.if (!device) return 'ok';- if (!device.online) return 'device-offline';+ // A sleeping managed cloud device is woken by the dispatch itself. A+ // notify-based platform still needs a live device to probe and run on.+ if (!device.online) {+ return isWakeableManagedDevice(device) && !remoteType ? 'ok' : 'device-offline';+ }return remoteType ? 'capability' : 'ok';})();diff --git a/src/services/device.ts b/src/services/device.tsindex 4df7fdbfd7b..e5b13ec4d90 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -31,6 +31,16 @@ class DeviceService {return createWorkspaceLambdaClient(null).device.updateDevice.mutate(input);}+ /**+ * Ask a managed cloud device to start. Resolves when the request is+ * accepted, not when the device is online. Routed by the device's own+ * scope, like the other per-device writes.+ */+ wakeManagedDevice({ deviceId, scope }: { deviceId: string; scope: DeviceScope }) {+ const client = scope === 'personal' ? createWorkspaceLambdaClient(null) : lambdaClient;+ return client.device.wakeManagedDevice.mutate({ deviceId });+ }+/** Update user-editable fields of a workspace-enrolled device (workspace-scoped write). */updateWorkspaceDevice(input: Parameters<DeviceClient['updateWorkspaceDevice']['mutate']>[0]) {return lambdaClient.device.updateWorkspaceDevice.mutate(input);