🤯 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(hetero): explain a device dispatch timeout (#21341)
Arvin Xua7139a9b5688
diff --git a/apps/server/src/services/aiAgent/helpers/heteroErrors.test.ts b/apps/server/src/services/aiAgent/helpers/heteroErrors.test.tsindex ffef031ef0c..eb1e56ec5ed 100644--- a/apps/server/src/services/aiAgent/helpers/heteroErrors.test.ts+++ b/apps/server/src/services/aiAgent/helpers/heteroErrors.test.ts@@ -64,6 +64,20 @@ describe('JSON device-gateway dispatch errors', () => {},);+ it('explains the gateway TIMEOUT body as a device response timeout', () => {+ // A 504 run dispatch answers this body; it used to become the headline verbatim.+ const raw = '{"error":"TIMEOUT","success":false}';++ expect(humanizeHeteroDispatchError(raw)).toBe(+ humanizeHeteroDispatchError('DEVICE_RESPONSE_TIMEOUT'),+ );+ expect(humanizeHeteroDispatchError(raw)).toContain('offline or asleep');+ expect(resolveHeteroDispatchErrorType(raw)).toBe(ChatErrorType.DeviceResponseTimeout);+ expect(resolveHeteroDispatchErrorType('DEVICE_RESPONSE_TIMEOUT (HTTP 504)')).toBe(+ ChatErrorType.DeviceResponseTimeout,+ );+ });+it.each(['{"error":"UNKNOWN_DEVICE_ERROR","success":false}','{"error":{"code":"DEVICE_NOT_FOUND"}}',diff --git a/apps/server/src/services/aiAgent/helpers/heteroErrors.ts b/apps/server/src/services/aiAgent/helpers/heteroErrors.tsindex bec885b09fc..b375cd58f8a 100644--- a/apps/server/src/services/aiAgent/helpers/heteroErrors.ts+++ b/apps/server/src/services/aiAgent/helpers/heteroErrors.ts@@ -30,11 +30,28 @@ export const HETERO_DISPATCH_ERROR_HEADLINES: Record<string, string> = {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.",+ "The device didn't answer in time. It may be offline or asleep, or it may still be starting this run. Check that the LobeHub desktop app (or the `lh` CLI) is connected and whether this run is already in progress 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.",};+/**+ * The gateway's own codes for a failure the transport already names. A run+ * dispatch answers 504 `{"error":"TIMEOUT"}` when the device sent no+ * `agent_run_ack` in time — the same 504 the transport calls+ * `DEVICE_RESPONSE_TIMEOUT`. Most often the socket was already dead (the+ * gateway only drops it after a missed heartbeat) and nothing ran, but a slow+ * spawn or a lost ack means the run may have started; the copy covers both.+ * Do not reclassify it from a later look at the device: a device that is+ * offline now may still have received the run before dropping (or run it when+ * it wakes), so only a gateway refusal *before* sending proves nothing ran.+ * Keeping the body verbatim (so `detail` stays diagnostic) meant the code+ * missed every lookup and the raw JSON became the headline.+ */+const GATEWAY_CODE_ALIASES: Record<string, string> = {+ TIMEOUT: 'DEVICE_RESPONSE_TIMEOUT',+};+/*** 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@@ -57,7 +74,9 @@ const toDispatchErrorCode = (raw?: string): string | undefined => {}}- return text?.match(/^([A-Z][\dA-Z_]*)/)?.[1];+ const code = text?.match(/^([A-Z][\dA-Z_]*)/)?.[1];++ return (code && GATEWAY_CODE_ALIASES[code]) || code;};/**@@ -104,6 +123,9 @@ const HETERO_DISPATCH_ERROR_TYPES: Record<string, ErrorType> = {DEVICE_CHANNEL_UNAVAILABLE: ChatErrorType.DeviceGatewayNotConfigured,DEVICE_NOT_FOUND: ChatErrorType.DeviceGatewayNotConfigured,DEVICE_OFFLINE: ChatErrorType.DeviceGatewayNotConfigured,+ // Not an unreachable device: the run was delivered and may be running, so+ // "connect a device, then try again" would invite a duplicate run.+ DEVICE_RESPONSE_TIMEOUT: ChatErrorType.DeviceResponseTimeout,GATEWAY_NOT_CONFIGURED: ChatErrorType.DeviceGatewayNotConfigured,};diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.tsindex 9837460083e..4f7420d511b 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts@@ -1,4 +1,5 @@import { HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR } from '@lobechat/heterogeneous-agents';+import { ChatErrorType } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';import {@@ -16,6 +17,7 @@ const mocks = vi.hoisted(() => ({executeToolCall: vi.fn(),finalizeHeteroDispatchError: vi.fn(),publishAgentRuntimeInit: vi.fn(),+ readDeviceSystemInfo: vi.fn(),recordStart: vi.fn(),resolveDeviceDispatchAuthorizationFailure: vi.fn(),resolveSandboxSessionConfig: vi.fn(),@@ -60,7 +62,7 @@ vi.mock('@/server/services/deviceGateway', () => ({deviceGateway: {dispatchAgentRun: mocks.dispatchAgentRun,executeToolCall: mocks.executeToolCall,- readDeviceSystemInfo: vi.fn(),+ readDeviceSystemInfo: mocks.readDeviceSystemInfo,},}));@@ -525,6 +527,36 @@ describe('dispatchHeteroAgent — local CLI agents', () => {);});+ it('settles a dispatch timeout as a device timeout, even when the device is now offline', async () => {+ // Whether the run started is unknowable after a timeout: the device may+ // have received it before dropping. Asking the device now must not turn+ // "may still be starting" into "never started".+ const raw = JSON.stringify({ error: 'TIMEOUT', success: false, timeSinceHeartbeatMs: 70_000 });+ mocks.dispatchAgentRun.mockResolvedValueOnce({ error: raw, success: false });+ mocks.readDeviceSystemInfo.mockResolvedValue({ ok: false, reason: 'DEVICE_OFFLINE' });+ const { deps } = createDeps();++ await dispatchHeteroAgent(+ deps,+ createCtx({+ boundDeviceId: 'dev-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+ }),+ createInput('claude-code'),+ );++ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(+ deps,+ expect.objectContaining({+ detail: raw,+ errorType: ChatErrorType.DeviceResponseTimeout,+ message: humanizeHeteroDispatchError('DEVICE_RESPONSE_TIMEOUT'),+ }),+ );+ expect(mocks.readDeviceSystemInfo).not.toHaveBeenCalled();+ });+it('never routes a device-only provider to the cloud sandbox', async () => {const { deps } = createDeps();diff --git a/apps/server/src/services/bot/replyTemplate.ts b/apps/server/src/services/bot/replyTemplate.tsindex ce4391890b1..05ab4e69429 100644--- a/apps/server/src/services/bot/replyTemplate.ts+++ b/apps/server/src/services/bot/replyTemplate.ts@@ -258,6 +258,7 @@ type SystemStrings = {errorCommandConnectionClosed: string;errorContentModeration: string;errorDeviceUnreachable: string;+ errorDeviceResponseTimeout: string;errorEmptyCompletion: string;errorModelRefusal: string;errorHarnessInternal: string;@@ -368,6 +369,8 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {'**Command session disconnected.**\nThe agent lost its command connection before finishing. Please retry. If this keeps happening, check the sandbox or device connection and review the server logs for the operation.',errorContentModeration:"**Blocked by the content-safety filter.**\nThe model provider's safety filter rejected the request or response. Please rephrase and try again.",+ errorDeviceResponseTimeout:+ "**The device didn't respond in time.**\nIt may be offline or asleep, or it may still be starting this run. Check that the LobeHub desktop app (or the `lh` CLI) is connected and whether this run is already in progress, then try again.",errorDeviceUnreachable:"**Couldn't reach the device this agent runs on.**\nThe run never started. Check that the LobeHub desktop app (or the `lh` CLI) is running and connected, then try again — or bind this agent to another online device in its settings.",errorEmptyCompletion:@@ -494,6 +497,8 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {'**命令会话已断开**\nAgent 在完成前丢失了命令连接。请重试;如果该问题持续出现,请检查 sandbox 或设备连接,并结合 Operation ID 查看服务端日志。',errorContentModeration:'**被内容安全策略拦截**\n模型 Provider 的安全策略拒绝了本次请求或回复。请调整内容后重试。',+ errorDeviceResponseTimeout:+ '**设备未及时响应**\n设备可能已离线或休眠,也可能仍在启动本次运行。请确认 LobeHub 桌面端(或 `lh` CLI)已连接、且没有正在进行的本次运行后,再重试。',errorDeviceUnreachable:'**无法连接到运行该 Agent 的设备**\n本次执行没有启动。请确认 LobeHub 桌面端(或 `lh` CLI)正在运行且已连接后重试,也可以在 Agent 设置中改绑其他在线设备。',errorEmptyCompletion:@@ -595,6 +600,7 @@ const FRIENDLY_ERROR_BY_TYPE: Record<string, keyof SystemStrings> = {// `HETERO_DISPATCH_ERROR_TYPES`. Without it a hetero dispatch failure fell to// the legacy tier and told an IM user nothing but an Operation ID.DeviceGatewayNotConfigured: 'errorDeviceUnreachable',+ DeviceResponseTimeout: 'errorDeviceResponseTimeout',ExceededContextWindow: 'errorExceededContextWindow',// Managed credits: all three codes come out of the same cost-admission gate,// so the fix is topping up / upgrading — not editing the input (without themdiff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex 6b26353a135..f56b9c4bfdb 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -75,6 +75,7 @@"response.524": "We apologize, the server timed out while waiting for a response, possibly due to a slow reply. Please try again later.","response.CreateMessageError": "Sorry, the message could not be sent successfully. Please copy the content and try sending it again. This message will not be retained after refreshing the page.","response.DeviceGatewayNotConfigured": "Couldn't reach a run device for this agent. Connect a device, or configure the device gateway on the server, then try again.",+ "response.DeviceResponseTimeout": "The device didn't respond in time. It may be offline or asleep, or it may still be starting this run. Check that the device is connected and whether this run is already in progress, then try again.","response.ExceededContextWindowCloud": "The conversation is too long to process. Please edit your last message to reduce input or delete some messages and try again.","response.FreePlanLimit": "You are currently a free user and cannot use this feature. Please upgrade to a paid plan to continue using it.","response.GoogleAIBlockReason.BLOCKLIST": "The content includes blocked terms. Please rephrase and try again.",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex a5abf40f9da..9365e6b5b65 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -75,6 +75,7 @@"response.524": "等待上游响应超时,请稍后再试","response.CreateMessageError": "消息未能发送。建议先复制内容再重试;刷新页面后该消息不会保留","response.DeviceGatewayNotConfigured": "无法连接到运行此助理的设备。请先连接设备,或在服务端配置设备网关,然后重试。",+ "response.DeviceResponseTimeout": "设备未及时响应,可能已离线或休眠,也可能仍在启动本次运行。请确认设备已连接、且没有正在进行的本次运行后,再重试。","response.ExceededContextWindowCloud": "当前对话内容过长,无法继续处理。请编辑最后一条消息减少输入内容或者删除一些消息重试。","response.FreePlanLimit": "当前计划不支持该功能。请升级到付费计划后继续","response.GoogleAIBlockReason.BLOCKLIST": "内容包含被屏蔽的词语。请重新措辞后再试。",diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex 2bd7609af23..c88012d4cc4 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -192,6 +192,8 @@ export default {'This generation was paused due to content safety restrictions. Its waiting period has ended. Revise your prompt and try again.','response.DeviceGatewayNotConfigured':"Couldn't reach a run device for this agent. Connect a device, or configure the device gateway on the server, then try again.",+ 'response.DeviceResponseTimeout':+ "The device didn't respond in time. It may be offline or asleep, or it may still be starting this run. Check that the device is connected and whether this run is already in progress, then try again.",'response.RemoteServerOffline':'You appear to be offline. This is a problem with your local network, not the app — please check your internet connection and try again.','response.RemoteServerTimeout':diff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.tsindex 15013e0ca6d..600923f99a8 100644--- a/packages/types/src/fetch.ts+++ b/packages/types/src/fetch.ts@@ -30,6 +30,7 @@ export const ChatErrorType = {SystemTimeNotMatchError: 'SystemTimeNotMatchError',ServerAgentRuntimeError: 'ServerAgentRuntimeError',DeviceGatewayNotConfigured: 'DeviceGatewayNotConfigured', // Heterogeneous agent has no reachable run device / gateway+ DeviceResponseTimeout: 'DeviceResponseTimeout', // Run reached the device, which did not answer in time// ******* Desktop Backend-Proxy Network Errors ******* //// Emitted by the Electron backend proxy when the upstream fetch fails at thediff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxindex 8b501988eff..b24fc73aba0 100644--- a/src/features/Conversation/Error/index.test.tsx+++ b/src/features/Conversation/Error/index.test.tsx@@ -724,6 +724,49 @@ describe('ErrorMessageExtra', () => {expect(screen.getByText(/"detail": "raw detail"/)).toBeInTheDocument();});+ it('shows a JSON gateway detail as an object instead of a twice-escaped string', () => {+ const raw = '{"error":"TIMEOUT","success":false}';+ render(+ <ErrorMessageExtra+ error={{ message: 'response.DeviceResponseTimeout' }}+ data={{+ error: {+ body: { detail: raw },+ message: raw,+ type: ChatErrorType.DeviceResponseTimeout,+ } as any,+ id: 'msg-device-timeout',+ }}+ />,+ );++ expect(screen.getByText('response.DeviceResponseTimeout')).toBeInTheDocument();+ const details = screen.getByText(/"error": "TIMEOUT"/).textContent ?? '';+ expect(details).not.toContain('\\"');+ expect(details).not.toContain('"message"');+ });++ it('keeps a truncated JSON gateway detail as the raw string', () => {+ render(+ <ErrorMessageExtra+ error={{ message: 'response.DeviceResponseTimeout' }}+ data={{+ error: {+ body: { detail: '{"error":"TIMEOUT"' },+ message: 'The device did not answer in time.',+ type: ChatErrorType.DeviceResponseTimeout,+ } as any,+ id: 'msg-device-timeout-truncated',+ }}+ />,+ );++ expect(screen.getByText(/"detail": "\{\\"error\\":\\"TIMEOUT\\""/)).toBeInTheDocument();+ expect(+ screen.getByText(/"message": "The device did not answer in time\."/),+ ).toBeInTheDocument();+ });+it('shows the localized empty-completion message while retaining the raw error in details', () => {render(<ErrorMessageExtradiff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex af461315466..2336cef215b 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -73,12 +73,35 @@ const getRawErrorMessage = (error?: ChatMessageError | null) => {return;};+/**+ * Server dispatch errors keep the upstream response body verbatim in `detail`+ * (e.g. the gateway's `{"error":"TIMEOUT","success":false}`). Stringified into+ * the JSON details block it renders escaped twice, so show the parsed object.+ */+const parseJsonDetail = (detail: unknown) => {+ if (typeof detail !== 'string' || !detail.trim().startsWith('{')) return detail;+ try {+ const parsed: unknown = JSON.parse(detail);+ return isRecord(parsed) ? parsed : detail;+ } catch {+ return detail;+ }+};+const getErrorDetails = (error?: ChatMessageError | null) => {if (!error) return;const rawErrorMessage = getRawErrorMessage(error);if (!rawErrorMessage) return error.body;- if (isRecord(error.body)) return { ...error.body, message: rawErrorMessage };+ if (isRecord(error.body)) {+ if (!('detail' in error.body)) return { ...error.body, message: rawErrorMessage };++ const { detail, ...rest } = error.body;+ // A message that only repeats the raw detail adds nothing to the block.+ return detail === rawErrorMessage+ ? { ...rest, detail: parseJsonDetail(detail) }+ : { ...rest, detail: parseJsonDetail(detail), message: rawErrorMessage };+ }if (error.body !== undefined) return { body: error.body, message: rawErrorMessage };return { message: rawErrorMessage };