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(bot): report a hetero dispatch failure once, and name the unreachable device (#19724)

Arvin Xuc7a86e0ec17a
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
index cf4e7202b41..823922e9a18 100644
--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
@@ -278,6 +278,22 @@ export class HookDispatcher {
return this.hooks.get(operationId)?.some((hook) => hook.id === hookId) ?? false;
}
+ /**
+ * Whether dispatching `type` right now would actually reach a consumer, under
+ * the rules {@link dispatch} applies for the current runtime mode: local mode
+ * needs an in-memory handler, queue mode needs a webhook to deliver.
+ *
+ * Callers that ALSO surface the same failure themselves (the IM bot bridge
+ * reports a startup failure inline) ask this before deciding whether their own
+ * report would be a duplicate — a failure the hooks will announce must not be
+ * announced twice, and one they cannot announce must not vanish.
+ */
+ canDeliver(operationId: string, type: AgentHookType): boolean {
+ const hooks = this.hooks.get(operationId)?.filter((hook) => hook.type === type) ?? [];
+
+ return isQueueAgentRuntimeEnabled() ? hooks.some((hook) => hook.webhook) : hooks.length > 0;
+ }
+
/**
* Register hooks for an operation
*
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
index d074e300988..6febd6ecf3d 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
@@ -378,6 +378,36 @@ describe('HookDispatcher', () => {
});
});
+ describe('canDeliver', () => {
+ it('answers per mode: a handler-only hook reaches nobody in queue mode', () => {
+ dispatcher.register(operationId, [
+ { handler: vi.fn(), id: 'local-only', type: 'onComplete' },
+ ]);
+
+ expect(dispatcher.canDeliver(operationId, 'onComplete')).toBe(true);
+
+ vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);
+ expect(dispatcher.canDeliver(operationId, 'onComplete')).toBe(false);
+ });
+
+ it('counts a webhook hook in both modes', () => {
+ dispatcher.register(operationId, [
+ { handler: vi.fn(), id: 'with-webhook', type: 'onComplete', webhook: { url: '/api/hook' } },
+ ]);
+
+ expect(dispatcher.canDeliver(operationId, 'onComplete')).toBe(true);
+ vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);
+ expect(dispatcher.canDeliver(operationId, 'onComplete')).toBe(true);
+ });
+
+ it('is false for another type, and for an operation with no hooks at all', () => {
+ dispatcher.register(operationId, [{ handler: vi.fn(), id: 'step', type: 'afterStep' }]);
+
+ expect(dispatcher.canDeliver(operationId, 'onComplete')).toBe(false);
+ expect(dispatcher.canDeliver('unknown', 'onComplete')).toBe(false);
+ });
+ });
+
describe('unregister', () => {
it('should remove all hooks for an operation', () => {
dispatcher.register(operationId, [{ handler: vi.fn(), id: 'hook', type: 'onComplete' }]);
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
index b3260635b8f..8406084e138 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
@@ -92,6 +92,11 @@ export interface HeteroDispatchDeps {
*
* Stream-close / hook dispatch / metadata clear are best-effort: a failure
* there must not mask the original dispatch error the caller surfaces.
+ *
+ * Returns whether an `onComplete` consumer was there to be told. Callers hand
+ * that back to the invoker as `terminalReported` so a surface that renders
+ * failures itself (the IM bot bridge) can tell "the lifecycle already announced
+ * this" from "nobody did" — see {@link HookDispatcher.canDeliver}.
*/
const finalizeHeteroDispatchError = async (
deps: HeteroDispatchDeps,
@@ -110,7 +115,7 @@ const finalizeHeteroDispatchError = async (
operationId: string;
topicId: string;
},
-): Promise<void> => {
+): Promise<boolean> => {
const {
agentId,
assistantMessageId,
@@ -137,6 +142,10 @@ const finalizeHeteroDispatchError = async (
// onComplete/onError hooks (task lifecycle → task failed + IM bot callback).
// `skipErrorMessageWrite` keeps the bespoke device-specific bubble written
// in step 1; verify is done-only, so it no-ops on this error path.
+ // Read BEFORE dispatching: a settled lifecycle unregisters the operation's
+ // hooks, so asking afterwards can no longer tell "delivered" from "never
+ // had one".
+ const terminalReported = hookDispatcher.canDeliver(operationId, 'onComplete');
await new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId).completeOperation(
{
agentId,
@@ -175,6 +184,8 @@ const finalizeHeteroDispatchError = async (
} catch (err) {
log('finalizeHeteroDispatchError: clear runningOperation failed (non-fatal): %O', err);
}
+
+ return terminalReported;
};
/**
@@ -607,6 +618,10 @@ export const dispatchHeteroAgent = async (
);
if (!attached) {
const message = 'Group supervisor finished before this member could start.';
+ // Same contract as `finalizeHeteroDispatchError`: read the hook before the
+ // dispatch settles and unregisters it, so the caller learns whether this
+ // failure was already announced to its own surfaces.
+ const terminalReported = hookDispatcher.canDeliver(operationId, 'onComplete');
await new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId).completeOperation(
{
agentId: persistAgentId,
@@ -630,6 +645,7 @@ export const dispatchHeteroAgent = async (
operationId,
status: 'error',
success: false,
+ terminalReported,
timestamp: new Date().toISOString(),
topicId,
userMessageId: userMessageId ?? parentMessageId ?? '',
@@ -685,7 +701,7 @@ export const dispatchHeteroAgent = async (
};
if (agentConfig.agencyConfig?.heterogeneousProvider?.authMode === 'api') {
- await finalizeHeteroDispatchError(deps, {
+ const terminalReported = await finalizeHeteroDispatchError(deps, {
agentId: resolvedAgentId,
assistantMessageId,
detail: HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
@@ -703,6 +719,7 @@ export const dispatchHeteroAgent = async (
operationId,
status: 'error',
success: false,
+ terminalReported,
timestamp: new Date().toISOString(),
topicId,
userMessageId: userMessageId ?? parentMessageId ?? '',
@@ -723,7 +740,7 @@ export const dispatchHeteroAgent = async (
'execAgent: device access denied for remote hetero dispatch (reason=%s)',
deviceAccessReason,
);
- await finalizeHeteroDispatchError(deps, {
+ const terminalReported = await finalizeHeteroDispatchError(deps, {
agentId: resolvedAgentId,
assistantMessageId,
detail: 'This sender is not allowed to run agents on a bound device.',
@@ -741,6 +758,7 @@ export const dispatchHeteroAgent = async (
operationId,
status: 'error',
success: false,
+ terminalReported,
timestamp: new Date().toISOString(),
topicId,
userMessageId: userMessageId ?? parentMessageId ?? '',
@@ -748,7 +766,7 @@ export const dispatchHeteroAgent = async (
}
if (!remoteDeviceId) {
log('execAgent: openclaw/hermes requires a local or connected device');
- await finalizeHeteroDispatchError(deps, {
+ const terminalReported = await finalizeHeteroDispatchError(deps, {
agentId: resolvedAgentId,
assistantMessageId,
detail: 'No local or connected device is available for this agent.',
@@ -766,6 +784,7 @@ export const dispatchHeteroAgent = async (
operationId,
status: 'error',
success: false,
+ terminalReported,
timestamp: new Date().toISOString(),
topicId,
userMessageId: userMessageId ?? parentMessageId ?? '',
@@ -832,7 +851,7 @@ export const dispatchHeteroAgent = async (
);
if (!result.success) {
log('execAgent: remote hetero dispatch failed: %s', result.error);
- await finalizeHeteroDispatchError(deps, {
+ const terminalReported = await finalizeHeteroDispatchError(deps, {
agentId: resolvedAgentId,
assistantMessageId,
detail: result.error ?? 'Device dispatch failed',
@@ -853,6 +872,7 @@ export const dispatchHeteroAgent = async (
operationId,
status: 'error',
success: false,
+ terminalReported,
timestamp: new Date().toISOString(),
topicId,
userMessageId: userMessageId ?? parentMessageId ?? '',
@@ -911,7 +931,7 @@ export const dispatchHeteroAgent = async (
const dispatchDeviceId = heteroPlan.kind === 'device' ? heteroPlan.deviceId : undefined;
if (!dispatchDeviceId) {
log('execAgent: hetero executionTarget=device but no boundDeviceId set');
- await finalizeHeteroDispatchError(deps, {
+ const terminalReported = await finalizeHeteroDispatchError(deps, {
agentId: resolvedAgentId,
assistantMessageId,
detail: !supportsCloudHeterogeneousSandbox(heteroType)
@@ -931,6 +951,7 @@ export const dispatchHeteroAgent = async (
operationId,
status: 'error',
success: false,
+ terminalReported,
timestamp: new Date().toISOString(),
topicId,
userMessageId: userMessageId ?? parentMessageId ?? '',
@@ -1010,7 +1031,7 @@ export const dispatchHeteroAgent = async (
});
if (!result.success) {
log('execAgent: hetero device dispatch failed: %s', result.error);
- await finalizeHeteroDispatchError(deps, {
+ const terminalReported = await finalizeHeteroDispatchError(deps, {
agentId: resolvedAgentId,
assistantMessageId,
detail: result.error ?? 'Device dispatch failed',
@@ -1031,6 +1052,7 @@ export const dispatchHeteroAgent = async (
operationId,
status: 'error',
success: false,
+ terminalReported,
timestamp: new Date().toISOString(),
topicId,
userMessageId: userMessageId ?? parentMessageId ?? '',
@@ -1059,7 +1081,7 @@ export const dispatchHeteroAgent = async (
} else {
if (!supportsCloudHeterogeneousSandbox(heteroType)) {
const message = `${getHeterogeneousAgentTitle(heteroType)} requires a local or connected device; cloud sandbox execution is not supported.`;
- await finalizeHeteroDispatchError(deps, {
+ const terminalReported = await finalizeHeteroDispatchError(deps, {
agentId: resolvedAgentId,
assistantMessageId,
detail: message,
@@ -1077,6 +1099,7 @@ export const dispatchHeteroAgent = async (
operationId,
status: 'error',
success: false,
+ terminalReported,
timestamp: new Date().toISOString(),
topicId,
userMessageId: userMessageId ?? parentMessageId ?? '',
diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.ts
index 45cd537505a..ae65c7d710f 100644
--- a/apps/server/src/services/bot/AgentBridgeService.ts
+++ b/apps/server/src/services/bot/AgentBridgeService.ts
@@ -427,6 +427,14 @@ export class AgentBridgeService {
}
private async finishStartupFailure(params: {
+ /**
+ * The run's terminal lifecycle already fired its `onComplete` hooks, which
+ * include this bot's own completion callback (see `ExecAgentResult.
+ * terminalReported`). Posting here as well is what used to leave two error
+ * messages — the curated card and the callback's — in the same thread, so
+ * this path only cleans up and lets the callback own the reply.
+ */
+ alreadyReported?: boolean;
client?: PlatformClient;
error?: unknown;
operationId?: string;
@@ -437,6 +445,7 @@ export class AgentBridgeService {
userMessage: Message;
}): Promise<void> {
const {
+ alreadyReported,
client,
error,
operationId,
@@ -450,15 +459,23 @@ export class AgentBridgeService {
error instanceof Error ? error.message : error ? String(error) : 'Agent execution failed';
log(
- 'finishStartupFailure: thread=%s, operationId=%s, stopped=%s, error=%s',
+ 'finishStartupFailure: thread=%s, operationId=%s, stopped=%s, alreadyReported=%s, error=%s',
thread.id,
operationId,
stopped,
+ alreadyReported,
errorMessage,
);
AgentBridgeService.clearActiveThread(thread.id);
+ // A stop is ours to report either way: the completion callback renders an
+ // interrupted run, not this local "stopped" acknowledgement.
+ if (alreadyReported && !stopped) {
+ await this.clearReaction(thread, client);
+ return;
+ }
+
// Classify before rendering so a startup failure lands on curated copy
// (harness / provider / user tier) instead of a bare "Agent Execution
// Failed" that tells the user nothing — especially when the run died
@@ -1235,6 +1252,7 @@ export class AgentBridgeService {
if (!result.success) {
await this.finishStartupFailure({
+ alreadyReported: result.terminalReported,
client,
error: result.error,
operationId: result.operationId,
@@ -1628,12 +1646,18 @@ export class AgentBridgeService {
clearTimeout(timeout);
log(
- 'executeWithCallback[local]: startup failed, operationId=%s, error=%s',
+ 'executeWithCallback[local]: startup failed, operationId=%s, terminalReported=%s, error=%s',
result.operationId,
+ result.terminalReported,
result.error,
);
- if (progressMessage) {
+ // The terminal lifecycle already ran this failure through the
+ // in-process `bot-completion` hook below, which edits the very same
+ // progress message. Rendering here too would just overwrite its
+ // (better-classified) copy — or, with no placeholder to edit, add a
+ // second error message to the thread.
+ if (progressMessage && !result.terminalReported) {
try {
await progressMessage.edit({
markdown: renderThrownAgentError(result.error, result.operationId, replyLocale),
diff --git a/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts b/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts
index d154734f594..aed92e56074 100644
--- a/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts
+++ b/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts
@@ -909,4 +909,58 @@ describe('AgentBridgeService', () => {
});
});
});
+ describe('startup failure reporting', () => {
+ // A hetero dispatch failure (device offline, no bound device, sandbox spawn
+ // rejected) finalizes the run through CompletionLifecycle — which fires the
+ // `bot-completion` hook — AND returns `success: false`. Reporting it here as
+ // well put two error messages in the same IM thread (#19676 follow-up).
+ const createProgressThread = () => {
+ const edit = vi.fn().mockResolvedValue(undefined);
+ const thread = createThread();
+ thread.post = vi.fn().mockResolvedValue({ edit, id: 'progress-msg-1' });
+ return { edit, thread };
+ };
+
+ const failedStartup = (extra?: Record<string, unknown>) => ({
+ assistantMessageId: 'assistant-msg-1',
+ createdAt: new Date().toISOString(),
+ error: 'DEVICE_NOT_FOUND (HTTP 404)',
+ operationId: 'op-1',
+ success: false,
+ topicId: 'topic-1',
+ ...extra,
+ });
+
+ it('stays silent when the terminal lifecycle already reported the failure', async () => {
+ mockExecAgent.mockResolvedValue(failedStartup({ terminalReported: true }));
+ const { edit, thread } = createProgressThread();
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+
+ await service.handleMention(thread, createMessage(), {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client: createClient(),
+ });
+
+ // Only the "Processing..." placeholder — the completion callback owns the
+ // error reply and edits that same message.
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(edit).not.toHaveBeenCalled();
+ });
+
+ it('reports a startup failure that reached no completion hook', async () => {
+ mockExecAgent.mockResolvedValue(failedStartup());
+ const { edit, thread } = createProgressThread();
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+
+ await service.handleMention(thread, createMessage(), {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client: createClient(),
+ });
+
+ expect(edit).toHaveBeenCalledTimes(1);
+ expect(edit.mock.calls[0][0].markdown).toContain('Operation ID');
+ });
+ });
});
diff --git a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts b/apps/server/src/services/bot/__tests__/replyTemplate.test.ts
index dcfd2fd724e..0a9c99264b4 100644
--- a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts
+++ b/apps/server/src/services/bot/__tests__/replyTemplate.test.ts
@@ -399,6 +399,25 @@ describe('replyTemplate', () => {
expect(output).not.toContain('secret upstream payload');
});
+ it('names the unreachable device instead of falling to the legacy tier', () => {
+ // A hetero dispatch failure (device offline / unregistered / no gateway)
+ // reaches the bot as `DeviceGatewayNotConfigured` with no attribution, so
+ // without its own mapping it rendered a bare "Agent Execution Failed".
+ const output = renderAgentError(
+ 'DeviceGatewayNotConfigured',
+ '{"error":"DEVICE_NOT_FOUND","success":false}',
+ 'op-device',
+ );
+ expect(output).toContain("Couldn't reach the device this agent runs on");
+ expect(output).toContain('op-device');
+ expect(output).not.toContain('Agent Execution Failed');
+ expect(output).not.toContain('DEVICE_NOT_FOUND');
+
+ const zh = renderAgentError('DeviceGatewayNotConfigured', undefined, 'op-device', 'zh-CN');
+ expect(zh).toContain('无法连接到运行该 Agent 的设备');
+ expect(zh).not.toContain('Agent 执行失败');
+ });
+
it('classifies a legacy envelope before choosing IM copy', () => {
const output = renderAgentError('ProviderBizError', 'insufficient quota', 'op-quota');
expect(output).toContain('Provider quota exhausted');
diff --git a/apps/server/src/services/bot/replyTemplate.ts b/apps/server/src/services/bot/replyTemplate.ts
index d1b6d1103e2..c429e6356cb 100644
--- a/apps/server/src/services/bot/replyTemplate.ts
+++ b/apps/server/src/services/bot/replyTemplate.ts
@@ -260,6 +260,7 @@ type SystemStrings = {
errorInvalidProviderAPIKey: string;
errorCommandConnectionClosed: string;
errorContentModeration: string;
+ errorDeviceUnreachable: string;
errorEmptyCompletion: string;
errorModelRefusal: string;
errorHarnessInternal: string;
@@ -370,6 +371,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.",
+ 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:
"**The model provider returned an empty response.**\nEven without visible content, this request may still incur charges. You can retry, or switch models in the agent's settings and try again.",
errorModelRefusal:
@@ -494,6 +497,8 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {
'**命令会话已断开**\nAgent 在完成前丢失了命令连接。请重试;如果该问题持续出现,请检查 sandbox 或设备连接,并结合 Operation ID 查看服务端日志。',
errorContentModeration:
'**被内容安全策略拦截**\n模型 Provider 的安全策略拒绝了本次请求或回复。请调整内容后重试。',
+ errorDeviceUnreachable:
+ '**无法连接到运行该 Agent 的设备**\n本次执行没有启动。请确认 LobeHub 桌面端(或 `lh` CLI)正在运行且已连接后重试,也可以在 Agent 设置中改绑其他在线设备。',
errorEmptyCompletion:
'**模型供应商返回了空内容**\n即使没有可显示的内容,本次请求仍可能产生费用。你可以重试,或在 Agent 设置中切换模型后再试。',
errorModelRefusal:
@@ -588,6 +593,11 @@ export function renderError(operationId?: string, lng?: BotReplyLocale): string
const FRIENDLY_ERROR_BY_TYPE: Record<string, keyof SystemStrings> = {
// ── user-fixable config / input (attribution: user) ──
ContentModeration: 'errorContentModeration',
+ // Every "we could not reach a run device" flavour (gateway unconfigured,
+ // device offline, registration gone) arrives under this one type — see
+ // `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',
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 them
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 05c5dbc4998..e6b3cee0dee 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -339,6 +339,20 @@ export interface ExecAgentResult {
status: string;
/** Whether the operation was created successfully */
success: boolean;
+ /**
+ * The failure was already announced through the run's terminal lifecycle —
+ * `CompletionLifecycle` fired its `onComplete` hooks, so every consumer of
+ * those hooks (IM bot completion callback, task lifecycle) has been told.
+ *
+ * Callers that render failures themselves must not report it a second time:
+ * a hetero dispatch failure finalizes the run AND returns `success: false`,
+ * which used to put two error messages in the same IM thread. Absent /
+ * `false` means no hook consumer was reachable, so the caller owns the
+ * report — as it still does when delivery itself fails, because a hook with
+ * no fallback throws `CriticalHookDeliveryError` out of `execAgent` instead
+ * of resolving to this result.
+ */
+ terminalReported?: boolean;
/** ISO timestamp */
timestamp: string;
/** Short-lived JWT token for Gateway WebSocket authentication */