π€― 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
π fix(agent): do not adopt a device a run may not use (#19709)
Arvin Xuf653241d16d3
diff --git a/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts b/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.tsindex eb8a6c55e92..8d23311dfb2 100644--- a/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts+++ b/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts@@ -11,6 +11,11 @@ import { isDeviceCapablePlan } from '@/helpers/executionTarget';* `callToolsBatch`) must read the id through this filter. Plans absent on* old / resumed operations fall back to the policy-only gate.*+ * {@link runMayUseDevice} is that authority on its own: the step boundary asks it+ * before binding a device out of the message history at all, so a run that may+ * not touch a device never adopts one β and never leaks its working directory+ * and system info into the prompt variables.+ ** `device-unrouted` deliberately passes the id through (via* `isDeviceCapablePlan`): the run-start id is derived strictly from the plan* (`aiAgent` sets it only for `kind === 'device'`), so an id appearing under@@ -20,14 +25,14 @@ import { isDeviceCapablePlan } from '@/helpers/executionTarget';* next step boundary while the plan still says unrouted. Tightening the gate to* `kind === 'device'` would swallow exactly that flow.*/-export const resolveRunActiveDeviceId = (- state: Pick<AgentState, 'binding' | 'plan' | 'principal'>,-): string | undefined => {+export const runMayUseDevice = (state: Pick<AgentState, 'plan' | 'principal'>): boolean => {const devicePolicy = state.principal?.policy?.deviceAccess;const executionPlan = state.plan?.execution;const planAllowsDevice = !executionPlan || isDeviceCapablePlan(executionPlan);- if (devicePolicy?.canUseDevice === false || !planAllowsDevice) return undefined;-- return state.binding?.device?.id;+ return devicePolicy?.canUseDevice !== false && planAllowsDevice;};++export const resolveRunActiveDeviceId = (+ state: Pick<AgentState, 'binding' | 'plan' | 'principal'>,+): string | undefined => (runMayUseDevice(state) ? state.binding?.device?.id : undefined);diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex 08f9829500d..66ca79ac352 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -990,6 +990,48 @@ describe('AgentRuntimeService', () => {},);+ // The executors read the device id through the same gate, so binding one for+ // a run that may not touch a device buys nothing β and its working directory+ // and system info would ride into the prompt variables.+ it.each([+ { policy: { deviceAccess: { canUseDevice: false, reason: 'external-bot' } }, why: 'policy' },+ { plan: { execution: { kind: 'sandbox', target: 'sandbox' } }, why: 'plan' },+ ])('does not adopt a device the run may not use ($why)', async ({ plan, policy }) => {+ const state = {+ ...mockState,+ messages: [],+ origin: { agentId: 'agent-1', topicId: 'topic-1' },+ ...(plan && { plan }),+ ...(policy && { principal: { policy } }),+ };+ mockCoordinator.loadAgentState.mockResolvedValue(state);+ const dbMessages = buildPersistedToolChain('answer');+ dbMessages[0] = {+ ...dbMessages[0],+ pluginState: {+ metadata: {+ activeDeviceId: 'device-1',+ devicePlatform: 'darwin',+ deviceSystemInfo: { workingDirectory: '/Users/someone/secret' },+ },+ },+ role: 'tool',+ };+ (service as any).messageModel.query.mockResolvedValue(dbMessages);+ vi.spyOn((service as any).messageService, 'prepareUiMessages').mockResolvedValue([]);+ const step = vi.fn().mockImplementation(async (input) => ({+ events: [],+ newState: { ...input, stepCount: 2 },+ nextContext: mockParams.context,+ }));+ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });++ const result = await service.executeStep(mockParams);++ expect(result.success).toBe(true);+ expect(step.mock.calls[0][0].binding?.device).toBeUndefined();+ });+it('shares one DB read while UI preparation is still pending', async () => {const state = {...mockState,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex ed20d854242..ee53944d76e 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -57,6 +57,7 @@ import { type LobeChatDatabase } from '@/database/type';import { appEnv } from '@/envs/app';import { type AgentRuntimeCoordinatorOptions } from '@/server/modules/AgentRuntime';import { AgentRuntimeCoordinator, createStreamEventManager } from '@/server/modules/AgentRuntime';+import { runMayUseDevice } from '@/server/modules/AgentRuntime/executors/resolveRunActiveDeviceId';import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';import { hasNonPersistedMessage } from '@/server/modules/AgentRuntime/messagePersistence';import {@@ -2043,7 +2044,11 @@ export class AgentRuntimeService {// Pre-step computation: extract device context from DB messages// Follows front-end computeStepContext pattern β computed at step boundary, not inside executors- if (!currentState.binding?.device?.id) {+ // Only for a run that may actually touch a device: the executors read the+ // id through the same gate, so binding one here for a forbidden run buys+ // nothing and puts the device's working directory and system info into+ // the prompt variables (`serverCallLlmContextBuilder`).+ if (!currentState.binding?.device?.id && runMayUseDevice(currentState)) {// Interventions and async resumes can change tool rows after the// entry snapshot. Those paths still need a fresh device read.const canReuseEntryMessages =