🤯 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-agent): surface cloud auth failures (#18035)
Arvin Xuec9ba6f95e9f
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.tsindex 2646feda5a2..f62e9afd5c5 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts@@ -10,7 +10,11 @@ import type { AgentHook, SerializedHook } from '@/server/services/agentRuntime/himport * as verifyService from '@/server/services/verify';import type { HeterogeneousPersistenceHandler } from '..';-import { HeterogeneousAgentService, StaleHeteroOperationError } from '..';+import {+ HeterogeneousAgentService,+ normalizeHeterogeneousFinishError,+ StaleHeteroOperationError,+} from '..';import { HeteroTraceRecorder } from '../HeteroTraceRecorder';// Force queue/production mode so the terminal funnel takes the serialized-webhook@@ -83,6 +87,48 @@ const createService = (overrides: { streamEventManager?: IStreamEventManager } =};describe('HeterogeneousAgentService', () => {+ describe('normalizeHeterogeneousFinishError', () => {+ it('classifies a flattened Claude Code login failure for the frontend status guide', () => {+ expect(+ normalizeHeterogeneousFinishError('claude-code', {+ message: 'Not logged in · Please run /login',+ type: 'AgentRuntimeError',+ }),+ ).toMatchObject({+ body: {+ agentType: 'claude-code',+ code: 'auth_required',+ stderr: 'Not logged in · Please run /login',+ },+ type: 'AgentRuntimeError',+ });+ });++ it('classifies auth details nested in a flattened error body', () => {+ expect(+ normalizeHeterogeneousFinishError('claude-code', {+ body: { stderr: 'Not logged in. Please run /login' },+ message: 'Agent execution failed',+ type: 'AgentRuntimeError',+ }),+ ).toMatchObject({ body: { agentType: 'claude-code', code: 'auth_required' } });+ });++ it('preserves an existing structured status-guide error', () => {+ const error = {+ body: {+ agentType: 'claude-code',+ code: 'auth_required',+ message: 'existing',+ },+ message: 'existing',+ type: 'AgentRuntimeError',+ };++ expect(normalizeHeterogeneousFinishError('claude-code', error)).toBe(error);+ });+ });+describe('heteroIngest', () => {it('republishes every event through the stream manager preserving ordering', async () => {const { manager, published, service } = createService();@@ -378,6 +424,32 @@ describe('HeterogeneousAgentService', () => {expect(published[0].event.data.sessionId).toBeUndefined();});+ it('persists and publishes a structured auth_required error from a flattened finish', async () => {+ const { persistenceHandler, published, service } = createService();++ await service.heteroFinish({+ agentType: 'claude-code',+ error: { message: 'Not logged in · Please run /login', type: 'AgentRuntimeError' },+ operationId: 'op-auth',+ result: 'error',+ topicId: 'topic-auth',+ });++ expect(persistenceHandler.finish).toHaveBeenCalledWith(+ expect.objectContaining({+ error: expect.objectContaining({+ body: expect.objectContaining({+ agentType: 'claude-code',+ code: 'auth_required',+ }),+ }),+ }),+ );+ expect(published[0].event.data.error).toMatchObject({+ body: { agentType: 'claude-code', code: 'auth_required' },+ });+ });+it('handles cancelled runs and runs without sessionId', async () => {const { published, service } = createService();diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 68dd42efb4f..68583922674 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -1,7 +1,11 @@import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { type ISnapshotStore, parseOperationId } from '@lobechat/agent-tracing';import type { LobeChatDatabase } from '@lobechat/database';-import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import {+ classifyHeteroProcessFailure,+ isHeteroStatusGuideErrorData,+ type LocalHeterogeneousAgentType,+} from '@lobechat/heterogeneous-agents';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -57,6 +61,39 @@ export interface HeterogeneousFinishParams {topicId: string;}+type HeterogeneousFinishError = NonNullable<HeterogeneousFinishParams['error']>;++/**+ * Older or partially upgraded `lh hetero exec` producers can flatten an+ * adapter-classified terminal error before calling `heteroFinish`. Reclassify+ * the final payload at the server boundary so a recognizable authentication+ * failure always reaches the message row as the structured status-guide shape+ * (`body.agentType + body.code`) the web client renders.+ */+export const normalizeHeterogeneousFinishError = (+ agentType: HeterogeneousAgentType,+ error: HeterogeneousFinishError | undefined,+): HeterogeneousFinishError | undefined => {+ if (!error || isHeteroStatusGuideErrorData(error.body)) return error;++ const body = error.body;+ const bodyDetails = body+ ? [body.message, body.error, body.stderr]+ .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)+ .join('\n')+ : '';+ const detail = [error.message, bodyDetails].filter(Boolean).join('\n');+ const classified = classifyHeteroProcessFailure({ agentType, detail });++ if (!classified) return error;++ return {+ body: { ...classified },+ message: classified.message,+ type: 'AgentRuntimeError',+ };+};+export interface HeterogeneousAgentServiceOptions {/** Inject a pre-built persistence handler (used by tests). */persistenceHandler?: HeterogeneousPersistenceHandler;@@ -191,7 +228,8 @@ export class HeterogeneousAgentService {}async heteroFinish(params: HeterogeneousFinishParams): Promise<void> {- const { agentType, error, operationId, result, sessionId, topicId } = params;+ const { agentType, operationId, result, sessionId, topicId } = params;+ const error = normalizeHeterogeneousFinishError(agentType, params.error);log('heteroFinish: user=%s topic=%s op=%s type=%s result=%s sessionId=%s',@@ -203,6 +241,17 @@ export class HeterogeneousAgentService {sessionId ?? '<none>',);+ if (error?.body?.code === 'auth_required') {+ log(+ 'heteroFinish: authentication required user=%s topic=%s op=%s type=%s detail=%s',+ this.userId,+ topicId,+ operationId,+ agentType,+ error.body.stderr ?? error.message,+ );+ }+// Drain any pending state in the persistence handler — flushes trailing// accumulated content / reasoning that the in-stream `agent_runtime_end`// already wrote (no-op when state is clean), persists the CLI's nativediff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 2f190f71643..ba61b597e28 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -97,9 +97,11 @@"claudeCodeInstallGuide.reason": "LobeHub could not start Claude Code: {{message}}","claudeCodeInstallGuide.title": "Install Claude Code CLI","clearCurrentMessages": "Clear current conversation messages",+ "cliAuthGuide.actions.openCloudCredentials": "Update Cloud Token","cliAuthGuide.actions.openDocs": "Open Sign-in Guide","cliAuthGuide.actions.openSystemTools": "Open System Tools","cliAuthGuide.afterLogin": "After signing in again or refreshing credentials, retry your message. You can also re-detect in System Tools.",+ "cliAuthGuide.cloudAfterUpdate": "Claude Code rejected the cloud credential. Generate a new token with `claude setup-token`, update it in the agent profile, then retry your message.","cliAuthGuide.desc": "{{name}} could not continue because its sign-in session expired or the credentials are invalid.","cliAuthGuide.errorDetails": "Error details","cliAuthGuide.runCommand": "Run this in Terminal",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 439d7cf1732..a5d5c544f2d 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -97,9 +97,11 @@"claudeCodeInstallGuide.reason": "LobeHub 无法启动 Claude Code:{{message}}","claudeCodeInstallGuide.title": "安装 Claude Code CLI","clearCurrentMessages": "清空当前会话消息",+ "cliAuthGuide.actions.openCloudCredentials": "更新云端 Token","cliAuthGuide.actions.openDocs": "打开登录指南","cliAuthGuide.actions.openSystemTools": "打开系统工具","cliAuthGuide.afterLogin": "重新登录或更新凭证后,请重试刚才的消息。你也可以去系统工具里重新检测。",+ "cliAuthGuide.cloudAfterUpdate": "Claude Code 拒绝了云端凭证。请运行 `claude setup-token` 生成新 Token,在 Agent 配置中更新后重试。","cliAuthGuide.desc": "{{name}} 当前无法继续运行,可能是登录态已失效,或凭证已经不可用。","cliAuthGuide.errorDetails": "错误详情","cliAuthGuide.runCommand": "在终端执行",diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex 25a4f750d25..ca55046eaf4 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -68,7 +68,10 @@ export type {export { createMainAgentRunState, reduceMainAgent } from './mainAgentCoordinator';export { createAdapter, listAgentTypes, listLocalAgentTypes } from './registry';export type { HeterogeneousAgentScanMap, HeterogeneousAgentScanStatus } from './scan/types';-export { isHeteroStatusGuideErrorData } from './spawn/classifyProcessFailure';+export {+ classifyHeteroProcessFailure,+ isHeteroStatusGuideErrorData,+} from './spawn/classifyProcessFailure';export type {CreateMessageIntent,CreateThreadIntent,diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.tsindex 0a8712161c4..64d3a1e1601 100644--- a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts@@ -154,6 +154,15 @@ describe('classifyHeteroProcessFailure', () => {).toBeUndefined();});+ it('classifies Claude Code not-logged-in output without relying on the adapter', () => {+ expect(+ classifyHeteroProcessFailure({+ agentType: 'claude-code',+ detail: 'Not logged in · Please run /login',+ }),+ ).toMatchObject({ agentType: 'claude-code', code: 'auth_required' });+ });+it('does NOT treat an in-run ENOENT (no spawn context) as cli_not_found', () => {const result = classifyHeteroProcessFailure({agentType: 'claude-code',diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 5707e401c3a..57aa479470e 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -725,9 +725,12 @@ export default {'claudeCodeInstallGuide.reason': 'LobeHub could not start Claude Code: {{message}}','claudeCodeInstallGuide.title': 'Install Claude Code CLI','cliAuthGuide.actions.openDocs': 'Open Sign-in Guide',+ 'cliAuthGuide.actions.openCloudCredentials': 'Update Cloud Token','cliAuthGuide.actions.openSystemTools': 'Open System Tools','cliAuthGuide.afterLogin':'After signing in again or refreshing credentials, retry your message. You can also re-detect in System Tools.',+ 'cliAuthGuide.cloudAfterUpdate':+ 'Claude Code rejected the cloud credential. Generate a new token with `claude setup-token`, update it in the agent profile, then retry your message.','cliAuthGuide.desc':'{{name}} could not continue because its sign-in session expired or the credentials are invalid.','cliAuthGuide.errorDetails': 'Error details',diff --git a/packages/types/src/agent/heterogeneousAgent.ts b/packages/types/src/agent/heterogeneousAgent.tsindex c8b53adb6a9..f45d681e6bc 100644--- a/packages/types/src/agent/heterogeneousAgent.ts+++ b/packages/types/src/agent/heterogeneousAgent.ts@@ -70,7 +70,11 @@ export const HETEROGENEOUS_AGENT_CONFIGS = [docsUrl: 'https://docs.anthropic.com/en/docs/claude-code/setup',errorMessage:'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',- patterns: COMMON_AUTH_REQUIRED_PATTERNS,+ // Current Claude Code builds can emit this as plain process output before+ // the structured result event reaches the adapter. Keep it in the shared+ // process classifier so server-side `heteroFinish` can still recover the+ // dedicated auth-required error card from a flattened payload.+ patterns: [...COMMON_AUTH_REQUIRED_PATTERNS, 'not logged in'],signInCommand: 'claude',},defaultCommand: 'claude',diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 42792b0a472..e394bb11963 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -1,3 +1,4 @@+import { isDesktop } from '@lobechat/const';import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import { type ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';import { AgentRuntimeErrorType, getErrorCodeSpec } from '@lobechat/model-runtime';@@ -341,6 +342,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(const activeTopicScheduled = useChatStore((s) => topicSelectors.currentActiveTopic(s)?.status === 'scheduled',);+ const activeAgentId = useChatStore((s) => s.activeAgentId);const scheduledResetsAt = useChatStore((s) => {const scheduledRun = topicSelectors.currentActiveTopic(s)?.metadata?.scheduledRun;return scheduledRun?.kind === 'resume_after_rate_limit'@@ -381,8 +383,16 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(error={sessionErrorBody}schedule={schedule}onDismiss={() => void updateMessageError(data.id, null)}- onOpenSystemTools={() => navigate('/settings/system-tools')}onRetry={handleManualRetry}+ onOpenSystemTools={() =>+ navigate(+ isDesktop+ ? '/settings/system-tools'+ : activeAgentId+ ? `/agent/${activeAgentId}/profile`+ : '/settings/credential',+ )+ }/>);}diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/AuthRequiredState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/AuthRequiredState.tsxindex 3a26d996a48..f4a051b1e14 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/AuthRequiredState.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/AuthRequiredState.tsx@@ -1,3 +1,4 @@+import { isDesktop } from '@lobechat/const';import { Flexbox, Highlighter, Snippet, Text } from '@lobehub/ui';import { useTranslation } from 'react-i18next';@@ -25,7 +26,11 @@ const AuthRequiredState = ({showDocsdocsUrl={docsUrl}openDocsLabel={t('cliAuthGuide.actions.openDocs')}- openSystemToolsLabel={t('cliAuthGuide.actions.openSystemTools')}+ openSystemToolsLabel={t(+ isDesktop+ ? 'cliAuthGuide.actions.openSystemTools'+ : 'cliAuthGuide.actions.openCloudCredentials',+ )}onOpenSystemTools={onOpenSystemTools}/>}@@ -33,15 +38,17 @@ const AuthRequiredState = ({<Text type="secondary">{t('cliAuthGuide.desc', { name: config.title })}</Text>}>- <Flexbox gap={6}>- <Text strong style={{ fontSize: 12 }}>- {t('cliAuthGuide.runCommand')}- </Text>- <Snippet language={'bash'}>{config.signInCommand}</Snippet>- </Flexbox>+ {isDesktop && (+ <Flexbox gap={6}>+ <Text strong style={{ fontSize: 12 }}>+ {t('cliAuthGuide.runCommand')}+ </Text>+ <Snippet language={'bash'}>{config.signInCommand}</Snippet>+ </Flexbox>+ )}<Text style={{ fontSize: 12 }} type="secondary">- {t('cliAuthGuide.afterLogin')}+ {t(isDesktop ? 'cliAuthGuide.afterLogin' : 'cliAuthGuide.cloudAfterUpdate')}</Text>{rawErrorDetails && (