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(device): stop replaying device tool calls and let offline answers arrive (#20110)

Arvin Xu109cc0a81286
diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.ts
index ebac7b4939a..0475a56026a 100644
--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts
@@ -7,10 +7,12 @@ import { deviceGateway } from '@/server/services/deviceGateway';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { ToolExecutionService } from '../index';
+import { localSystemRuntime } from '../serverRuntimes/localSystem';
vi.mock('@/server/services/deviceGateway', () => ({
deviceGateway: {
executeMcpCall: vi.fn(),
+ executeToolCall: vi.fn(),
isConfigured: false,
queryDeviceList: vi.fn().mockResolvedValue([]),
},
@@ -123,6 +125,77 @@ describe('ToolExecutionService', () => {
},
);
+ it.each([
+ {
+ case: 'the device never answered',
+ failure: {
+ content:
+ 'This tool call timed out before the device answered. The work may still be running on the device, so do NOT blindly repeat anything that writes or has side effects.',
+ error: 'DEVICE_RESPONSE_TIMEOUT: The operation was aborted due to timeout',
+ success: false,
+ },
+ },
+ {
+ // The executor classifies `errorData ?? error`, so a structured payload
+ // bypasses the string path entirely. Its 503 status alone would classify
+ // as `retry` and replay the call.
+ case: 'the device is offline with structured errorData',
+ failure: {
+ content:
+ 'The device is not reachable right now, so this tool call never ran on it (gateway responded HTTP 503). Nothing was executed, so retrying the same call is safe.',
+ error: 'DEVICE_OFFLINE',
+ errorData: {
+ code: 'DEVICE_OFFLINE',
+ message: 'Device is offline',
+ retryable: true,
+ status: 503,
+ },
+ success: false,
+ },
+ },
+ ])('does not replay a device command when $case', async ({ failure }) => {
+ // The device may already be running the first copy: a woken laptop ran a
+ // single `echo >> file` three times after the transport replayed it.
+ vi.mocked(deviceGateway.executeToolCall).mockClear();
+ vi.mocked(deviceGateway.executeToolCall).mockResolvedValue(failure as any);
+ const runtime = localSystemRuntime.factory({
+ activeDeviceId: 'device-1',
+ operationId: 'op-1',
+ toolManifestMap: {},
+ userId: 'user-1',
+ }) as Record<string, (args: unknown) => Promise<any>>;
+ const service = new ToolExecutionService({
+ builtinToolsExecutor: {
+ execute: () => runtime.runCommand({ command: 'echo once >> /tmp/count.txt' }),
+ } as any,
+ mcpService: {} as any,
+ });
+
+ const { attempts, result } = await executeToolWithRetry(
+ () =>
+ service.executeTool(
+ {
+ apiName: 'runCommand',
+ arguments: '{}',
+ id: 'device-call',
+ identifier: 'lobe-local-system',
+ type: 'builtin',
+ },
+ { toolManifestMap: {} },
+ ),
+ { maxRetries: 2 },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe(failure.content);
+ expect(result.error).toMatchObject({ kind: 'stop' });
+ expect(result.errorData).toEqual(
+ 'errorData' in failure ? { ...failure.errorData, kind: 'stop' } : undefined,
+ );
+ expect(attempts).toBe(1);
+ expect(deviceGateway.executeToolCall).toHaveBeenCalledTimes(1);
+ });
+
describe.each(['writeFile', 'runCommand', 'executeCode', 'exportFile'] as const)(
'non-retryable sandbox %s failures',
(api) => {
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index 891870d117c..cc2d743f821 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -25,6 +25,7 @@ import { type MCPService } from '../mcp';
import { type BuiltinToolsExecutor } from './builtin';
import { classifyToolError, getToolAccessDeniedError } from './errorClassification';
import { resolveRunWorkspaceId } from './serverRuntimes/resolveWorkspaceScope';
+import { withoutDeviceReplay } from './serverRuntimes/withoutDeviceReplay';
import {
type ToolExecutionContext,
type ToolExecutionResult,
@@ -491,7 +492,9 @@ export class ToolExecutionService {
);
if (!result.success) {
- return {
+ // The device may already be running the call, so never let the retry
+ // classifier replay it (see withoutDeviceReplay).
+ return withoutDeviceReplay({
content: result.content,
error: result.errorData ?? {
code: 'MCP_DEVICE_EXECUTION_ERROR',
@@ -499,7 +502,7 @@ export class ToolExecutionService {
},
errorData: result.errorData,
success: false,
- };
+ });
}
return {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts b/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
index 69a3b9d0ef5..23440446e53 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
@@ -5,6 +5,7 @@ import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway
import { resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { type ServerRuntimeRegistration } from './types';
+import { withoutDeviceReplay } from './withoutDeviceReplay';
export const auvRuntime: ServerRuntimeRegistration = {
factory: (context) => {
@@ -45,7 +46,7 @@ export const auvRuntime: ServerRuntimeRegistration = {
'The selected device does not support Computer Use. Update the desktop app and reconnect.',
);
}
- return executeAuthorizedDeviceToolCall(
+ const result = await executeAuthorizedDeviceToolCall(
context.serverDB,
{
deviceId: context.activeDeviceId!,
@@ -60,6 +61,8 @@ export const auvRuntime: ServerRuntimeRegistration = {
},
context.executionTimeoutMs,
);
+
+ return withoutDeviceReplay(result);
},
};
},
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
index b870f752e7d..40dade8fd0b 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
@@ -9,6 +9,7 @@ import { FileService } from '@/server/services/file';
import { buildNoActiveDeviceResult, REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';
import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { type ServerRuntimeRegistration } from './types';
+import { withoutDeviceReplay } from './withoutDeviceReplay';
/**
* Browser tool server runtime.
@@ -205,7 +206,9 @@ export const browserRuntime: ServerRuntimeRegistration = {
context.executionTimeoutMs,
);
- return api.name === 'screenshot' ? storeScreenshot(result, context) : result;
+ return withoutDeviceReplay(
+ api.name === 'screenshot' ? await storeScreenshot(result, context) : result,
+ );
};
}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
index 6e29b97ba0c..0ad091607f8 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
@@ -10,6 +10,7 @@ import { buildDeviceLhEnv } from '@/server/services/toolExecution/preprocessLhCo
import { buildNoActiveDeviceResult, REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';
import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { type ServerRuntimeRegistration } from './types';
+import { withoutDeviceReplay } from './withoutDeviceReplay';
/**
* Which arg carries the working directory for the APIs that consume one. The
@@ -152,7 +153,7 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
}
}
- return executeAuthorizedDeviceToolCall(
+ const result = await executeAuthorizedDeviceToolCall(
context.serverDB,
{
deviceId: context.activeDeviceId!,
@@ -170,6 +171,8 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
},
context.executionTimeoutMs,
);
+
+ return withoutDeviceReplay(result);
};
}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/withoutDeviceReplay.ts b/apps/server/src/services/toolExecution/serverRuntimes/withoutDeviceReplay.ts
new file mode 100644
index 00000000000..a28e99fbf65
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/withoutDeviceReplay.ts
@@ -0,0 +1,32 @@
+import { toRecord } from '@lobechat/utils/object';
+
+/**
+ * Marks a failed device tool call as never-replayable.
+ *
+ * A device result carries its failure as a plain string, so the tool error
+ * classifier falls back to keyword matching: "timed out" in a gateway timeout,
+ * or in a command's own stderr, classifies as `retry` and the transport silently
+ * re-sends the call. The device may already be running the first copy (it was
+ * asleep, or slow to answer), so a single `echo >> file` ran three times and the
+ * user waited three full timeouts β€” while the model was told not to repeat
+ * anything blindly. Whether and how to retry is the model's call; the content
+ * already explains which failures are safe to retry.
+ */
+export const withoutDeviceReplay = <
+ T extends { error?: unknown; errorData?: unknown; success?: boolean },
+>(
+ result: T,
+): T => {
+ if (result.success) return result;
+
+ const error =
+ typeof result.error === 'string' ? { message: result.error } : toRecord(result.error);
+ const errorData = toRecord(result.errorData);
+
+ return {
+ ...result,
+ error: { ...error, kind: 'stop' },
+ // `errorData` wins over `error` when the executor classifies the failure.
+ ...(errorData && { errorData: { ...errorData, kind: 'stop' } }),
+ };
+};
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 52b6dc2b3c0..c63d66163d2 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -430,7 +430,7 @@ describe('GatewayHttpClient', () => {
{ apiName: 'readFile', arguments: '{}', identifier: 'test' },
);
- expect(timeoutSpy).toHaveBeenCalledWith(35_000);
+ expect(timeoutSpy).toHaveBeenCalledWith(65_000);
expect(fetch).toHaveBeenCalledWith(
'https://gateway.test.com/api/device/tool-call',
expect.objectContaining({
@@ -444,6 +444,40 @@ describe('GatewayHttpClient', () => {
expect(body.toolCall.type).toBe('tool');
});
+ it("waits out the gateway's reconnect window so an offline device reads as offline", async () => {
+ // The gateway holds an undelivered call for `timeout + 45s` before it
+ // answers 503 DEVICE_OFFLINE. Aborting earlier turned every offline
+ // device into "timed out, the work may still be running".
+ const GATEWAY_RECOVERY_WINDOW_MS = 45_000;
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
+ ok: true,
+ });
+ const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(AbortSignal.abort());
+
+ await client.executeToolCall(
+ { deviceId: 'device-1', timeout: 10_000, userId: 'user-1' },
+ { apiName: 'runCommand', arguments: '{}', identifier: 'test' },
+ );
+
+ expect(timeoutSpy.mock.calls[0][0]).toBeGreaterThan(10_000 + GATEWAY_RECOVERY_WINDOW_MS);
+ });
+
+ it('never pads a call past the agent function window', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
+ ok: true,
+ });
+ const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(AbortSignal.abort());
+
+ await client.executeToolCall(
+ { deviceId: 'device-1', timeout: 760_000, userId: 'user-1' },
+ { apiName: 'runCommand', arguments: '{}', identifier: 'test' },
+ );
+
+ expect(timeoutSpy).toHaveBeenCalledWith(800_000);
+ });
+
it('should pass optional operationId', async () => {
mockFetch({
json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
@@ -473,7 +507,7 @@ describe('GatewayHttpClient', () => {
{ apiName: 'readFile', arguments: '{}', identifier: 'test' },
);
- expect(timeoutSpy).toHaveBeenCalledWith(60_000);
+ expect(timeoutSpy).toHaveBeenCalledWith(90_000);
expect(fetch).toHaveBeenCalledWith(
'https://gateway.test.com/api/device/tool-call',
expect.objectContaining({ signal }),
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index c91e7ccb2c5..7f064142674 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -22,6 +22,20 @@ const DEFAULT_GATEWAY_TOOL_CALL_TIMEOUT_MS = 30_000;
*/
const DEVICE_QUERY_TIMEOUT_MS = 10_000;
const HTTP_CALL_TIMEOUT_PADDING_MS = 30_000;
+/**
+ * The gateway holds an undelivered tool call for `timeout` plus a recovery
+ * window (45s) waiting for the device to reconnect, then answers 503
+ * `DEVICE_OFFLINE` β€” "never ran, safe to retry". A client deadline shorter than
+ * that window aborts first, so an offline device always read as "timed out, the
+ * work may still be running". Keep this above the gateway's window.
+ */
+const TOOL_CALL_HTTP_TIMEOUT_PADDING_MS = 60_000;
+/**
+ * The padding must not stretch a call past the agent function window (800s,
+ * the server's tool-timeout ceiling): an invocation killed mid-wait normalizes
+ * nothing at all. Near the ceiling the offline answer is given up instead.
+ */
+const TOOL_CALL_HTTP_DEADLINE_CAP_MS = 800_000;
export interface DeviceStatusResult {
deviceCount: number;
@@ -185,7 +199,12 @@ export class GatewayHttpClient {
userId: params.userId,
workspaceId: params.workspaceId,
},
- { timeout: timeout + HTTP_CALL_TIMEOUT_PADDING_MS },
+ {
+ timeout: Math.min(
+ timeout + TOOL_CALL_HTTP_TIMEOUT_PADDING_MS,
+ Math.max(timeout, TOOL_CALL_HTTP_DEADLINE_CAP_MS),
+ ),
+ },
);
} catch (error) {
// A client-side deadline or an unreachable gateway host used to escape as