🤯 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(agent): prevent the inbox agent from turning into a heterogeneous agent (#17369)
Arvin Xu4ee3ea23311e
diff --git a/.agents/acceptance/scripts/init-dev-env.sh b/.agents/acceptance/scripts/init-dev-env.shindex 6b970fd9234..08018aa63af 100755--- a/.agents/acceptance/scripts/init-dev-env.sh+++ b/.agents/acceptance/scripts/init-dev-env.sh@@ -457,6 +457,21 @@ const client = new pg.Client({ connectionString: databaseUrl });],);+ // Self-heal the inbox agent: a prior test run (e.g. `lh agent edit --slug inbox`)+ // can turn the built-in default cloud agent into a heterogeneous (external-CLI)+ // one, which then fails every run with GATEWAY_NOT_CONFIGURED. Reset any polluted+ // inbox row for the test user back to a clean cloud default. Idempotent — a+ // healthy inbox never matches the `heterogeneousProvider` filter.+ const inboxReset = await client.query(+ `UPDATE agents+ SET provider = NULL, model = NULL, agency_config = NULL, updated_at = now()+ WHERE user_id = $1 AND slug = 'inbox' AND agency_config ? 'heterogeneousProvider'`,+ [TEST_USER.id],+ );+ if (inboxReset.rowCount > 0) {+ console.log(`reset ${inboxReset.rowCount} polluted inbox agent(s) back to cloud default`);+ }+const cliEnvFile = writeCliEnvFile();console.log('seeded baseline user:');diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex b599f883619..abafa81595d 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -24,7 +24,7 @@ import {} from '@lobechat/builtin-tool-self-iteration';import { TaskIdentifier } from '@lobechat/builtin-tool-task';import { builtinTools, manualModeExcludeToolIds } from '@lobechat/builtin-tools';-import { LOADING_FLAT } from '@lobechat/const';+import { isHeterogeneousAgentModelId, LOADING_FLAT } from '@lobechat/const';import {type AgentGroupConfig,type AgentManagementContext,@@ -44,6 +44,7 @@ import type {ChatFileItem,ChatTopicBotContext,ChatVideoItem,+ ErrorType,ExecAgentParams,ExecAgentResult,ExecGroupAgentParams,@@ -62,6 +63,7 @@ import type {} from '@lobechat/types';import {buildHeteroExecArgs,+ ChatErrorType,getActivePluginIds,getDisabledPluginIds,getWorkingDirEffectivePath,@@ -469,6 +471,33 @@ interface ResolvedWorkspaceInit {workspace: WorkspaceInitResult;}+/**+ * Turn a raw device-gateway dispatch error code into a human-readable headline.+ * The gateway returns terse machine codes (e.g. `GATEWAY_NOT_CONFIGURED`) which,+ * surfaced verbatim, render as a cryptic error card. We rewrite the headline the+ * caller keeps for non-web surfaces (IM bots) while retaining the raw code in+ * `detail` for diagnostics. Web clients localize via the mapped error type below.+ */+const HETERO_DISPATCH_ERROR_HEADLINES: Record<string, string> = {+ 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.",+};++const humanizeHeteroDispatchError = (raw?: string): string =>+ (raw && HETERO_DISPATCH_ERROR_HEADLINES[raw]) || raw || 'Device dispatch failed';++/**+ * Map a raw dispatch code to a dedicated `ChatErrorType` so the web client renders+ * its own localized headline (the generic `ServerAgentRuntimeError` copy would+ * otherwise mask the specific message). Unknown codes keep the generic type.+ */+const HETERO_DISPATCH_ERROR_TYPES: Record<string, ErrorType> = {+ GATEWAY_NOT_CONFIGURED: ChatErrorType.DeviceGatewayNotConfigured,+};++const resolveHeteroDispatchErrorType = (raw?: string): ErrorType =>+ (raw && HETERO_DISPATCH_ERROR_TYPES[raw]) || ChatErrorType.ServerAgentRuntimeError;+/*** AI Agent Service*@@ -591,17 +620,31 @@ export class AiAgentService {agentId?: string;assistantMessageId: string;detail: string;+ /**+ * Client error type. Defaults to the generic `ServerAgentRuntimeError`; pass a+ * dedicated `ChatErrorType` (e.g. `DeviceGatewayNotConfigured`) so the web+ * client renders a specific localized headline instead of the generic copy.+ */+ errorType?: ErrorType;message: string;operationId: string;topicId: string;}): Promise<void> {- const { agentId, assistantMessageId, detail, message, operationId, topicId } = params;+ const {+ agentId,+ assistantMessageId,+ detail,+ errorType = ChatErrorType.ServerAgentRuntimeError,+ message,+ operationId,+ topicId,+ } = params;// 1. Error bubble — written first so a stream subscriber reacting to the// end event below re-reads a message that already carries the error.await this.messageModel.update(assistantMessageId, {content: '',- error: { body: { detail }, message, type: 'ServerAgentRuntimeError' },+ error: { body: { detail }, message, type: errorType },});// 1b. Finalize the run through CompletionLifecycle's single entry — the SAME@@ -616,7 +659,7 @@ export class AiAgentService {{agentId,assistantMessageId,- error: { message, type: 'ServerAgentRuntimeError' },+ error: { message, type: errorType },operationId,serializedHooks: hookDispatcher.getSerializedHooks(operationId),topicId,@@ -1634,10 +1677,10 @@ export class AiAgentService {// `agentNotify.notify` (openclaw / hermes).//// Detection: prefer agencyConfig.heterogeneousProvider.type (set by the UI),- // fall back to model field for backwards compatibility.- const HETERO_AGENT_MODELS = new Set<string>(['amp', 'claude-code', 'codex', 'opencode']);+ // fall back to the legacy `model` field for backwards compatibility (shared+ // with the inbox write guard via `isHeterogeneousAgentModelId`).const heteroProviderType = agentConfig.agencyConfig?.heterogeneousProvider?.type;- const isHeteroAgent = !!heteroProviderType || HETERO_AGENT_MODELS.has(model);+ const isHeteroAgent = !!heteroProviderType || isHeterogeneousAgentModelId(model);const heteroType = (heteroProviderType ?? model) as'amp' | 'claude-code' | 'codex' | 'hermes' | 'openclaw' | 'opencode';@@ -2083,7 +2126,8 @@ export class AiAgentService {agentId: resolvedAgentId,assistantMessageId: assistantMessageRecord.id,detail: result.error ?? 'Device dispatch failed',- message: result.error ?? 'Device dispatch failed',+ errorType: resolveHeteroDispatchErrorType(result.error),+ message: humanizeHeteroDispatchError(result.error),operationId,topicId,});@@ -2247,7 +2291,8 @@ export class AiAgentService {agentId: resolvedAgentId,assistantMessageId: assistantMessageRecord.id,detail: result.error ?? 'Device dispatch failed',- message: result.error ?? 'Device dispatch failed',+ errorType: resolveHeteroDispatchErrorType(result.error),+ message: humanizeHeteroDispatchError(result.error),operationId,topicId,});diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex e66cf4805a7..952065d0e6c 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -67,6 +67,7 @@"response.522": "We apologize, the server connection timed out and was unable to respond to your request in a timely manner. This may be due to an unstable network or the server being temporarily inaccessible. Please try again later; we are working to restore service.","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.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 e9c8d3b53da..edc6a258c69 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -67,6 +67,7 @@"response.522": "连接超时(可能网络不稳定或服务暂不可达),请稍后再试","response.524": "等待上游响应超时,请稍后再试","response.CreateMessageError": "消息未能发送。建议先复制内容再重试;刷新页面后该消息不会保留",+ "response.DeviceGatewayNotConfigured": "无法连接到运行此智能体的设备。请先连接设备,或在服务端配置设备网关,然后重试。","response.ExceededContextWindowCloud": "当前对话内容过长,无法继续处理。请编辑最后一条消息减少输入内容或者删除一些消息重试。","response.FreePlanLimit": "当前计划不支持该功能。请升级到付费计划后继续","response.GoogleAIBlockReason.BLOCKLIST": "内容包含被屏蔽的词语。请重新措辞后再试。",diff --git a/packages/const/src/heterogeneousAgent.ts b/packages/const/src/heterogeneousAgent.tsindex 85d670bb035..fbc0b25af43 100644--- a/packages/const/src/heterogeneousAgent.ts+++ b/packages/const/src/heterogeneousAgent.ts@@ -1,3 +1,19 @@/** Model instruction used when resuming an interrupted Claude Code or Codex session. */export const HETERO_CONTINUE_PROMPT ='Continue the task from where it stopped. The transcript above shows the work already completed — do not redo it.';++/**+ * Legacy heterogeneous-agent model IDs. Before `agencyConfig.heterogeneousProvider`+ * existed, an agent was routed to the external-CLI / device execution path purely+ * by its `model` matching one of these. `AiAgentService` still honors this fallback,+ * so a stray `model: 'claude-code'` alone makes an agent heterogeneous — any guard+ * that keeps an agent on the cloud path must sanitize the model too, not just the+ * provider config.+ */+export const HETEROGENEOUS_AGENT_MODEL_IDS = ['amp', 'claude-code', 'codex', 'opencode'] as const;++const HETEROGENEOUS_AGENT_MODEL_ID_SET = new Set<string>(HETEROGENEOUS_AGENT_MODEL_IDS);++/** Whether a bare `model` value identifies a legacy heterogeneous agent runtime. */+export const isHeterogeneousAgentModelId = (model?: string | null): boolean =>+ !!model && HETEROGENEOUS_AGENT_MODEL_ID_SET.has(model);diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex 1a96beba61a..91f06bfc027 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -1257,6 +1257,90 @@ describe('AgentModel', () => {expect(result?.tags).toEqual([]);expect(result?.model).toBe('gpt-4');});++ it('should strip heterogeneousProvider when updating the inbox agent', async () => {+ // The inbox is the built-in default cloud agent; a stray+ // heterogeneousProvider (e.g. from a CLI `agent edit --slug inbox`) would+ // reroute the whole chat surface through the device gateway and break with+ // GATEWAY_NOT_CONFIGURED.+ const agent = await serverDB+ .insert(agents)+ .values({ slug: INBOX_SESSION_ID, userId })+ .returning()+ .then((res) => res[0]);++ await agentModel.updateConfig(agent.id, {+ agencyConfig: {+ heterogeneousProvider: { command: 'claude', type: 'claude-code' },+ },+ model: 'gpt-4', // non-protected field should still be applied+ } as any);++ const result = await serverDB.query.agents.findFirst({+ where: eq(agents.id, agent.id),+ });++ expect((result?.agencyConfig as any)?.heterogeneousProvider).toBeUndefined();+ expect(result?.model).toBe('gpt-4');+ });++ it('should keep heterogeneousProvider for non-inbox agents', async () => {+ const agent = await serverDB+ .insert(agents)+ .values({ slug: 'my-claude-code', userId })+ .returning()+ .then((res) => res[0]);++ await agentModel.updateConfig(agent.id, {+ agencyConfig: {+ heterogeneousProvider: { command: 'claude', type: 'claude-code' },+ },+ } as any);++ const result = await serverDB.query.agents.findFirst({+ where: eq(agents.id, agent.id),+ });++ expect((result?.agencyConfig as any)?.heterogeneousProvider).toEqual({+ command: 'claude',+ type: 'claude-code',+ });+ });++ it('should reset a legacy heterogeneous model id on the inbox agent', async () => {+ // A bare `model: 'claude-code'` (no heterogeneousProvider) is enough to make+ // AiAgentService route the run to the device/sandbox path, so the inbox guard+ // must sanitize the model too.+ const agent = await serverDB+ .insert(agents)+ .values({ slug: INBOX_SESSION_ID, userId })+ .returning()+ .then((res) => res[0]);++ await agentModel.updateConfig(agent.id, { model: 'claude-code' } as any);++ const result = await serverDB.query.agents.findFirst({+ where: eq(agents.id, agent.id),+ });++ expect(result?.model).toBeNull();+ });++ it('should keep a legacy heterogeneous model id for non-inbox agents', async () => {+ const agent = await serverDB+ .insert(agents)+ .values({ slug: 'my-claude-code', userId })+ .returning()+ .then((res) => res[0]);++ await agentModel.updateConfig(agent.id, { model: 'claude-code' } as any);++ const result = await serverDB.query.agents.findFirst({+ where: eq(agents.id, agent.id),+ });++ expect(result?.model).toBe('claude-code');+ });});describe('create', () => {diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex 5a3e419d68a..820abd6120f 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -1,5 +1,5 @@import { BUILTIN_AGENT_SLUGS, getAgentPersistConfig } from '@lobechat/builtin-agents';-import { INBOX_SESSION_ID } from '@lobechat/const';+import { INBOX_SESSION_ID, isHeterogeneousAgentModelId } from '@lobechat/const';import type { AgentRankItem, LobeAgentAgencyConfig } from '@lobechat/types';import { pruneWorkingDirByDeviceDeletes } from '@lobechat/types';import { TRPCError } from '@trpc/server';@@ -1102,6 +1102,23 @@ export class AgentModel {const mergedValue = merge(agent, restData);+ // The inbox is LobeHub's built-in default cloud agent; it must never be+ // turned into a heterogeneous (external-CLI) agent. Two independent inputs can+ // flip it — a stray `agencyConfig.heterogeneousProvider`, and a legacy hetero+ // `model` id (amp / claude-code / codex / opencode), which AiAgentService still+ // treats as heterogeneous on its own even without a provider config. Either one+ // reroutes the whole chat surface through the device gateway and breaks it with+ // GATEWAY_NOT_CONFIGURED, so sanitize both at this write chokepoint regardless+ // of caller (mirrors AGENT_BUILDER_PROTECTED_FIELDS).+ if (agent.slug === INBOX_SESSION_ID) {+ if (mergedValue.agencyConfig?.heterogeneousProvider) {+ delete mergedValue.agencyConfig.heterogeneousProvider;+ }+ if (isHeterogeneousAgentModelId(mergedValue.model)) {+ mergedValue.model = null;+ }+ }+// Apply the processed parametersmergedValue.params = Object.keys(updatedParams).length > 0 ? updatedParams : undefined;diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex 773f44875df..a629e87b84d 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -170,6 +170,8 @@ export default {'Repeated content policy rejections detected. Please revise your prompt before retrying.','response.ProviderImageContentModerationWarning':'Repeated image safety rejections detected. Similar prompts may temporarily pause image generation.',+ '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.ServerAgentRuntimeError':'Sorry, the Agent service is currently unavailable. Please try again later or contact us via email for support.','response.SubscriptionKeyMismatch':diff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.tsindex fd530f8e132..50dcb77d674 100644--- a/packages/types/src/fetch.ts+++ b/packages/types/src/fetch.ts@@ -26,6 +26,7 @@ export const ChatErrorType = {UnknownChatFetchError: 'UnknownChatFetchError',SystemTimeNotMatchError: 'SystemTimeNotMatchError',ServerAgentRuntimeError: 'ServerAgentRuntimeError',+ DeviceGatewayNotConfigured: 'DeviceGatewayNotConfigured', // Heterogeneous agent has no reachable run device / gateway// ******* Client Errors ******* //BadRequest: 400,