Skip to content

🤯 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.

🐛 fix(agent-runtime): follow the latest activateDevice while the run's device is still open (#20099)

Arvin Xu52e113743a31
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index a903857bb8c..ab35cb4ebe6 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -1095,6 +1095,62 @@ describe('AgentRuntimeService', () => {
expect(step.mock.calls[0][0].binding?.device).toBeUndefined();
});
+ describe('activateDevice after a device is already bound', () => {
+ const activation = (id: string, deviceId: string): UIChatMessage =>
+ ({
+ content: `Device "${deviceId}" activated successfully.`,
+ createdAt: 3,
+ id,
+ pluginState: { metadata: { activeDeviceId: deviceId } },
+ role: 'tool',
+ updatedAt: 3,
+ }) as UIChatMessage;
+
+ const runStep = async (execution: Record<string, unknown>) => {
+ const state = {
+ ...mockState,
+ binding: { device: { id: 'device-a' } },
+ messages: [],
+ origin: { agentId: 'agent-1', topicId: 'topic-1' },
+ plan: { execution },
+ };
+ mockCoordinator.loadAgentState.mockResolvedValue(state);
+ // The model activated device-a first, then device-b.
+ (service as any).messageModel.query.mockResolvedValue([
+ ...buildPersistedToolChain('answer'),
+ activation('activate-a', 'device-a'),
+ activation('activate-b', 'device-b'),
+ ]);
+ 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);
+ return step.mock.calls[0][0].binding?.device?.id;
+ };
+
+ it('follows the latest activation while the plan leaves the device open', async () => {
+ const deviceId = await runStep({
+ kind: 'device-unrouted',
+ reason: 'ambiguous-online-devices',
+ target: 'auto',
+ });
+
+ expect(deviceId).toBe('device-b');
+ });
+
+ it('keeps a locked run on its device even if history names another one', async () => {
+ const deviceId = await runStep({ deviceId: 'device-a', kind: 'device', target: 'device' });
+
+ expect(deviceId).toBe('device-a');
+ });
+ });
+
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.ts
index fef8bd08910..c2363c56f21 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -57,6 +57,7 @@ import { MessageModel } from '@/database/models/message';
import { UserModel } from '@/database/models/user';
import { type LobeChatDatabase } from '@/database/type';
import { appEnv } from '@/envs/app';
+import { isDeviceCapablePlan, isDeviceLockedPlan } from '@/helpers/executionTarget';
import { type AgentRuntimeCoordinatorOptions } from '@/server/modules/AgentRuntime';
import { AgentRuntimeCoordinator, createStreamEventManager } from '@/server/modules/AgentRuntime';
import { runMayUseDevice } from '@/server/modules/AgentRuntime/executors/resolveRunActiveDeviceId';
@@ -2108,7 +2109,21 @@ export class AgentRuntimeService {
// 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)) {
+ //
+ // A run whose plan still leaves the device open (unrouted, not locked)
+ // keeps the remote-device picker for its whole lifetime, so it must keep
+ // following it: re-read on every step and let the latest activation win.
+ // Binding only once made every later `activateDevice` report success
+ // while local tools stayed on the first device.
+ const executionPlan = currentState.plan?.execution;
+ const deviceStillSelectable =
+ !!executionPlan &&
+ isDeviceCapablePlan(executionPlan) &&
+ !isDeviceLockedPlan(executionPlan);
+ if (
+ (!currentState.binding?.device?.id || deviceStillSelectable) &&
+ runMayUseDevice(currentState)
+ ) {
// Interventions and async resumes can change tool rows after the
// entry snapshot. Those paths still need a fresh device read.
const canReuseEntryMessages =
@@ -2121,7 +2136,7 @@ export class AgentRuntimeService {
currentState,
canReuseEntryMessages ? stepEntryMessages : undefined,
);
- if (deviceContext) {
+ if (deviceContext && deviceContext.activeDeviceId !== currentState.binding?.device?.id) {
currentState.binding = {
...currentState.binding,
device: {