π€― 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
π style(device-gateway): explain device channel failures instead of raw 503/504 (#19113)
Arvin Xu69c986d270b3
diff --git a/apps/server/src/services/aiAgent/helpers/heteroErrors.test.ts b/apps/server/src/services/aiAgent/helpers/heteroErrors.test.tsnew file mode 100644index 00000000000..905be5d392e--- /dev/null+++ b/apps/server/src/services/aiAgent/helpers/heteroErrors.test.ts@@ -0,0 +1,54 @@+import { ChatErrorType } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { humanizeHeteroDispatchError, resolveHeteroDispatchErrorType } from './heteroErrors';++describe('humanizeHeteroDispatchError', () => {+ it('replaces a bare gateway code with a sentence the user can act on', () => {+ // `DEVICE_OFFLINE` used to render verbatim in the error card.+ const headline = humanizeHeteroDispatchError('DEVICE_OFFLINE');++ expect(headline).not.toBe('DEVICE_OFFLINE');+ expect(headline).toContain('offline');+ expect(headline).toContain('desktop app');+ });++ it('looks past the status annotation the gateway client appends', () => {+ // The device-gateway client answers `CODE (HTTP 503)` when the gateway sent+ // no body; an exact-match lookup would fall through to the raw string.+ expect(humanizeHeteroDispatchError('DEVICE_CHANNEL_UNAVAILABLE (HTTP 503)')).toContain(+ "isn't reachable right now",+ );+ });++ it('keeps the existing gateway-not-configured copy', () => {+ expect(humanizeHeteroDispatchError('GATEWAY_NOT_CONFIGURED')).toContain(+ "run device gateway isn't configured",+ );+ });++ it('passes unknown text through and falls back when there is none', () => {+ expect(humanizeHeteroDispatchError('spawn failed')).toBe('spawn failed');+ expect(humanizeHeteroDispatchError()).toBe('Device dispatch failed');+ });+});++describe('resolveHeteroDispatchErrorType', () => {+ it('routes every unreachable-device flavour to the localized device error', () => {+ for (const raw of [+ 'DEVICE_OFFLINE',+ 'DEVICE_CHANNEL_UNAVAILABLE (HTTP 503)',+ 'DEVICE_NOT_FOUND (HTTP 404)',+ 'GATEWAY_NOT_CONFIGURED',+ ]) {+ expect(resolveHeteroDispatchErrorType(raw)).toBe(ChatErrorType.DeviceGatewayNotConfigured);+ }+ });++ it('keeps the generic runtime error for anything else', () => {+ expect(resolveHeteroDispatchErrorType('spawn failed')).toBe(+ ChatErrorType.ServerAgentRuntimeError,+ );+ expect(resolveHeteroDispatchErrorType()).toBe(ChatErrorType.ServerAgentRuntimeError);+ });+});diff --git a/apps/server/src/services/aiAgent/helpers/heteroErrors.ts b/apps/server/src/services/aiAgent/helpers/heteroErrors.tsindex 9be17880f63..f58fe51ff01 100644--- a/apps/server/src/services/aiAgent/helpers/heteroErrors.ts+++ b/apps/server/src/services/aiAgent/helpers/heteroErrors.ts@@ -10,12 +10,41 @@ import { ChatErrorType, type ErrorType } from '@lobechat/types';* `detail` for diagnostics. Web clients localize via the mapped error type below.*/const HETERO_DISPATCH_ERROR_HEADLINES: Record<string, string> = {+ DEVICE_CHANNEL_UNAVAILABLE:+ "The device this agent runs on isn't reachable right now β it went offline, went to sleep, or is reconnecting. Check that the LobeHub desktop app (or the `lh` CLI) is running and connected, then try again.",+ DEVICE_GATEWAY_ERROR:+ 'The device connection service hit an error while starting this run. Nothing started on the device. This is usually temporary β try again in a moment.',+ DEVICE_GATEWAY_RATE_LIMITED:+ 'Too many device requests at once, so this run was turned away. Wait a few seconds and try again.',+ DEVICE_GATEWAY_UNAUTHORIZED:+ "The device connection service rejected this run's credentials. This is a server configuration problem β retrying won't help.",+ DEVICE_GATEWAY_UNREACHABLE:+ "Couldn't reach the device connection service, so this run never started. Check the network, then try again.",+ DEVICE_NOT_FOUND:+ 'The device this agent is bound to is no longer registered with the connection service. Reconnect the device, or bind this agent to another online device.',+ DEVICE_OFFLINE:+ "The device this agent runs on is offline, so the run couldn't start. Check that the LobeHub desktop app (or the `lh` CLI) is running and connected, then try again.",+ DEVICE_RESPONSE_TIMEOUT:+ "The device didn't answer in time, so we can't tell whether this run started. Check the device before starting it again.",GATEWAY_NOT_CONFIGURED:"The run device gateway isn't configured on the server, so this agent can't reach a device to run on. Configure the device gateway, or switch this agent to a connected local device.",};-export const humanizeHeteroDispatchError = (raw?: string): string =>- (raw && HETERO_DISPATCH_ERROR_HEADLINES[raw]) || raw || 'Device dispatch failed';+/**+ * The gateway may answer with a bare code (`DEVICE_OFFLINE`) or with a code the+ * device-gateway client annotated with the status it came from+ * (`DEVICE_CHANNEL_UNAVAILABLE (HTTP 503)`). Look the headline up by the code+ * itself so the annotation doesn't cost the user a readable message; `detail`+ * keeps the full raw string for diagnostics either way.+ */+const toDispatchErrorCode = (raw?: string): string | undefined =>+ raw?.trim().match(/^([A-Z][\dA-Z_]*)/)?.[1];++export const humanizeHeteroDispatchError = (raw?: string): string => {+ const code = toDispatchErrorCode(raw);++ return (code && HETERO_DISPATCH_ERROR_HEADLINES[code]) || raw || 'Device dispatch failed';+};/*** Map a raw dispatch code to a dedicated `ChatErrorType` so the web client renders@@ -23,11 +52,21 @@ export const humanizeHeteroDispatchError = (raw?: string): string =>* otherwise mask the specific message). Unknown codes keep the generic type.*/const HETERO_DISPATCH_ERROR_TYPES: Record<string, ErrorType> = {+ // Every "we could not reach a device" flavour shares the localized+ // `DeviceGatewayNotConfigured` copy β the user-facing action ("connect a+ // device") is the same whether the gateway is unconfigured, the device is+ // offline, or its registration is gone.+ DEVICE_CHANNEL_UNAVAILABLE: ChatErrorType.DeviceGatewayNotConfigured,+ DEVICE_NOT_FOUND: ChatErrorType.DeviceGatewayNotConfigured,+ DEVICE_OFFLINE: ChatErrorType.DeviceGatewayNotConfigured,GATEWAY_NOT_CONFIGURED: ChatErrorType.DeviceGatewayNotConfigured,};-export const resolveHeteroDispatchErrorType = (raw?: string): ErrorType =>- (raw && HETERO_DISPATCH_ERROR_TYPES[raw]) || ChatErrorType.ServerAgentRuntimeError;+export const resolveHeteroDispatchErrorType = (raw?: string): ErrorType => {+ const code = toDispatchErrorCode(raw);++ return (code && HETERO_DISPATCH_ERROR_TYPES[code]) || ChatErrorType.ServerAgentRuntimeError;+};export const supportsCloudHeterogeneousSandbox = (type: HeterogeneousAgentType): boolean =>type === 'claude-code' || type === 'codex';diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.tsindex aff2824a934..8c13e64a36c 100644--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts@@ -24,7 +24,11 @@ vi.mock('@/envs/gateway', () => ({gatewayEnv: mockEnv,}));-vi.mock('@lobechat/device-gateway-client', () => ({+// Partial mock: only the HTTP client is swapped. The transport-failure+// describers are pure functions the service calls to phrase its errors, and+// stubbing them would test nothing.+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@lobechat/device-gateway-client')>()),GatewayHttpClient: MockGatewayHttpClient,}));@@ -345,11 +349,11 @@ describe('DeviceGateway', () => {const proxy = new DeviceGateway();const result = await proxy.executeToolCall(params, toolCall);- expect(result).toEqual({- content: 'Device tool call error: connection refused',- error: 'connection refused',- success: false,- });+ // `connection refused` is a network failure, so the model is told the call+ // never ran rather than being handed the bare driver message.+ expect(result.success).toBe(false);+ expect(result.content).toContain('Could not reach the device gateway');+ expect(result.error).toBe('DEVICE_GATEWAY_UNREACHABLE: connection refused');});it('should handle non-Error exceptions', async () => {@@ -360,11 +364,11 @@ describe('DeviceGateway', () => {const proxy = new DeviceGateway();const result = await proxy.executeToolCall(params, toolCall);- expect(result).toEqual({- content: 'Device tool call error: string error',- error: 'string error',- success: false,- });+ // Unrecognised cause: describe the hop without claiming to know whether+ // the device ran the call.+ expect(result.success).toBe(false);+ expect(result.content).toContain('unclear whether the device ran it');+ expect(result.error).toBe('DEVICE_GATEWAY_ERROR: string error');});});@@ -427,11 +431,10 @@ describe('DeviceGateway', () => {const proxy = new DeviceGateway();const result = await proxy.executeMcpCall(mcpCall);- expect(result).toEqual({- content: 'Device MCP call error: connection refused',- error: 'connection refused',- success: false,- });+ // Tunneled MCP calls ride the same relay, so they get the same phrasing.+ expect(result.success).toBe(false);+ expect(result.content).toContain('Could not reach the device gateway');+ expect(result.error).toBe('DEVICE_GATEWAY_UNREACHABLE: connection refused');});});diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex fcda58dbf14..8b35102e1b6 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -2,6 +2,7 @@ import path from 'node:path';import { type DeviceAttachment } from '@lobechat/builtin-tool-remote-device';import {+ describeGatewayRequestFailure,type DeviceMessageApiResult,type DeviceStatusResult,type DeviceSystemInfo,@@ -1400,7 +1401,11 @@ export class DeviceGateway {} catch (error) {const message = error instanceof Error ? error.message : String(error);log('executeToolCall: error β %s', message);- return { content: `Device tool call error: ${message}`, error: message, success: false };+ // Backstop for anything the http client did not already describe. A raw+ // `TimeoutError` / driver message here reads to the model as if the tool+ // itself blew up; name the failing hop and its recovery instead.+ const failure = describeGatewayRequestFailure(error, 'tool call');+ return { content: failure.content, error: failure.error, success: false };}}@@ -1444,7 +1449,8 @@ export class DeviceGateway {} catch (error) {const message = error instanceof Error ? error.message : String(error);log('executeMcpCall: error β %s', message);- return { content: `Device MCP call error: ${message}`, error: message, success: false };+ const failure = describeGatewayRequestFailure(error, 'tool call');+ return { content: failure.content, error: failure.error, success: false };}}diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.tsindex 084fe0f3776..15d25a4d61f 100644--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts@@ -90,10 +90,6 @@ You have access to a set of tools to interact with the user's local file system:Returns a current output snapshot.- For killing running terminal sessions: Use 'killCommand' with 'shell_id'.Treat terminal sessions as ongoing resources: when elapsed wait time and observed progress no longer match the command's expected lifecycle, reassess whether the session should continue running.-- For remote device execution feedback: 'Device tool call failed (HTTP ...)' describes the remote-device/gateway layer, not necessarily the local operation.- - HTTP 403 likely means an edge security policy blocked the request; replan with an equivalent approach or another tool such as runCommand.- - HTTP 503 is usually transient during reconnects or stale session replacement. For the same intended operation, retry up to 8 times only when the operation is safe to repeat; if it still fails, stop retrying that operation and replan.- - HTTP 504 means the device did not respond within the wait window; the command may already have started, so retry only when the operation is safe to repeat.- For searching content in files: Use 'grepContent'. Provide:- 'pattern': The regex pattern to search for.- 'scope' (Optional): Directory to search in. Defaults to the working directory if omitted.diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.tsindex ccd768c5cf5..669d4a2a2b5 100644--- a/packages/builtin-tool-local-system/src/systemRole.ts+++ b/packages/builtin-tool-local-system/src/systemRole.ts@@ -88,10 +88,6 @@ You have access to a set of tools to interact with the user's local file system:Returns a current output snapshot.- For killing running terminal sessions: Use 'killCommand' with 'shell_id'.Treat terminal sessions as ongoing resources: when elapsed wait time and observed progress no longer match the command's expected lifecycle, reassess whether the session should continue running.-- For remote device execution feedback: 'Device tool call failed (HTTP ...)' describes the remote-device/gateway layer, not necessarily the local operation.- - HTTP 403 likely means an edge security policy blocked the request; replan with an equivalent approach or another tool such as runCommand.- - HTTP 503 is usually transient during reconnects or stale session replacement. For the same intended operation, retry up to 8 times only when the operation is safe to repeat; if it still fails, stop retrying that operation and replan.- - HTTP 504 means the device did not respond within the wait window; the command may already have started, so retry only when the operation is safe to repeat.- For searching content in files: Use 'grepContent'. Provide:- 'pattern': The regex pattern to search for.- 'scope' (Optional): Directory to search in. Defaults to the working directory if omitted.diff --git a/packages/device-gateway-client/src/deviceTransportError.test.ts b/packages/device-gateway-client/src/deviceTransportError.test.tsnew file mode 100644index 00000000000..d3b53d5a418--- /dev/null+++ b/packages/device-gateway-client/src/deviceTransportError.test.ts@@ -0,0 +1,164 @@+import { describe, expect, it } from 'vitest';++import {+ DeviceTransportErrorCode,+ describeGatewayRequestFailure,+ describeGatewayResponseFailure,+} from './deviceTransportError';++describe('describeGatewayResponseFailure', () => {+ it('separates "never delivered" (503) from "may still be running" (504)', () => {+ // This is the distinction the old `HTTP ${status}` string erased, and the+ // one that decides whether repeating a mutating call is safe.+ const undelivered = describeGatewayResponseFailure(503, '', 'tool call');+ const unanswered = describeGatewayResponseFailure(504, '', 'tool call');++ expect(undelivered.code).toBe(DeviceTransportErrorCode.DeviceChannelUnavailable);+ expect(undelivered.content).toContain('never ran on it');+ expect(undelivered.content).toContain('retrying the same call is safe');++ expect(unanswered.code).toBe(DeviceTransportErrorCode.DeviceResponseTimeout);+ expect(unanswered.content).toContain('may still be running');+ expect(unanswered.content).toContain('do NOT blindly repeat');+ });++ it('treats 502 like 503 β the gateway never handed the call over', () => {+ expect(describeGatewayResponseFailure(502, '', 'tool call').code).toBe(+ DeviceTransportErrorCode.DeviceChannelUnavailable,+ );+ });++ it('keeps the gateway body verbatim as the error so code matching still works', () => {+ // `directMentionExecutor` and the hetero dispatch headlines both match on+ // the raw gateway code.+ const failure = describeGatewayResponseFailure(503, 'DEVICE_OFFLINE', 'agent run');++ expect(failure.error).toBe('DEVICE_OFFLINE');+ expect(failure.content).toContain('Gateway detail: DEVICE_OFFLINE');+ });++ it('falls back to the mapped code when the gateway sent no body', () => {+ expect(describeGatewayResponseFailure(503, '', 'tool call').error).toBe(+ 'DEVICE_CHANNEL_UNAVAILABLE (HTTP 503)',+ );+ expect(describeGatewayResponseFailure(500, undefined, 'RPC call').error).toBe(+ 'DEVICE_GATEWAY_ERROR (HTTP 500)',+ );+ });++ it('marks auth failures as not worth retrying', () => {+ for (const status of [401, 403]) {+ const failure = describeGatewayResponseFailure(status, '', 'tool call');+ expect(failure.code).toBe(DeviceTransportErrorCode.Unauthorized);+ expect(failure.content).toContain('will not fix it');+ }+ });++ it('maps the remaining statuses to routing-aware codes', () => {+ expect(describeGatewayResponseFailure(404, '', 'tool call').code).toBe(+ DeviceTransportErrorCode.DeviceNotFound,+ );+ expect(describeGatewayResponseFailure(429, '', 'tool call').code).toBe(+ DeviceTransportErrorCode.RateLimited,+ );+ expect(describeGatewayResponseFailure(400, '', 'tool call').code).toBe(+ DeviceTransportErrorCode.GatewayRejected,+ );+ });++ it('names the operation that failed', () => {+ expect(describeGatewayResponseFailure(503, '', 'message API call').content).toContain(+ 'message API call',+ );+ expect(describeGatewayResponseFailure(503, '', 'agent run').content).toContain('agent run');+ });++ it('carries the retry policy that used to live in the system prompt', () => {+ // The prompt block naming these budgets was deleted: guidance belongs on+ // the failure it applies to, not in a static preamble paid for on every+ // call that also silently rots when the wire copy changes.+ const undelivered = describeGatewayResponseFailure(503, '', 'tool call');+ expect(undelivered.content).toContain('retry up to 8 times');+ expect(undelivered.content).toContain('stop retrying it and replan');++ const unanswered = describeGatewayResponseFailure(504, '', 'tool call');+ expect(unanswered.content).toContain('safe to repeat');++ const blocked = describeGatewayResponseFailure(403, '', 'tool call');+ expect(blocked.content).toContain('edge security policy');+ expect(blocked.content).toContain('replan with an equivalent approach');+ });++ it('always keeps the status in the sentence for log correlation', () => {+ // Not showing the code *bare* is the point; dropping it entirely would cost+ // operators the only thing that correlates with gateway logs.+ for (const status of [400, 401, 404, 429, 500, 503, 504]) {+ expect(describeGatewayResponseFailure(status, '', 'tool call').content).toContain(+ `HTTP ${status}`,+ );+ }+ });+});++describe('describeGatewayRequestFailure', () => {+ it('treats a client-side abort like a 504 β the call may have landed', () => {+ const failure = describeGatewayRequestFailure(+ Object.assign(new Error('The operation was aborted due to timeout'), {+ name: 'TimeoutError',+ }),+ 'tool call',+ );++ expect(failure.code).toBe(DeviceTransportErrorCode.DeviceResponseTimeout);+ expect(failure.content).toContain('do NOT blindly repeat');+ expect(failure.error).toContain('The operation was aborted due to timeout');+ });++ it('recognises the DOM AbortError name as well', () => {+ expect(+ describeGatewayRequestFailure(Object.assign(new Error('aborted'), { name: 'AbortError' }), 'tool call')+ .code,+ ).toBe(DeviceTransportErrorCode.DeviceResponseTimeout);+ });++ it('reports a dead gateway host as an undelivered call', () => {+ const failure = describeGatewayRequestFailure(new TypeError('fetch failed'), 'tool call');++ expect(failure.code).toBe(DeviceTransportErrorCode.GatewayUnreachable);+ expect(failure.content).toContain('never ran on the device');+ expect(failure.error).toContain('fetch failed');+ });++ it('recognises a plain-English connection failure', () => {+ // Node's own driver messages ("connection refused") carry no `E*` code, so+ // matching on codes alone dropped the most common device-gateway failure+ // into the unknown bucket.+ expect(describeGatewayRequestFailure(new Error('connection refused'), 'tool call').code).toBe(+ DeviceTransportErrorCode.GatewayUnreachable,+ );+ });++ it('recognises a network failure carried on `cause.code`', () => {+ const failure = describeGatewayRequestFailure(+ Object.assign(new Error('request to gateway failed'), { cause: { code: 'ECONNREFUSED' } }),+ 'tool call',+ );++ expect(failure.code).toBe(DeviceTransportErrorCode.GatewayUnreachable);+ });++ it('does not invent a cause for an unrecognised failure', () => {+ // The old copy claimed the gateway was unreachable for every rejection,+ // including ones (a malformed response body, say) that prove nothing about+ // whether the device ran the call.+ const failure = describeGatewayRequestFailure(new Error('Unexpected token < in JSON'), 'tool call');++ expect(failure.code).toBe(DeviceTransportErrorCode.GatewayError);+ expect(failure.content).toContain('unclear whether the device ran it');+ expect(failure.content).toContain('Unexpected token < in JSON');+ });++ it('handles a non-Error rejection', () => {+ expect(describeGatewayRequestFailure('boom', 'tool call').error).toContain('boom');+ });+});diff --git a/packages/device-gateway-client/src/deviceTransportError.ts b/packages/device-gateway-client/src/deviceTransportError.tsnew file mode 100644index 00000000000..77ccd886203--- /dev/null+++ b/packages/device-gateway-client/src/deviceTransportError.ts@@ -0,0 +1,207 @@+/**+ * Human- and model-readable descriptions for device-channel transport+ * failures.+ *+ * Every call to a user's device travels cloud β gateway β device WebSocket, and+ * that hop fails on its own schedule: the desktop app sleeps, the socket+ * reconnects, a long command outruns the deadline. The client used to hand the+ * raw status straight through β `Device tool call failed (HTTP 503)` β which is+ * the least useful sentence available to either reader:+ *+ * - The **model** cannot tell a transport failure from a tool that genuinely+ * refused, so it either gives up on a device that is one retry away from+ * answering, or blindly re-runs a mutating command that may still be running.+ * - The **user** sees a bare status code in the tool card with no hint that the+ * thing to check is their own desktop app.+ *+ * So each status is mapped to a stable code plus a sentence that says what+ * happened, whether the call reached the device, and what to do next. The+ * gateway's own body text is preserved verbatim in `error` β downstream still+ * matches on codes like `DEVICE_OFFLINE`.+ */++export const DeviceTransportErrorCode = {+ /** Gateway reachable, device not: offline, asleep, or mid-reconnect. */+ DeviceChannelUnavailable: 'DEVICE_CHANNEL_UNAVAILABLE',+ /** The gateway has no record of the addressed device. */+ DeviceNotFound: 'DEVICE_NOT_FOUND',+ /** Delivered to the device, but no answer before the deadline. */+ DeviceResponseTimeout: 'DEVICE_RESPONSE_TIMEOUT',+ /** The gateway itself failed (5xx that is not a routing failure). */+ GatewayError: 'DEVICE_GATEWAY_ERROR',+ /** The request was malformed or rejected by the gateway (4xx). */+ GatewayRejected: 'DEVICE_GATEWAY_REJECTED',+ /** The cloud could not open a connection to the gateway at all. */+ GatewayUnreachable: 'DEVICE_GATEWAY_UNREACHABLE',+ /** Gateway throttled this caller. */+ RateLimited: 'DEVICE_GATEWAY_RATE_LIMITED',+ /** The service token was rejected. */+ Unauthorized: 'DEVICE_GATEWAY_UNAUTHORIZED',+} as const;++export type DeviceTransportErrorCode =+ (typeof DeviceTransportErrorCode)[keyof typeof DeviceTransportErrorCode];++export interface DeviceTransportFailure {+ code: DeviceTransportErrorCode;+ /** LLM- and user-facing explanation. Goes in the result `content`. */+ content: string;+ /** Machine-facing detail: the gateway's own body when it sent one. */+ error: string;+}++/** What the failed hop was carrying, used to open the sentence. */+export type DeviceTransportOperation = 'tool call' | 'message API call' | 'RPC call' | 'agent run';++const RECONNECT_HINT = `Tell the user to check that the LobeHub desktop app (or the \`lh\` CLI) is running and shows as connected.`;++const describeStatus = (+ status: number,+ operation: DeviceTransportOperation,+): { code: DeviceTransportErrorCode; content: string } => {+ switch (true) {+ // The gateway is up but could not hand the call to the device. The device+ // never ran it, so a retry is safe even for a mutating call.+ case status === 502 || status === 503: {+ return {+ code: DeviceTransportErrorCode.DeviceChannelUnavailable,+ content: `The device is not reachable right now, so this ${operation} never ran on it (gateway responded HTTP ${status}). The device connection dropped, went to sleep, or is mid-reconnect β this is a connection problem, not a failure of the requested operation. Nothing was executed, so retrying the same call is safe: wait a few seconds, then retry up to 8 times for this operation. If it still fails, stop retrying it and replan. ${RECONNECT_HINT}`,+ };+ }++ // Delivered, but unanswered before the deadline. Critically different from+ // 503: the device may still be executing, so a blind retry can double-apply.+ case status === 504: {+ return {+ code: DeviceTransportErrorCode.DeviceResponseTimeout,+ content: `The device received this ${operation} but did not answer before the deadline (gateway responded HTTP ${status}). The work may still be running on the device, so do NOT blindly repeat anything that writes or has side effects β first check the current state (re-read the file, list the directory, or check the process) and retry only if the change clearly did not happen and the operation is safe to repeat. Long-running commands should be started in the background and polled instead.`,+ };+ }++ case status === 404: {+ return {+ code: DeviceTransportErrorCode.DeviceNotFound,+ content: `The gateway has no connected device matching this ${operation}'s target (gateway responded HTTP ${status}). The device was never registered, or it disconnected and its session was dropped. Re-resolve the target device (list the online devices and activate one) before retrying. If none is online, stop retrying. ${RECONNECT_HINT}`,+ };+ }++ case status === 401 || status === 403: {+ return {+ code: DeviceTransportErrorCode.Unauthorized,+ content: `The device gateway rejected this ${operation} as unauthorized (HTTP ${status}) β usually an edge security policy blocking the request, or a server configuration problem. Retrying the identical request will not fix it: replan with an equivalent approach, and report it to the user if there is none.`,+ };+ }++ case status === 429: {+ return {+ code: DeviceTransportErrorCode.RateLimited,+ content: `The device gateway is rate limiting this ${operation} (HTTP ${status}). Nothing ran on the device. Back off for a few seconds before retrying, and batch the remaining work into fewer calls.`,+ };+ }++ case status >= 500: {+ return {+ code: DeviceTransportErrorCode.GatewayError,+ content: `The device gateway failed while relaying this ${operation} (HTTP ${status}). This is an infrastructure error on the connection path, not a failure of the requested operation, and it is usually transient β retry once. If it persists, report it to the user rather than retrying in a loop.`,+ };+ }++ default: {+ return {+ code: DeviceTransportErrorCode.GatewayRejected,+ content: `The device gateway rejected this ${operation} (HTTP ${status}). The request never reached the device. Re-check the arguments before retrying; an identical retry will fail the same way.`,+ };+ }+ }+};++/**+ * Describe a non-ok gateway HTTP response.+ *+ * `body` is the gateway's response text; it is kept verbatim as `error` so that+ * existing matches on gateway codes (e.g. `DEVICE_OFFLINE`) keep working, and+ * appended to the explanation when it carries anything beyond the status.+ */+export const describeGatewayResponseFailure = (+ status: number,+ body: string | undefined,+ operation: DeviceTransportOperation,+): DeviceTransportFailure => {+ const { code, content } = describeStatus(status, operation);+ const detail = body?.trim();++ return {+ code,+ content: detail ? `${content}\n\nGateway detail: ${detail}` : content,+ error: detail || `${code} (HTTP ${status})`,+ };+};++const isTimeoutError = (error: unknown): boolean => {+ if (!error || typeof error !== 'object') return false;+ const name = (error as { name?: string }).name;+ return name === 'TimeoutError' || name === 'AbortError';+};++const NETWORK_ERROR_MARKERS = [+ 'fetch failed',+ 'socket hang up',+ 'connection refused',+ 'connection reset',+ 'econnrefused',+ 'econnreset',+ 'enotfound',+ 'eai_again',+ 'etimedout',+ 'network',+];++const isNetworkError = (error: unknown, message: string): boolean => {+ const code = (error as { cause?: { code?: unknown }; code?: unknown } | null)?.code;+ const causeCode = (error as { cause?: { code?: unknown } } | null)?.cause?.code;+ const haystack = [message, code, causeCode]+ .filter((value) => typeof value === 'string')+ .join(' ')+ .toLowerCase();++ return NETWORK_ERROR_MARKERS.some((marker) => haystack.includes(marker));+};++/**+ * Describe a failure that happened before any HTTP status existed β the request+ * timed out client-side, or the gateway host could not be reached at all.+ *+ * A client-side timeout is the same situation as a 504 (the call may have been+ * delivered and may still be running), so it carries the same warning.+ */+export const describeGatewayRequestFailure = (+ error: unknown,+ operation: DeviceTransportOperation,+): DeviceTransportFailure => {+ const message = error instanceof Error ? error.message : String(error);++ if (isTimeoutError(error)) {+ return {+ code: DeviceTransportErrorCode.DeviceResponseTimeout,+ content: `This ${operation} 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 β check the current state first and only retry if the change clearly did not happen.`,+ error: `${DeviceTransportErrorCode.DeviceResponseTimeout}: ${message}`,+ };+ }++ if (isNetworkError(error, message)) {+ return {+ code: DeviceTransportErrorCode.GatewayUnreachable,+ content: `Could not reach the device gateway to relay this ${operation}, so it never ran on the device. This is a network failure between the server and the gateway. Retry once; if it persists, report it to the user rather than retrying in a loop.`,+ error: `${DeviceTransportErrorCode.GatewayUnreachable}: ${message}`,+ };+ }++ // Cause unknown: say so rather than inventing one. The one thing we do know+ // is that the failure is on the device connection path, which decides how the+ // model should treat a retry.+ return {+ code: DeviceTransportErrorCode.GatewayError,+ content: `The device connection failed while relaying this ${operation}, so it is unclear whether the device ran it. Check the current state before repeating anything that writes or has side effects. Underlying error: ${message}`,+ error: `${DeviceTransportErrorCode.GatewayError}: ${message}`,+ };+};diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.tsindex dbdc4e591ef..5553c334833 100644--- a/packages/device-gateway-client/src/http.test.ts+++ b/packages/device-gateway-client/src/http.test.ts@@ -256,7 +256,77 @@ describe('GatewayHttpClient', () => {);expect(result.success).toBe(false);- expect(result.error).toBe('HTTP 500');+ // With no gateway body to quote, the code carries the diagnosis instead+ // of a bare status.+ expect(result.error).toBe('DEVICE_GATEWAY_ERROR (HTTP 500)');+ });++ it('explains a 503 as an undelivered call that is safe to retry', async () => {+ // A bare `Device tool call failed (HTTP 503)` told the model nothing about+ // whether the tool ran, so it either abandoned a device that was one retry+ // from answering or re-ran a mutating command blindly.+ mockFetch({ ok: false, status: 503, text: vi.fn().mockResolvedValue('DEVICE_OFFLINE') });++ const result = await client.executeToolCall(+ { userId: 'user-1' },+ { apiName: 'runCommand', arguments: '{}', identifier: 'test' },+ );++ expect(result.success).toBe(false);+ expect(result.content).toContain('never ran on it');+ expect(result.content).toContain('retrying the same call is safe');+ expect(result.content).toContain('HTTP 503');+ // The gateway's own code stays verbatim for downstream matching.+ expect(result.error).toBe('DEVICE_OFFLINE');+ expect(result.content).toContain('DEVICE_OFFLINE');+ });++ it('warns that a 504 may still be running on the device', async () => {+ // The opposite of 503: the call WAS delivered, so repeating a write can+ // double-apply it.+ mockFetch({ ok: false, status: 504, text: vi.fn().mockResolvedValue('') });++ const result = await client.executeToolCall(+ { userId: 'user-1' },+ { apiName: 'writeFile', arguments: '{}', identifier: 'test' },+ );++ expect(result.success).toBe(false);+ expect(result.content).toContain('did not answer before the deadline');+ expect(result.content).toContain('do NOT blindly repeat');+ expect(result.error).toBe('DEVICE_RESPONSE_TIMEOUT (HTTP 504)');+ });++ it('describes a client-side timeout instead of leaking the abort error', async () => {+ // `AbortSignal.timeout` rejects the fetch, which used to escape as a bare+ // `The operation was aborted due to timeout` β indistinguishable from the+ // tool itself failing.+ const timeout = Object.assign(new Error('The operation was aborted due to timeout'), {+ name: 'TimeoutError',+ });+ vi.mocked(fetch).mockRejectedValue(timeout);++ const result = await client.executeToolCall(+ { userId: 'user-1' },+ { apiName: 'runCommand', arguments: '{}', identifier: 'test' },+ );++ expect(result.success).toBe(false);+ expect(result.content).toContain('timed out before the device answered');+ expect(result.error).toContain('DEVICE_RESPONSE_TIMEOUT');+ });++ it('describes an unreachable gateway host', async () => {+ vi.mocked(fetch).mockRejectedValue(new TypeError('fetch failed'));++ const result = await client.executeToolCall(+ { userId: 'user-1' },+ { apiName: 'readFile', arguments: '{}', identifier: 'test' },+ );++ expect(result.success).toBe(false);+ expect(result.content).toContain('Could not reach the device gateway');+ expect(result.error).toContain('DEVICE_GATEWAY_UNREACHABLE');});it('should pass optional deviceId and timeout', async () => {@@ -547,11 +617,11 @@ describe('GatewayHttpClient', () => {{ apiName: 'ping', payload: {}, platform: 'imessage' },);- expect(result).toEqual({- content: 'Device message API call failed (HTTP 503)',- error: 'Desktop offline',- success: false,- });+ expect(result.success).toBe(false);+ expect(result.error).toBe('Desktop offline');+ expect(result.content).toContain('The device is not reachable right now');+ expect(result.content).toContain('message API call');+ expect(result.content).toContain('HTTP 503');});it('should pass optional deviceId and timeout', async () => {diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex de1d52dbdef..f1127215cc7 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -1,3 +1,7 @@+import {+ describeGatewayRequestFailure,+ describeGatewayResponseFailure,+} from './deviceTransportError';import type {DeviceSystemInfo,GatewayDevice,@@ -38,6 +42,16 @@ export interface DeviceRpcResult<T = unknown> {success: boolean;}+/** Shape a described transport failure into the LLM-facing tool result. */+const toFailedToolCallResult = (failure: {+ content: string;+ error: string;+}): DeviceToolCallResult => ({+ content: failure.content,+ error: failure.error,+ success: false,+});+export interface GatewayHttpClientOptions {gatewayUrl: string;serviceToken: string;@@ -143,26 +157,30 @@ export class GatewayHttpClient {typeof params.timeout === 'number' && Number.isFinite(params.timeout)? Math.max(Math.trunc(params.timeout), 0): DEFAULT_GATEWAY_TOOL_CALL_TIMEOUT_MS;- const res = await this.post(- '/api/device/tool-call',- {- deviceId: params.deviceId,- operationId: params.operationId,- timeout: params.timeout,- toolCall,- userId: params.userId,- workspaceId: params.workspaceId,- },- { timeout: timeout + HTTP_CALL_TIMEOUT_PADDING_MS },- );+ let res: Response;+ try {+ res = await this.post(+ '/api/device/tool-call',+ {+ deviceId: params.deviceId,+ operationId: params.operationId,+ timeout: params.timeout,+ toolCall,+ userId: params.userId,+ workspaceId: params.workspaceId,+ },+ { timeout: timeout + HTTP_CALL_TIMEOUT_PADDING_MS },+ );+ } catch (error) {+ // A client-side deadline or an unreachable gateway host used to escape as+ // a raw `TimeoutError` / `fetch failed`, which reads to the model as if+ // the tool itself blew up. Describe the hop that actually failed instead.+ return toFailedToolCallResult(describeGatewayRequestFailure(error, 'tool call'));+ }if (!res.ok) {const text = await res.text().catch(() => '');- return {- content: `Device tool call failed (HTTP ${res.status})`,- error: text || `HTTP ${res.status}`,- success: false,- };+ return toFailedToolCallResult(describeGatewayResponseFailure(res.status, text, 'tool call'));}const data = await res.json();@@ -201,11 +219,8 @@ export class GatewayHttpClient {if (!res.ok) {const text = await res.text().catch(() => '');- return {- content: `Device message API call failed (HTTP ${res.status})`,- error: text || `HTTP ${res.status}`,- success: false,- };+ const failure = describeGatewayResponseFailure(res.status, text, 'message API call');+ return { content: failure.content, error: failure.error, success: false };}const data = await res.json();@@ -247,7 +262,10 @@ export class GatewayHttpClient {const res = await this.post('/api/device/agent/run', params);if (!res.ok) {const text = await res.text().catch(() => '');- return { error: text || `HTTP ${res.status}`, success: false };+ return {+ error: describeGatewayResponseFailure(res.status, text, 'agent run').error,+ success: false,+ };}const data = await res.json().catch(() => null);if (data && (data.success === false || data.status === 'rejected')) {@@ -290,7 +308,10 @@ export class GatewayHttpClient {if (!res.ok) {const text = await res.text().catch(() => '');- return { error: text || `HTTP ${res.status}`, success: false };+ return {+ error: describeGatewayResponseFailure(res.status, text, 'RPC call').error,+ success: false,+ };}const data = await res.json();diff --git a/packages/device-gateway-client/src/index.ts b/packages/device-gateway-client/src/index.tsindex 73b373a0536..8745f3de054 100644--- a/packages/device-gateway-client/src/index.ts+++ b/packages/device-gateway-client/src/index.ts@@ -1,5 +1,11 @@export type { GatewayClientLogger, GatewayClientOptions } from './client';export { GatewayClient } from './client';+export type { DeviceTransportFailure, DeviceTransportOperation } from './deviceTransportError';+export {+ describeGatewayRequestFailure,+ describeGatewayResponseFailure,+ DeviceTransportErrorCode,+} from './deviceTransportError';export type {DeviceMessageApiResult,DeviceRpcResult,